Checkpoint stats equipment and control catalog implementation
This commit is contained in:
+26
-12
@@ -56,7 +56,8 @@ from network interest. The server retains mutation deltas across chunk eviction.
|
||||
The finite circular world, 48-unit spawn separation, 100-character capacity,
|
||||
combat numbers, terrain details, mob scaling, and respawn periods are provisional
|
||||
defaults. They are not newly confirmed design decisions. Balance is validated and
|
||||
persisted with the world; editing YAML affects newly created world IDs only.
|
||||
persisted with the world. YAML initializes new worlds; Control publishes a shared,
|
||||
versioned title/equipment/stat catalog that world owners apply and checkpoint.
|
||||
|
||||
## Durability and ownership
|
||||
|
||||
@@ -92,12 +93,13 @@ checkpoints, versioned migrations, and crash/latency fault injection.
|
||||
## Progression and permanent titles
|
||||
|
||||
The Go simulation awards character XP for successful gathering, crafting, mob
|
||||
kills, and the boss killing blow. Each crossed level threshold banks stat points;
|
||||
there is no allocation intent until the stat design is defined. Levels, XP,
|
||||
points, and the character's original level curve survive restart and survivor
|
||||
passage. Replacement characters start at level 1. Existing snapshots receive
|
||||
level 1 and the initial progression defaults once, without retroactive XP or
|
||||
points, while preserving deaths and daily usage.
|
||||
kills, and the boss killing blow. Each crossed level threshold banks 10 stat points,
|
||||
adds 5 stamina, and banks a choice of 5 maximum health or mana. Seven primary
|
||||
attributes accept allocation intents; all derived values are calculated in Go.
|
||||
Levels, choices, allocations, XP, and the character's level curve survive restart
|
||||
and survivor passage. Replacement characters start at level 1. Legacy characters
|
||||
receive the extra points and pending vital choices for already-earned levels once,
|
||||
while retaining deaths, XP, and daily usage.
|
||||
|
||||
Title requirements are evaluated in Go and produce ordered award candidates.
|
||||
The shared database resolves first-world and first-ever claims in the same
|
||||
@@ -110,11 +112,23 @@ This account inheritance is the initial interpretation of player-bound titles.
|
||||
Awarded names, descriptions, effects, and provenance are copied at grant time;
|
||||
later content changes do not remove or alter an earned title.
|
||||
|
||||
All earned title effects are active and additive, once per title ID. The initial
|
||||
effect hooks are damage and movement speed; both accept positive and negative
|
||||
values, with effective damage/speed floored at zero. They cannot alter death,
|
||||
the daily play budget, or passage eligibility. The broader stat and effect
|
||||
catalog remains open. See [progression configuration](PROGRESSION.md).
|
||||
All earned title effects are active once per title ID. Flat bonuses are summed,
|
||||
then combined percentage bonuses apply. Modified primaries feed the derived-stat
|
||||
formulas. Existing damage/movement effects remain compatible. None can alter death,
|
||||
the daily play budget, or passage eligibility. See [progression configuration](PROGRESSION.md).
|
||||
|
||||
Control publications serialize on a singleton catalog row, check the editor's
|
||||
expected version, and record an immutable audit entry in the same transaction.
|
||||
Title/item IDs are append-only; stat formulas can be updated. Owners poll under
|
||||
the simulation lock and checkpoint updates before snapshots. New title requirements
|
||||
are evaluated on the next gameplay event. Published content cannot rewrite earned
|
||||
title awards or acquired equipment snapshots.
|
||||
|
||||
Equipment instances retain identity across equip, drop, corpse loot, and passage.
|
||||
All equipment effects are excluded when checking prerequisites, preventing items
|
||||
from enabling themselves or each other. Invalidated equipment returns to the bag.
|
||||
Legacy knife/spear stacks migrate once, including corpses; duplicate instance IDs
|
||||
within a world fail restoration. Materials and consumables remain quantity stacks.
|
||||
|
||||
## Security scope
|
||||
|
||||
|
||||
+108
-72
@@ -1,92 +1,128 @@
|
||||
# Levels and permanent titles
|
||||
# Levels, stats, titles, and equipment
|
||||
|
||||
Levels belong to a character. Titles belong to an account in this first pass,
|
||||
so a new life inherits titles while starting at level 1 with no XP or stat
|
||||
points. A dead character remains dead and keeps its historical progression.
|
||||
Survivor passage preserves levels, XP, points, titles, and the daily time budget.
|
||||
Levels belong to a character. Titles retain the existing account-bound interpretation
|
||||
of player ownership: replacement lives inherit titles, while starting at level 1.
|
||||
Dead characters retain historical stats and stay permanently dead. Survivor passage
|
||||
preserves XP, allocations, pending rewards, titles, equipment, and the daily budget.
|
||||
|
||||
## Provisional level tuning
|
||||
## Level rewards
|
||||
|
||||
Edit `server/content/balance.yaml`. New characters start at level 1. Reaching
|
||||
level 2 takes 100 XP; each following threshold costs 50 XP more. Every level
|
||||
awards 5 banked stat points. The current safety cap is level 1000. All of these
|
||||
values are configuration, not a settled stat or balance design.
|
||||
Each level-up grants **10 allocatable stat points**, **5 maximum stamina**, and a
|
||||
choice of **5 maximum health or 5 maximum mana**. Choices and points may be saved.
|
||||
Increasing a maximum does not heal/refill the pool. The server accepts one primary
|
||||
point per `allocate-stat` intent and one pending reward per `choose-vital` intent.
|
||||
Overspending, derived-stat allocation, and actions after death/daily cap are rejected.
|
||||
|
||||
Successful gathering gives 10 XP, crafting 20 XP, a sentinel kill 50 XP, and
|
||||
the boss killing blow 500 XP. Nonlethal hits, failed actions, duplicate requests,
|
||||
and actions after death give no XP. XP beyond a threshold carries into the next
|
||||
level, including multiple level-ups from one reward. XP stops at the cap.
|
||||
Initial tuning: level 1 start, 100 XP to level 2, thresholds increasing by 50 XP,
|
||||
level 1000 cap. Gathering awards 10 XP, crafting 20, sentinel kills 50, boss killing
|
||||
blow 500, modified by XP gain. Failed actions/nonlethal hits grant no XP. Threshold
|
||||
overflow carries forward, including multiple level-ups. Activity tuning lives in
|
||||
`server/content/balance.yaml` and a character's saved reward/XP curve follows it.
|
||||
|
||||
There is no stat allocation or client XP-grant API. Points remain banked until
|
||||
the full stat system is designed. Character level curves and point grants are
|
||||
stored with the character, so moving into differently tuned worlds cannot reset
|
||||
or reprice earned progress. Activity XP rewards use the destination world's tuning.
|
||||
Legacy five-point characters receive five extra points and one pending vital choice
|
||||
per earned level once. Migration preserves XP, deaths, and daily usage and is idempotent.
|
||||
|
||||
## Title definitions
|
||||
## Stats
|
||||
|
||||
The YAML `titles` list is the initial authoring interface. Each entry needs a
|
||||
stable `id`, `name`, `description`, `scope`, one or more `requirements`, and
|
||||
`effects`. Requirements are ANDed and use positive integer `atLeast` thresholds.
|
||||
|
||||
| Requirement metric | Meaning |
|
||||
| Allocatable primary | Derived stats |
|
||||
| --- | --- |
|
||||
| `level` | Current character level |
|
||||
| `kills` | Lifetime sentinel kills for this character |
|
||||
| `worldKills` | Sentinel kills since arriving in this world; resets on passage |
|
||||
| `bossKills` | Boss killing blows for this character |
|
||||
| `worldsSurvived` | Worlds survived when their boss dies, including offline survivors |
|
||||
| `gathering`, `crafting`, `combat` | Existing character skill XP counters |
|
||||
| `deaths` | 1 when this character dies, otherwise 0 |
|
||||
| Constitution | Health points, endurance, resistance, health recovery |
|
||||
| Intelligence | Magic damage, knowledge, spell points, mana points |
|
||||
| Dexterity | Movement speed, ranged damage, critical chance, endurance, dodge chance, stamina recovery |
|
||||
| Strength | Close-combat weapon damage, heavy-weapon damage, carrying capacity, endurance, defence |
|
||||
| Wisdom | Knowledge, resistance, skill points, XP gain, mana recovery |
|
||||
| Charisma | Buff effectiveness |
|
||||
| Luck | Critical chance, drop rate, gathering rate, dodge chance |
|
||||
|
||||
Control character details and the player panel show **base / flat / percent / final**.
|
||||
Primary base = configured base + allocated points. Derived base adds the contributions
|
||||
of **final primary values** and level pool rewards. Each stat then uses:
|
||||
|
||||
`final = max(0, (base + sum(flat)) * max(0, 1 + sum(percent)/100))`
|
||||
|
||||
Health capacity has a floor of 50 for daily-limit safety. Critical/dodge chances cap
|
||||
at 100%. Recovery rates are points per online simulation second. XP, drop, gathering,
|
||||
and buff-effectiveness rates start at 100 (100%). Critical/dodge values are percentage
|
||||
points. Critical damage uses `criticalMultiplier` in balance YAML.
|
||||
|
||||
Coefficients are provisional and editable through Control -> Content -> Stat formulas.
|
||||
Constitution initially adds 5 health, 1 endurance, 0.5 resistance, and 0.02 health
|
||||
recovery per point. Formula changes clamp current pools when maxima fall, without
|
||||
healing or rewriting a dead life's stat record.
|
||||
|
||||
Current gameplay consumes health, movement, melee damage, defence, dodge, critical
|
||||
chance, recovery, XP gain, drop rate, and gathering rate. Other listed stats are
|
||||
calculated, inspectable, and available in requirements/effects. Dedicated spell,
|
||||
ranged/heavy attack, skill-spending, timed-buff, stamina-cost, and encumbrance mechanics
|
||||
await their later scope. Carry weight/capacity is advisory; stack units have weight 1.
|
||||
|
||||
## Control authoring
|
||||
|
||||
Administrators publish titles, equipment, and stat formulas in **Control -> Content**.
|
||||
Publications require a reason and the current catalog version. Stale edits conflict;
|
||||
identical request retries are idempotent. An immutable database audit records actor,
|
||||
operation, target, reason, and version. World owners apply updates during their normal
|
||||
control poll (about one second) and before joining, checkpointing before snapshots.
|
||||
World records expose the applied version. Offline owners apply updates when resumed.
|
||||
|
||||
YAML seeds the catalog once. Later YAML edits do not overwrite published content.
|
||||
Title/item definitions are append-only: use a new ID for a variation. Acquired items
|
||||
and earned titles retain their original definition snapshots. Stat formulas are editable.
|
||||
|
||||
## Permanent titles
|
||||
|
||||
Requirements are ANDed positive integer thresholds. Metrics: level, kills, worldKills,
|
||||
bossKills, worldsSurvived, gathering/crafting/combat skill XP, deaths, and any primary
|
||||
or derived stat. worldKills resets on passage; deaths is 1 at death. Stat requirements
|
||||
compare the final server-calculated value.
|
||||
|
||||
| Scope | Award policy |
|
||||
| --- | --- |
|
||||
| `personal` | Any qualifying account can earn the title once |
|
||||
| `world` | First qualifying account to commit the title claim in a world |
|
||||
| `global` | First qualifying account to commit the title claim across the shared database |
|
||||
| Personal | Every qualifying account earns the title once |
|
||||
| World | First qualifying account to commit a claim in that world |
|
||||
| Global | First qualifying account to commit across the shared database |
|
||||
|
||||
“First ever” is determined by the first committed eligible transaction, starting
|
||||
when the title is introduced. It cannot reconstruct an achievement predating
|
||||
the title system. All production worlds must share the PostgreSQL database.
|
||||
Within a world, candidates follow simulation event order. Simultaneous survivor
|
||||
milestones break ties by character ID. An account already owning a title does
|
||||
not earn it again or stack its effects by visiting another world.
|
||||
First claims start when the title is introduced; earlier achievements cannot be
|
||||
reconstructed. Requirements evaluate on gameplay events, not editor publication.
|
||||
Candidates follow event order; simultaneous milestones use stable character-ID order.
|
||||
The world snapshot and title ledger commit atomically before effects become visible.
|
||||
|
||||
The shipped starter examples are Wayfarer (level 2, +1 damage), First Hunter of
|
||||
the World (first sentinel kill in a world, +2 damage), and The First Hunter
|
||||
(first sentinel kill globally, +3 damage and -0.5 movement speed).
|
||||
Every owned title is active once per ID forever. Flat and percentage modifiers may
|
||||
be positive or negative and target any stat. Legacy damage/moveSpeed effects remain
|
||||
compatible. Titles cannot be removed, traded, revoked, or lost if requirements cease
|
||||
to hold. Content edits do not alter earned awards.
|
||||
|
||||
Effects are additive `damage` and `moveSpeed` values using existing game units.
|
||||
Negative values are supported. Every owned title is active; effective damage
|
||||
and movement speed cannot go below zero. There is no equip, remove, trade, or
|
||||
revoke action. Future stat/effect hooks can extend this catalog without deciding
|
||||
the final player stat list now.
|
||||
## Inventory and equipment
|
||||
|
||||
```yaml
|
||||
- id: burdened_survivor
|
||||
name: Burdened Survivor
|
||||
description: Survive a world after defeating at least ten sentinels.
|
||||
scope: personal
|
||||
requirements:
|
||||
- { metric: worldsSurvived, atLeast: 1 }
|
||||
- { metric: kills, atLeast: 10 }
|
||||
effects: { damage: 4, moveSpeed: -1 }
|
||||
```
|
||||
The 21 slots are helmet, mask, chest, shoulders, pants, boots, gloves, earrings,
|
||||
necklace, ring1 through ring8, weapon, offhand, cape, and bag. Ring definitions use
|
||||
category `ring`; players choose one of eight slots. Offhand definitions can represent
|
||||
a shield or offhand weapon.
|
||||
|
||||
Worlds persist their balance and title catalogs. YAML edits apply to new world
|
||||
IDs; they do not hot-edit existing worlds or already-earned titles. Existing
|
||||
worlds without progression are upgraded once with the starter defaults on
|
||||
restore, with no retroactive XP or automatic historical first claims. New
|
||||
definitions can match existing counters on the next qualifying gameplay event.
|
||||
Treat published title IDs as permanent identities. Use a new ID for a distinct
|
||||
award rather than repurposing an existing one.
|
||||
Definitions specify weight, level and optional stat/title requirements, plus signed
|
||||
flat/percentage modifiers. Requirements exclude **all equipment effects**, preventing
|
||||
self-enabling gear or mutually enabling pairs. Ineligible gear automatically returns
|
||||
to the bag. Occupied slots must first be explicitly unequipped.
|
||||
|
||||
Equipment instances have unique IDs and snapshot their definitions. Equipping only
|
||||
changes a slot assignment. Bags hold unequipped gear and resource/tool/consumable
|
||||
stacks. Starting knives and crafted spears are gear; spear damage requires equipping.
|
||||
Dropping moves one stack unit or one instance to a ground pile. Loot transfers whole
|
||||
piles atomically. Death moves equipped/bag gear and stacks to the corpse. Passage
|
||||
preserves IDs; duplicate item IDs within a world fail restoration. Legacy knife/spear
|
||||
stacks migrate once, including corpses.
|
||||
|
||||
Control can set an equipment definition's per-sentinel-kill drop chance (0-100%). The
|
||||
player's drop-rate multiplier applies, capped at a guaranteed drop. Zero disables
|
||||
sentinel drops for that definition. Starting and crafted gear retains those existing
|
||||
acquisition paths. There is no arbitrary browser inventory grant.
|
||||
|
||||
## Verification and limits
|
||||
|
||||
Game tests cover successful-action XP, multi-level grants, caps, migration,
|
||||
signed effects, death, daily limits, and survivor progress. Store tests cover
|
||||
durable title claims, first-award races, retries/rollback, inheritance, and stale
|
||||
source worlds. PostgreSQL integration tests require `TEST_DATABASE_URL`.
|
||||
Tests cover formulas, allocation, choices, migration, requirements, death/drop/loot,
|
||||
passage, title claims, catalog publication/replay/conflicts, and checkpoint failures.
|
||||
PostgreSQL integration tests require `TEST_DATABASE_URL`; SQLite tests run by default.
|
||||
Browser tests cover player panels and Control authoring.
|
||||
|
||||
The tested world capacity is unchanged. This remains the existing checkpoint
|
||||
persistence model: unacknowledged actions can be lost on a crash, and storage
|
||||
failures freeze the owner before it can publish speculative progression.
|
||||
Tested capacity is unchanged. Existing checkpoint limits still apply: unacknowledged
|
||||
actions may be lost on a crash; storage failure freezes further world snapshots.
|
||||
|
||||
+17
-3
@@ -65,9 +65,11 @@ Tracked across:
|
||||
- Good karma source — **unspecified, open question**.
|
||||
|
||||
## Player Progression and Titles
|
||||
- Characters gain levels; every level-up awards stat points.
|
||||
- The full stat list and allocation rules are still undecided. The first
|
||||
implementation banks points without spending them.
|
||||
- Every level-up grants 10 allocatable stat points, 5 stamina, and a choice of
|
||||
5 maximum health or 5 maximum mana. Pending choices can be taken later.
|
||||
- Allocatable stats: constitution, intelligence, dexterity, strength, wisdom,
|
||||
charisma, and luck. Their derived stats and provisional coefficients are
|
||||
documented in `docs/PROGRESSION.md` and editable through Control.
|
||||
- Titles have configurable requirements, a name, and positive or negative effects.
|
||||
- Award scopes include personal achievements, first in a world, and first ever.
|
||||
- Earned titles cannot be lost or transferred to another player.
|
||||
@@ -77,6 +79,18 @@ Tracked across:
|
||||
Account inheritance is an implementation assumption awaiting player-design confirmation.
|
||||
- XP rewards, level curve, points per level, starter titles, and effect numbers
|
||||
are provisional tuning in `server/content/balance.yaml`.
|
||||
- Control can publish title requirements and signed flat/percentage effects,
|
||||
equipment definitions, and stat formulas, and inspect final character stats.
|
||||
|
||||
## Inventory and equipment
|
||||
- Equipment slots: helmet, mask, chest, shoulders, pants, boots, gloves,
|
||||
earrings, necklace, eight rings, weapon, shield/offhand weapon, cape, and bag.
|
||||
- Equipment can require level, stats, and permanent titles, and can provide
|
||||
positive or negative stat modifiers. Each equipment instance has its own ID.
|
||||
- Equipment transfers through dropping, corpse looting, and survivor passage.
|
||||
Equipment requirements are checked without other equipment bonuses.
|
||||
- Weight and carrying capacity are displayed; encumbrance penalties and hard
|
||||
capacity enforcement remain undecided.
|
||||
|
||||
## Open Questions
|
||||
- Good karma: what actions/behaviors generate it? — **undecided**.
|
||||
|
||||
@@ -15,6 +15,7 @@ attackRange: 6
|
||||
attackCooldown: 0.7
|
||||
playerDamage: 18
|
||||
criticalMultiplier: 2
|
||||
maxYieldPerAction: 100
|
||||
spearDamage: 32
|
||||
gatherRange: 7
|
||||
gatherCooldown: 0.6
|
||||
|
||||
@@ -36,6 +36,7 @@ type Balance struct {
|
||||
AttackCooldown float64 `yaml:"attackCooldown"`
|
||||
PlayerDamage float64 `yaml:"playerDamage"`
|
||||
CriticalMultiplier float64 `yaml:"criticalMultiplier"`
|
||||
MaxYieldPerAction int64 `yaml:"maxYieldPerAction"`
|
||||
SpearDamage float64 `yaml:"spearDamage"`
|
||||
GatherRange float64 `yaml:"gatherRange"`
|
||||
GatherCooldown float64 `yaml:"gatherCooldown"`
|
||||
@@ -106,6 +107,7 @@ func (b Balance) Validate() error {
|
||||
if b.TickHz > 60 || b.SnapshotHz > b.TickHz || b.TickHz%b.SnapshotHz != 0 || b.TerrainResolution > 64 || b.ResourcesPerChunk > 128 || b.MaxPlayers > 2000 || b.WorldRadius < b.ChunkSize*2 {
|
||||
return fmt.Errorf("invalid capacity, terrain, or tick configuration")
|
||||
}
|
||||
if b.MaxYieldPerAction > 1000 || b.CriticalMultiplier > 100 { return fmt.Errorf("invalid yield or critical damage tuning") }
|
||||
known := map[string]bool{"knife": true, "axe": true, "flint_and_steel": true, "fishing_pole": true, "wood": true, "ore": true, "herb": true, "spear": true, "bandage": true}
|
||||
check := func(items map[string]int64) error {
|
||||
if len(items) == 0 {
|
||||
|
||||
@@ -93,7 +93,9 @@ func ValidItemSlot(slot string) bool {
|
||||
return slices.Contains([]string{"helmet", "mask", "chest", "shoulders", "pants", "boots", "gloves", "earrings", "necklace", "ring", "weapon", "offhand", "cape", "bag"}, slot)
|
||||
}
|
||||
func (item ItemDefinition) Validate() error {
|
||||
if slices.Contains([]string{"axe","flint_and_steel","fishing_pole","wood","ore","herb","bandage"},item.ID){return fmt.Errorf("equipment ID conflicts with a stackable item")}
|
||||
if slices.Contains([]string{"axe", "flint_and_steel", "fishing_pole", "wood", "ore", "herb", "bandage"}, item.ID) {
|
||||
return fmt.Errorf("equipment ID conflicts with a stackable item")
|
||||
}
|
||||
if math.IsNaN(item.DropChance) || math.IsInf(item.DropChance, 0) || item.DropChance < 0 || item.DropChance > 100 {
|
||||
return fmt.Errorf("invalid drop chance")
|
||||
}
|
||||
|
||||
@@ -1,27 +1,44 @@
|
||||
package content
|
||||
|
||||
import (
|
||||
"math"
|
||||
"testing"
|
||||
"math"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestCatalogRejectsInvalidStatsAndItemRequirements(t *testing.T) {
|
||||
for name, mutate:=range map[string]func(*Catalog){
|
||||
"unknown stat":func(c *Catalog){c.Stats.Base["admin"]=1},
|
||||
"negative primary":func(c *Catalog){c.Stats.Base["constitution"]=-1},
|
||||
"nonfinite coefficient":func(c *Catalog){c.Stats.Coefficients["luck"]["criticalChance"]=math.NaN()},
|
||||
"unrelated coefficient":func(c *Catalog){delete(c.Stats.Coefficients["charisma"],"buffEffectiveness");c.Stats.Coefficients["charisma"]["healthPoints"]=1},
|
||||
"unknown modifier":func(c *Catalog){c.Titles[0].Effects.Modifiers=[]StatModifier{{Stat:"dailySeconds",Flat:100}}},
|
||||
"unsafe percentage":func(c *Catalog){c.Titles[0].Effects.Modifiers=[]StatModifier{{Stat:"strength",Percent:-101}}},
|
||||
"invalid slot":func(c *Catalog){c.Items[0].Slot="ring9"},
|
||||
"unknown title":func(c *Catalog){c.Items[0].Requirements.Titles=[]string{"missing"}},
|
||||
"duplicate item":func(c *Catalog){c.Items=append(c.Items,c.Items[0])},
|
||||
"stack collision":func(c *Catalog){c.Items[0].ID="wood"},
|
||||
"invalid drop chance":func(c *Catalog){c.Items[0].DropChance=101},
|
||||
} {
|
||||
t.Run(name,func(t *testing.T){c,err:=DefaultCatalog();if err!=nil{t.Fatal(err)};mutate(&c);if err=c.Validate();err==nil{t.Fatal("invalid catalog accepted")}})
|
||||
}
|
||||
c,err:=DefaultCatalog();if err!=nil{t.Fatal(err)}
|
||||
c.Items=append(c.Items,ItemDefinition{ID:"cursed_ring",Name:"Cursed ring",Slot:"ring",Weight:1,DropChance:2,Requirements:ItemRequirements{Level:2,Stats:map[string]float64{"constitution":3},Titles:[]string{"wayfarer"}},Modifiers:[]StatModifier{{Stat:"constitution",Flat:2,Percent:10},{Stat:"moveSpeed",Percent:-10}}})
|
||||
if err=c.Validate();err!=nil{t.Fatal(err)}
|
||||
for name, mutate := range map[string]func(*Catalog){
|
||||
"unknown stat": func(c *Catalog) { c.Stats.Base["admin"] = 1 },
|
||||
"negative primary": func(c *Catalog) { c.Stats.Base["constitution"] = -1 },
|
||||
"nonfinite coefficient": func(c *Catalog) { c.Stats.Coefficients["luck"]["criticalChance"] = math.NaN() },
|
||||
"unrelated coefficient": func(c *Catalog) {
|
||||
delete(c.Stats.Coefficients["charisma"], "buffEffectiveness")
|
||||
c.Stats.Coefficients["charisma"]["healthPoints"] = 1
|
||||
},
|
||||
"unknown modifier": func(c *Catalog) { c.Titles[0].Effects.Modifiers = []StatModifier{{Stat: "dailySeconds", Flat: 100}} },
|
||||
"unsafe percentage": func(c *Catalog) { c.Titles[0].Effects.Modifiers = []StatModifier{{Stat: "strength", Percent: -101}} },
|
||||
"invalid slot": func(c *Catalog) { c.Items[0].Slot = "ring9" },
|
||||
"unknown title": func(c *Catalog) { c.Items[0].Requirements.Titles = []string{"missing"} },
|
||||
"duplicate item": func(c *Catalog) { c.Items = append(c.Items, c.Items[0]) },
|
||||
"stack collision": func(c *Catalog) { c.Items[0].ID = "wood" },
|
||||
"invalid drop chance": func(c *Catalog) { c.Items[0].DropChance = 101 },
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
c, err := DefaultCatalog()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mutate(&c)
|
||||
if err = c.Validate(); err == nil {
|
||||
t.Fatal("invalid catalog accepted")
|
||||
}
|
||||
})
|
||||
}
|
||||
c, err := DefaultCatalog()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c.Items = append(c.Items, ItemDefinition{ID: "cursed_ring", Name: "Cursed ring", Slot: "ring", Weight: 1, DropChance: 2, Requirements: ItemRequirements{Level: 2, Stats: map[string]float64{"constitution": 3}, Titles: []string{"wayfarer"}}, Modifiers: []StatModifier{{Stat: "constitution", Flat: 2, Percent: 10}, {Stat: "moveSpeed", Percent: -10}}})
|
||||
if err = c.Validate(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,87 +1,340 @@
|
||||
package game
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"sort"
|
||||
p "aeternalis/server/internal/protocol"
|
||||
p "aeternalis/server/internal/protocol"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"sort"
|
||||
)
|
||||
|
||||
var equipmentSlots = []string{"helmet", "mask", "chest", "shoulders", "pants", "boots", "gloves", "earrings", "necklace", "ring1", "ring2", "ring3", "ring4", "ring5", "ring6", "ring7", "ring8", "weapon", "offhand", "cape", "bag"}
|
||||
|
||||
func validEquipmentSlot(slot string) bool {
|
||||
for _, candidate := range equipmentSlots { if slot == candidate { return true } }; return false
|
||||
for _, candidate := range equipmentSlots {
|
||||
if slot == candidate {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
func itemFitsSlot(item p.ItemInstance, slot string) bool {
|
||||
if !validEquipmentSlot(slot) { return false }
|
||||
if item.Slot == "ring" { return len(slot) == 5 && slot[:4] == "ring" }; return item.Slot == slot
|
||||
if !validEquipmentSlot(slot) {
|
||||
return false
|
||||
}
|
||||
if item.Slot == "ring" {
|
||||
return len(slot) == 5 && slot[:4] == "ring"
|
||||
}
|
||||
return item.Slot == slot
|
||||
}
|
||||
func ownedItem(c *Character, id string) *p.ItemInstance {
|
||||
for i := range c.View.Items { if c.View.Items[i].ID == id { return &c.View.Items[i] } }; return nil
|
||||
for i := range c.View.Items {
|
||||
if c.View.Items[i].ID == id {
|
||||
return &c.View.Items[i]
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Definitions are copied at acquisition; passage cannot replace an owned item.
|
||||
func (w *World) addInventoryItems(inventory *map[string]int64, items *[]p.ItemInstance, name string, quantity int64) error {
|
||||
if quantity < 1 { return errors.New("invalid item quantity") }
|
||||
if *inventory == nil { *inventory = map[string]int64{} }; if *items == nil { *items = []p.ItemInstance{} }
|
||||
for _, definition := range w.Balance.Items {
|
||||
if definition.ID != name { continue }
|
||||
if quantity > 100000 { return errors.New("equipment quantity exceeds migration limit") }
|
||||
created := make([]p.ItemInstance, 0, int(quantity))
|
||||
for n := int64(0); n < quantity; n++ {
|
||||
item := p.ItemInstance{ID: ID(), DefinitionID: definition.ID, Name: definition.Name, Description: definition.Description, Slot: definition.Slot, Weight: definition.Weight,
|
||||
Requirements: p.ItemRequirements{Level: definition.Requirements.Level, Stats: map[string]float64{}, Titles: append([]string{}, definition.Requirements.Titles...)}, Modifiers: []p.StatModifier{}}
|
||||
for stat, value := range definition.Requirements.Stats { item.Requirements.Stats[stat] = value }
|
||||
for _, modifier := range definition.Modifiers { item.Modifiers = append(item.Modifiers, p.StatModifier{Stat: modifier.Stat, Flat: modifier.Flat, Percent: modifier.Percent}) }
|
||||
created = append(created, item)
|
||||
}
|
||||
*items = append(*items, created...); return nil
|
||||
}
|
||||
if (*inventory)[name] > math.MaxInt64-quantity { return errors.New("item quantity overflow") }
|
||||
(*inventory)[name] += quantity; return nil
|
||||
if quantity < 1 {
|
||||
return errors.New("invalid item quantity")
|
||||
}
|
||||
if *inventory == nil {
|
||||
*inventory = map[string]int64{}
|
||||
}
|
||||
if *items == nil {
|
||||
*items = []p.ItemInstance{}
|
||||
}
|
||||
for _, definition := range w.Balance.Items {
|
||||
if definition.ID != name {
|
||||
continue
|
||||
}
|
||||
if quantity > 100000 {
|
||||
return errors.New("equipment quantity exceeds migration limit")
|
||||
}
|
||||
created := make([]p.ItemInstance, 0, int(quantity))
|
||||
for n := int64(0); n < quantity; n++ {
|
||||
item := p.ItemInstance{ID: ID(), DefinitionID: definition.ID, Name: definition.Name, Description: definition.Description, Slot: definition.Slot, Weight: definition.Weight,
|
||||
Requirements: p.ItemRequirements{Level: definition.Requirements.Level, Stats: map[string]float64{}, Titles: append([]string{}, definition.Requirements.Titles...)}, Modifiers: []p.StatModifier{}}
|
||||
for stat, value := range definition.Requirements.Stats {
|
||||
item.Requirements.Stats[stat] = value
|
||||
}
|
||||
for _, modifier := range definition.Modifiers {
|
||||
item.Modifiers = append(item.Modifiers, p.StatModifier{Stat: modifier.Stat, Flat: modifier.Flat, Percent: modifier.Percent})
|
||||
}
|
||||
created = append(created, item)
|
||||
}
|
||||
*items = append(*items, created...)
|
||||
return nil
|
||||
}
|
||||
if (*inventory)[name] > math.MaxInt64-quantity {
|
||||
return errors.New("item quantity overflow")
|
||||
}
|
||||
(*inventory)[name] += quantity
|
||||
return nil
|
||||
}
|
||||
func (w *World) grantItems(c *Character, name string, quantity int64) error {
|
||||
if err := w.addInventoryItems(&c.View.Inventory, &c.View.Items, name, quantity); err != nil { return err }
|
||||
w.RefreshStats(c); w.dirty = true; return nil
|
||||
if err := w.addInventoryItems(&c.View.Inventory, &c.View.Items, name, quantity); err != nil {
|
||||
return err
|
||||
}
|
||||
w.RefreshStats(c)
|
||||
w.dirty = true
|
||||
return nil
|
||||
}
|
||||
func (w *World) migrateEquipment(inventory *map[string]int64, items *[]p.ItemInstance) error {
|
||||
if *inventory == nil { *inventory = map[string]int64{} }; if *items == nil { *items = []p.ItemInstance{} }
|
||||
names := make([]string, 0, len(*inventory))
|
||||
for name, quantity := range *inventory { if quantity < 0 { return errors.New("negative persisted inventory") }; names = append(names, name) }; sort.Strings(names)
|
||||
for _, name := range names {
|
||||
quantity := (*inventory)[name]
|
||||
for _, definition := range w.Balance.Items {
|
||||
if definition.ID != name { continue }
|
||||
if quantity > 0 { if err := w.addInventoryItems(inventory, items, name, quantity); err != nil { return err } }
|
||||
delete(*inventory, name); w.dirty = true; break
|
||||
}
|
||||
}; return nil
|
||||
if *inventory == nil {
|
||||
*inventory = map[string]int64{}
|
||||
}
|
||||
if *items == nil {
|
||||
*items = []p.ItemInstance{}
|
||||
}
|
||||
names := make([]string, 0, len(*inventory))
|
||||
for name, quantity := range *inventory {
|
||||
if quantity < 0 {
|
||||
return errors.New("negative persisted inventory")
|
||||
}
|
||||
names = append(names, name)
|
||||
}
|
||||
sort.Strings(names)
|
||||
for _, name := range names {
|
||||
quantity := (*inventory)[name]
|
||||
for _, definition := range w.Balance.Items {
|
||||
if definition.ID != name {
|
||||
continue
|
||||
}
|
||||
if quantity > 0 {
|
||||
if err := w.addInventoryItems(inventory, items, name, quantity); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
delete(*inventory, name)
|
||||
w.dirty = true
|
||||
break
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func validateOwnedItems(items []p.ItemInstance, seen map[string]bool) error {
|
||||
for _, item := range items {
|
||||
if item.ID == "" || len(item.ID) > 100 || seen[item.ID] || item.DefinitionID == "" || item.Name == "" || (item.Slot != "ring" && !validEquipmentSlot(item.Slot)) || math.IsNaN(item.Weight) || math.IsInf(item.Weight, 0) || item.Weight < 0 || item.Requirements.Level < 1 {
|
||||
return errors.New("invalid or duplicate persisted equipment")
|
||||
}
|
||||
seen[item.ID] = true
|
||||
for _, value := range item.Requirements.Stats { if math.IsNaN(value) || math.IsInf(value, 0) || value < 0 { return errors.New("invalid equipment requirement") } }
|
||||
for _, modifier := range item.Modifiers { if modifier.Stat == "" || math.IsNaN(modifier.Flat) || math.IsInf(modifier.Flat, 0) || math.IsNaN(modifier.Percent) || math.IsInf(modifier.Percent, 0) { return errors.New("invalid equipment modifier") } }
|
||||
}; return nil
|
||||
for _, item := range items {
|
||||
if item.ID == "" || len(item.ID) > 100 || seen[item.ID] || item.DefinitionID == "" || item.Name == "" || (item.Slot != "ring" && !validEquipmentSlot(item.Slot)) || math.IsNaN(item.Weight) || math.IsInf(item.Weight, 0) || item.Weight < 0 || item.Requirements.Level < 1 {
|
||||
return errors.New("invalid or duplicate persisted equipment")
|
||||
}
|
||||
seen[item.ID] = true
|
||||
for _, value := range item.Requirements.Stats {
|
||||
if math.IsNaN(value) || math.IsInf(value, 0) || value < 0 {
|
||||
return errors.New("invalid equipment requirement")
|
||||
}
|
||||
}
|
||||
for _, modifier := range item.Modifiers {
|
||||
if modifier.Stat == "" || math.IsNaN(modifier.Flat) || math.IsInf(modifier.Flat, 0) || math.IsNaN(modifier.Percent) || math.IsInf(modifier.Percent, 0) {
|
||||
return errors.New("invalid equipment modifier")
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (w *World) restoreEquipment(c *Character) error {
|
||||
if err := w.migrateEquipment(&c.View.Inventory, &c.View.Items); err != nil { return err }
|
||||
if c.View.Equipment == nil { c.View.Equipment = map[string]string{} }
|
||||
if err := validateOwnedItems(c.View.Items, map[string]bool{}); err != nil { return err }
|
||||
seen := map[string]bool{}
|
||||
for slot, id := range c.View.Equipment {
|
||||
item := ownedItem(c, id)
|
||||
if item == nil || !itemFitsSlot(*item, slot) || seen[id] { return errors.New("invalid persisted equipment assignment") }; seen[id] = true
|
||||
}
|
||||
if c.View.Entity.State == "dead" && (len(c.View.Items) != 0 || len(c.View.Equipment) != 0) { return errors.New("dead character still owns equipment") }; return nil
|
||||
if err := w.migrateEquipment(&c.View.Inventory, &c.View.Items); err != nil {
|
||||
return err
|
||||
}
|
||||
if c.View.Equipment == nil {
|
||||
c.View.Equipment = map[string]string{}
|
||||
}
|
||||
if err := validateOwnedItems(c.View.Items, map[string]bool{}); err != nil {
|
||||
return err
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for slot, id := range c.View.Equipment {
|
||||
item := ownedItem(c, id)
|
||||
if item == nil || !itemFitsSlot(*item, slot) || seen[id] {
|
||||
return errors.New("invalid persisted equipment assignment")
|
||||
}
|
||||
seen[id] = true
|
||||
}
|
||||
if c.View.Entity.State == "dead" && (len(c.View.Items) != 0 || len(c.View.Equipment) != 0) {
|
||||
return errors.New("dead character still owns equipment")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (w *World) restoreCorpseEquipment() error {
|
||||
seen := map[string]bool{}
|
||||
for _, c := range w.Characters { if err := validateOwnedItems(c.View.Items, seen); err != nil { return err } }
|
||||
for _, corpse := range w.Corpses {
|
||||
if err := w.migrateEquipment(&corpse.Inventory, &corpse.Items); err != nil { return err }
|
||||
if err := validateOwnedItems(corpse.Items, seen); err != nil { return err }
|
||||
}; return nil
|
||||
seen := map[string]bool{}
|
||||
for _, c := range w.Characters {
|
||||
if err := validateOwnedItems(c.View.Items, seen); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
for _, corpse := range w.Corpses {
|
||||
if err := w.migrateEquipment(&corpse.Inventory, &corpse.Items); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := validateOwnedItems(corpse.Items, seen); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func equipmentRequirementError(c *Character, item p.ItemInstance, stats map[string]p.StatValue) error {
|
||||
if c.View.Level < item.Requirements.Level {
|
||||
return fmt.Errorf("requires level %d", item.Requirements.Level)
|
||||
}
|
||||
names := make([]string, 0, len(item.Requirements.Stats))
|
||||
for name := range item.Requirements.Stats {
|
||||
names = append(names, name)
|
||||
}
|
||||
sort.Strings(names)
|
||||
for _, name := range names {
|
||||
required := item.Requirements.Stats[name]
|
||||
value, ok := stats[name]
|
||||
if !ok || value.Final < required {
|
||||
return fmt.Errorf("requires %g %s before equipment", required, name)
|
||||
}
|
||||
}
|
||||
for _, required := range item.Requirements.Titles {
|
||||
found := false
|
||||
for _, title := range c.View.Titles {
|
||||
if title.ID == required {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
return fmt.Errorf("requires title %s", required)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (w *World) revalidateEquipment(c *Character) {
|
||||
stats := w.RequirementStats(c)
|
||||
valid := map[string]bool{}
|
||||
for i := range c.View.Items {
|
||||
item := &c.View.Items[i]
|
||||
err := equipmentRequirementError(c, *item, stats)
|
||||
item.Equippable = err == nil
|
||||
item.RequirementMessage = ""
|
||||
if err != nil {
|
||||
item.RequirementMessage = err.Error()
|
||||
}
|
||||
valid[item.ID] = item.Equippable
|
||||
}
|
||||
for slot, id := range c.View.Equipment {
|
||||
item := ownedItem(c, id)
|
||||
if !valid[id] || item == nil || !itemFitsSlot(*item, slot) {
|
||||
delete(c.View.Equipment, slot)
|
||||
w.dirty = true
|
||||
}
|
||||
}
|
||||
}
|
||||
func (w *World) equip(c *Character, itemID, slot string) error {
|
||||
item := ownedItem(c, itemID)
|
||||
if item == nil {
|
||||
return errors.New("item not owned")
|
||||
}
|
||||
if !itemFitsSlot(*item, slot) {
|
||||
return errors.New("item does not fit equipment slot")
|
||||
}
|
||||
if err := equipmentRequirementError(c, *item, w.RequirementStats(c)); err != nil {
|
||||
return err
|
||||
}
|
||||
if c.View.Equipment == nil {
|
||||
c.View.Equipment = map[string]string{}
|
||||
}
|
||||
if c.View.Equipment[slot] != "" {
|
||||
return errors.New("unequip the occupied slot first")
|
||||
}
|
||||
for _, id := range c.View.Equipment {
|
||||
if id == itemID {
|
||||
return errors.New("item is already equipped")
|
||||
}
|
||||
}
|
||||
c.View.Equipment[slot] = itemID
|
||||
w.RefreshStats(c)
|
||||
w.evaluateTitles(c)
|
||||
w.dirty = true
|
||||
return nil
|
||||
}
|
||||
func (w *World) unequip(c *Character, slot string) error {
|
||||
if !validEquipmentSlot(slot) || c.View.Equipment[slot] == "" {
|
||||
return errors.New("equipment slot is empty or invalid")
|
||||
}
|
||||
delete(c.View.Equipment, slot)
|
||||
w.RefreshStats(c)
|
||||
w.dirty = true
|
||||
return nil
|
||||
}
|
||||
func (w *World) dropItem(c *Character, target string) error {
|
||||
dropped := &Corpse{Inventory: map[string]int64{}, Items: []p.ItemInstance{}}
|
||||
name := target
|
||||
index := -1
|
||||
for i, item := range c.View.Items {
|
||||
if item.ID == target {
|
||||
index = i
|
||||
name = item.Name
|
||||
break
|
||||
}
|
||||
}
|
||||
if index >= 0 {
|
||||
dropped.Items = append(dropped.Items, c.View.Items[index])
|
||||
c.View.Items = append(c.View.Items[:index], c.View.Items[index+1:]...)
|
||||
for slot, id := range c.View.Equipment {
|
||||
if id == target {
|
||||
delete(c.View.Equipment, slot)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if c.View.Inventory[target] < 1 {
|
||||
return errors.New("item not owned")
|
||||
}
|
||||
c.View.Inventory[target]--
|
||||
if c.View.Inventory[target] == 0 {
|
||||
delete(c.View.Inventory, target)
|
||||
}
|
||||
dropped.Inventory[target] = 1
|
||||
}
|
||||
dropped.Entity = p.Entity{ID: "drop:" + ID(), Kind: "corpse", Name: "Dropped " + name, Position: c.View.Entity.Position, State: "dead"}
|
||||
w.Corpses[dropped.Entity.ID] = dropped
|
||||
w.RefreshStats(c)
|
||||
w.dirty = true
|
||||
return nil
|
||||
}
|
||||
func (w *World) lootCorpse(c *Character, target string) error {
|
||||
corpse := w.Corpses[target]
|
||||
if corpse == nil || distance(c.View.Entity.Position, corpse.Entity.Position) > w.Balance.GatherRange {
|
||||
return errors.New("corpse out of reach")
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
if err := validateOwnedItems(c.View.Items, seen); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := validateOwnedItems(corpse.Items, seen); err != nil {
|
||||
return err
|
||||
}
|
||||
for name, quantity := range corpse.Inventory {
|
||||
if quantity < 0 || c.View.Inventory[name] > math.MaxInt64-quantity {
|
||||
return errors.New("invalid loot quantity")
|
||||
}
|
||||
}
|
||||
for name, quantity := range corpse.Inventory {
|
||||
c.View.Inventory[name] += quantity
|
||||
}
|
||||
c.View.Items = append(c.View.Items, corpse.Items...)
|
||||
delete(w.Corpses, target)
|
||||
w.RefreshStats(c)
|
||||
w.dirty = true
|
||||
return nil
|
||||
}
|
||||
func (w *World) checkImportedEquipment(c *Character) error {
|
||||
seen := map[string]bool{}
|
||||
for _, existing := range w.Characters {
|
||||
if err := validateOwnedItems(existing.View.Items, seen); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
for _, corpse := range w.Corpses {
|
||||
if err := validateOwnedItems(corpse.Items, seen); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return validateOwnedItems(c.View.Items, seen)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
package game
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"math"
|
||||
"testing"
|
||||
"time"
|
||||
"aeternalis/server/content"
|
||||
p "aeternalis/server/internal/protocol"
|
||||
)
|
||||
func gearCount(items []p.ItemInstance,definition string)int{n:=0;for _,item:=range items{if item.DefinitionID==definition{n++}};return n}
|
||||
func testGear(id,slot string,modifiers ...p.StatModifier)p.ItemInstance{return p.ItemInstance{ID:id,DefinitionID:"test_"+id,Name:"Test "+id,Slot:slot,Weight:2,Requirements:p.ItemRequirements{Level:1,Stats:map[string]float64{},Titles:[]string{}},Modifiers:append([]p.StatModifier{},modifiers...)}}
|
||||
func TestEquipmentSlotsAndRequirements(t *testing.T){
|
||||
w,c:=fixture(t);w.grantXP(c,100)
|
||||
for n:=0;n<5;n++{if err:=w.allocateStat(c,"strength");err!=nil{t.Fatal(err)}}
|
||||
for _,slot:=range equipmentSlots{
|
||||
category:=slot;if len(slot)==5&&slot[:4]=="ring"{category="ring"}
|
||||
item:=testGear("slot_"+slot,category,p.StatModifier{Stat:"strength",Flat:1,Percent:10});c.View.Items=append(c.View.Items,item)
|
||||
if err:=w.equip(c,item.ID,slot);err!=nil{t.Fatal(slot,err)}
|
||||
}
|
||||
if len(c.View.Equipment)!=21{t.Fatal("missing equipment slots")}
|
||||
if w.equip(c,"missing","weapon")==nil||w.equip(c,"slot_ring1","ring9")==nil{t.Fatal("invalid ownership/slot accepted")}
|
||||
if w.equip(c,"slot_ring1","ring2")==nil{t.Fatal("same instance equipped twice")}
|
||||
if err:=w.unequip(c,"helmet");err!=nil{t.Fatal(err)}
|
||||
gated:=testGear("gated","helmet",p.StatModifier{Stat:"strength",Flat:100});gated.Requirements.Stats["strength"]=6;c.View.Items=append(c.View.Items,gated)
|
||||
if w.equip(c,gated.ID,"helmet")==nil{t.Fatal("equipment satisfied its own prerequisite")}
|
||||
item:=ownedItem(c,gated.ID);item.Requirements.Stats["strength"]=5;item.Requirements.Level=3;item.Requirements.Titles=[]string{"trial"}
|
||||
if w.equip(c,item.ID,"helmet")==nil{t.Fatal("missing level accepted")};item.Requirements.Level=2
|
||||
if w.equip(c,item.ID,"helmet")==nil{t.Fatal("missing title accepted")}
|
||||
c.View.Titles=append(c.View.Titles,p.TitleAward{ID:"trial"})
|
||||
if err:=w.equip(c,item.ID,"helmet");err!=nil{t.Fatal(err)}
|
||||
c.View.Titles=append(c.View.Titles,p.TitleAward{ID:"curse",Effects:p.TitleEffects{Modifiers:[]p.StatModifier{{Stat:"strength",Flat:-1}}}});w.RefreshStats(c)
|
||||
if c.View.Equipment["helmet"]!=""||ownedItem(c,gated.ID)==nil{t.Fatal("invalidated gear stayed active or was lost")}
|
||||
}
|
||||
func TestEquipmentDeathDropLootAndRestart(t *testing.T){
|
||||
w,c:=fixture(t);ring:=testGear("unique_ring","ring",p.StatModifier{Stat:"luck",Flat:2});c.View.Items=append(c.View.Items,ring)
|
||||
if err:=w.equip(c,ring.ID,"ring8");err!=nil{t.Fatal(err)}
|
||||
if err:=w.dropItem(c,ring.ID);err!=nil{t.Fatal(err)}
|
||||
if ownedItem(c,ring.ID)!=nil||c.View.Equipment["ring8"]!=""{t.Fatal("drop retained ownership")}
|
||||
var pile string;for id:=range w.Corpses{pile=id}
|
||||
if err:=w.lootCorpse(c,pile);err!=nil{t.Fatal(err)};if w.lootCorpse(c,pile)==nil{t.Fatal("looted twice")}
|
||||
if err:=w.equip(c,ring.ID,"ring8");err!=nil{t.Fatal(err)}
|
||||
c.DailySeconds=123;raw,_:=json.Marshal(w);var restored World
|
||||
if err:=json.Unmarshal(raw,&restored);err!=nil{t.Fatal(err)};if err:=restored.Restore(w.now);err!=nil{t.Fatal(err)}
|
||||
survivor:=restored.Characters[c.View.Entity.ID];survivor.View.Entity.State="eligible"
|
||||
next:=New("gear-next",345,w.now,w.Balance);if err:=next.Import(survivor);err!=nil{t.Fatal(err)}
|
||||
if survivor.DailySeconds!=123||survivor.View.Equipment["ring8"]!=ring.ID||ownedItem(survivor,ring.ID)==nil{t.Fatal("passage changed item or daily usage")}
|
||||
count:=len(survivor.View.Items);next.kill(survivor,"test death")
|
||||
corpse:=next.Corpses["corpse:"+survivor.View.Entity.ID]
|
||||
if len(corpse.Items)!=count||len(survivor.View.Items)!=0||len(survivor.View.Equipment)!=0{t.Fatal("death duplicated/lost items")}
|
||||
replacement,err:=next.Join(c.Account,"Replacement");if err!=nil{t.Fatal(err)};replacement.View.Entity.Position=corpse.Entity.Position
|
||||
if err=next.lootCorpse(replacement,corpse.Entity.ID);err!=nil{t.Fatal(err)}
|
||||
if ownedItem(replacement,ring.ID)==nil||next.Connect(survivor.View.Entity.ID)==nil{t.Fatal("loot changed identity or resurrected life")}
|
||||
}
|
||||
func TestLegacyEquipmentMigrationAndAtomicFailures(t *testing.T){
|
||||
w,c:=fixture(t);original:=len(c.View.Items);c.View.Inventory["spear"]=2
|
||||
w.Corpses["legacy"]=&Corpse{Entity:p.Entity{ID:"legacy",Position:c.View.Entity.Position},Inventory:map[string]int64{"spear":1,"ore":3}}
|
||||
for n:=0;n<2;n++{if err:=w.Restore(w.now);err!=nil{t.Fatal(err)};if len(c.View.Items)!=original+2||len(w.Corpses["legacy"].Items)!=1||c.View.Inventory["spear"]!=0{t.Fatal("migration duplicated/lost gear")}}
|
||||
corpse:=w.Corpses["legacy"];corpse.Items=append(corpse.Items,c.View.Items[0]);before:=c.View.Inventory["ore"]
|
||||
if w.lootCorpse(c,"legacy")==nil||c.View.Inventory["ore"]!=before||w.Corpses["legacy"]==nil{t.Fatal("failed loot changed inventory")}
|
||||
if w.Restore(w.now)==nil{t.Fatal("duplicate ID restored")}
|
||||
delete(w.Corpses,"legacy")
|
||||
c.View.Inventory["wood"]=3;c.View.Inventory["ore"]=2
|
||||
w.Balance.Recipes["spear"]=content.Recipe{Inputs:map[string]int64{"wood":3,"ore":2},Outputs:map[string]int64{"spear":100001}}
|
||||
if w.craft(c,"spear")==nil||c.View.Inventory["wood"]!=3||c.View.Inventory["ore"]!=2{t.Fatal("failed craft consumed materials")}
|
||||
c.View.Inventory["wood"]=math.MaxInt64
|
||||
w.Corpses["overflow"]=&Corpse{Entity:p.Entity{ID:"overflow",Position:c.View.Entity.Position},Inventory:map[string]int64{"wood":1}}
|
||||
if w.lootCorpse(c,"overflow")==nil||c.View.Inventory["wood"]!=math.MaxInt64{t.Fatal("overflow loot changed inventory")}
|
||||
}
|
||||
func TestCatalogEquipmentCanDropFromSentinels(t *testing.T){
|
||||
w,c:=fixture(t);w.Balance.Items=append(w.Balance.Items,content.ItemDefinition{ID:"drop_ring",Name:"Dropped Ring",Slot:"ring",Weight:1,DropChance:100,Requirements:content.ItemRequirements{Level:1}})
|
||||
w.now=w.now.Add(time.Second);w.Mobs["test"]=&Mob{Entity:p.Entity{ID:"test",HP:1,Position:c.View.Entity.Position}}
|
||||
if err:=w.attack(c,"test");err!=nil{t.Fatal(err)}
|
||||
if gearCount(c.View.Items,"drop_ring")!=1{t.Fatal("authored gear never dropped")}
|
||||
if w.attack(c,"test")==nil||gearCount(c.View.Items,"drop_ring")!=1{t.Fatal("repeated kill duplicated gear")}
|
||||
}
|
||||
@@ -31,6 +31,7 @@ func (w *World) orderedCharacters() []*Character {
|
||||
}
|
||||
|
||||
func (w *World) restoreProgression(c *Character) error {
|
||||
if c.StatsVersion < 0 || c.StatsVersion > 1 { return errors.New("unsupported character stats version") }
|
||||
if c.View.Level == 0 {
|
||||
c.View.Level = 1
|
||||
}
|
||||
@@ -43,7 +44,8 @@ func (w *World) restoreProgression(c *Character) error {
|
||||
if rules.StatPointsPerLevel < w.Balance.Progression.StatPointsPerLevel {
|
||||
c.View.StatPoints += (c.View.Level - 1) * (w.Balance.Progression.StatPointsPerLevel - rules.StatPointsPerLevel)
|
||||
}
|
||||
rules.StatPointsPerLevel = w.Balance.Progression.StatPointsPerLevel
|
||||
// Preserve any older, more generous grant curve rather than deleting points.
|
||||
if rules.StatPointsPerLevel < w.Balance.Progression.StatPointsPerLevel { rules.StatPointsPerLevel = w.Balance.Progression.StatPointsPerLevel }
|
||||
rules.StaminaPerLevel = w.Balance.Progression.StaminaPerLevel
|
||||
rules.VitalPointsPerChoice = w.Balance.Progression.VitalPointsPerChoice
|
||||
c.Progression = &rules
|
||||
@@ -102,18 +104,18 @@ func (w *World) grantXP(c *Character, amount int64) {
|
||||
}
|
||||
|
||||
func (w *World) evaluateTitles(c *Character) {
|
||||
metric := func(name string) int64 {
|
||||
metric := func(name string) float64 {
|
||||
switch name {
|
||||
case "level":
|
||||
return c.View.Level
|
||||
return float64(c.View.Level)
|
||||
case "kills":
|
||||
return c.View.Kills
|
||||
return float64(c.View.Kills)
|
||||
case "worldKills":
|
||||
return c.WorldKills
|
||||
return float64(c.WorldKills)
|
||||
case "bossKills":
|
||||
return c.BossKills
|
||||
return float64(c.BossKills)
|
||||
case "worldsSurvived":
|
||||
return c.WorldsSurvived
|
||||
return float64(c.WorldsSurvived)
|
||||
case "deaths":
|
||||
if c.View.Entity.State == "dead" {
|
||||
return 1
|
||||
@@ -121,9 +123,9 @@ func (w *World) evaluateTitles(c *Character) {
|
||||
return 0
|
||||
default:
|
||||
if value, ok := c.View.Stats[name]; ok {
|
||||
return int64(math.Floor(value.Final))
|
||||
return value.Final
|
||||
}
|
||||
return c.View.Skills[name]
|
||||
return float64(c.View.Skills[name])
|
||||
}
|
||||
}
|
||||
for _, title := range w.Balance.Titles {
|
||||
@@ -148,7 +150,7 @@ func (w *World) evaluateTitles(c *Character) {
|
||||
}
|
||||
eligible := true
|
||||
for _, requirement := range title.Requirements {
|
||||
if metric(requirement.Metric) < requirement.AtLeast {
|
||||
if metric(requirement.Metric) < float64(requirement.AtLeast) {
|
||||
eligible = false
|
||||
break
|
||||
}
|
||||
|
||||
@@ -22,16 +22,16 @@ func TestLevelUpsBankPointsAndCap(t *testing.T) {
|
||||
t.Fatal("premature level")
|
||||
}
|
||||
w.grantXP(c, 151)
|
||||
if c.View.Level != 3 || c.View.Experience != 0 || c.View.StatPoints != 10 || c.View.ExperienceToNextLevel != 200 {
|
||||
if c.View.Level != 3 || c.View.Experience != 0 || c.View.StatPoints != 20 || c.View.ExperienceToNextLevel != 200 {
|
||||
t.Fatalf("multi-level award lost points or XP: %+v", c.View)
|
||||
}
|
||||
c.Progression.MaxLevel = 4
|
||||
w.grantXP(c, 1000000)
|
||||
if c.View.Level != 4 || c.View.StatPoints != 15 || c.View.Experience != 0 || c.View.ExperienceToNextLevel != 0 {
|
||||
if c.View.Level != 4 || c.View.StatPoints != 30 || c.View.Experience != 0 || c.View.ExperienceToNextLevel != 0 {
|
||||
t.Fatal("level cap failed")
|
||||
}
|
||||
w.grantXP(c, 1000000)
|
||||
if c.View.StatPoints != 15 {
|
||||
if c.View.StatPoints != 30 {
|
||||
t.Fatal("cap farming granted extra points")
|
||||
}
|
||||
}
|
||||
@@ -110,7 +110,7 @@ func TestProgressionSurvivesRestartDeathAndTransfer(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
loaded := restored.Characters[c.View.Entity.ID]
|
||||
if loaded.View.Level != 3 || loaded.View.Experience != 25 || loaded.View.StatPoints != 10 || !reflect.DeepEqual(loaded.View.Titles, c.View.Titles) {
|
||||
if loaded.View.Level != 3 || loaded.View.Experience != 25 || loaded.View.StatPoints != 20 || !reflect.DeepEqual(loaded.View.Titles, c.View.Titles) {
|
||||
t.Fatal("restart reset progression")
|
||||
}
|
||||
loaded.View.Entity.State = "eligible"
|
||||
@@ -123,12 +123,12 @@ func TestProgressionSurvivesRestartDeathAndTransfer(t *testing.T) {
|
||||
if err = destination.Import(loaded); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if loaded.View.ExperienceToNextLevel != 200 || loaded.Progression.StatPointsPerLevel != 5 || loaded.DailySeconds != 123 || loaded.WorldKills != 0 || loaded.View.StatPoints != 10 || len(loaded.View.Titles) != 1 {
|
||||
if loaded.View.ExperienceToNextLevel != 200 || loaded.Progression.StatPointsPerLevel != 10 || loaded.DailySeconds != 123 || loaded.WorldKills != 0 || loaded.View.StatPoints != 20 || len(loaded.View.Titles) != 1 {
|
||||
t.Fatal("transfer altered progression, titles, or daily budget")
|
||||
}
|
||||
destination.kill(loaded, "test death")
|
||||
destination.grantXP(loaded, 1000)
|
||||
if loaded.View.StatPoints != 10 || loaded.View.Experience != 25 || len(loaded.View.Titles) != 1 {
|
||||
if loaded.View.StatPoints != 20 || loaded.View.Experience != 25 || len(loaded.View.Titles) != 1 {
|
||||
t.Fatal("death erased progression or allowed postmortem XP")
|
||||
}
|
||||
replacement, err := destination.Join(loaded.Account, "Replacement")
|
||||
@@ -154,7 +154,7 @@ func TestLegacySnapshotProgressionMigrationIsIdempotent(t *testing.T) {
|
||||
c.View.Kills = 42
|
||||
c.View.Skills["gathering"] = 99
|
||||
c.DailySeconds = 456
|
||||
c.View.Entity.State = "dead"
|
||||
w.kill(c, "legacy test death")
|
||||
if err := w.Restore(w.now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -188,6 +188,7 @@ func TestTitleRequirementsAndPendingAwardsHaveNoEffects(t *testing.T) {
|
||||
t.Fatal("candidate lost provenance or negative effect")
|
||||
}
|
||||
c.View.Titles = append(c.View.Titles, award)
|
||||
w.RefreshStats(c)
|
||||
w.PendingTitles = nil
|
||||
w.Balance.Titles[0].Effects.MoveSpeed = 99
|
||||
c.WorldKills = 0
|
||||
@@ -200,6 +201,7 @@ func TestTitleRequirementsAndPendingAwardsHaveNoEffects(t *testing.T) {
|
||||
func TestSignedTitleEffectsAreServerAuthoritative(t *testing.T) {
|
||||
w, c := fixture(t)
|
||||
c.View.Titles = []p.TitleAward{{ID: "blessing", Effects: p.TitleEffects{Damage: 5, MoveSpeed: 2}}, {ID: "curse", Effects: p.TitleEffects{Damage: -2, MoveSpeed: -1}}}
|
||||
w.RefreshStats(c)
|
||||
w.now = w.now.Add(2 * time.Second)
|
||||
if err := w.Intent(c.View.Entity.ID, p.Intent{Op: "move", Seq: 1, X: 1}); err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -217,6 +219,7 @@ func TestSignedTitleEffectsAreServerAuthoritative(t *testing.T) {
|
||||
t.Fatal("signed damage effects not applied")
|
||||
}
|
||||
c.View.Titles = append(c.View.Titles, p.TitleAward{ID: "heavy", Effects: p.TitleEffects{Damage: -1000, MoveSpeed: -1000}})
|
||||
w.RefreshStats(c)
|
||||
if w.playerSpeed(c) != 0 {
|
||||
t.Fatal("negative speed reversed movement")
|
||||
}
|
||||
@@ -249,13 +252,13 @@ func TestBossXPAndSurvivalMilestoneGrantedOnce(t *testing.T) {
|
||||
if err := w.Intent(c.View.Entity.ID, p.Intent{Op: "attack", Seq: 1, Target: "boss"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if c.BossKills != 1 || c.WorldsSurvived != 1 || offline.WorldsSurvived != 1 || dead.WorldsSurvived != 0 || c.View.Level != 4 || c.View.Experience != 50 || c.View.StatPoints != 15 {
|
||||
if c.BossKills != 1 || c.WorldsSurvived != 1 || offline.WorldsSurvived != 1 || dead.WorldsSurvived != 0 || c.View.Level != 4 || c.View.Experience != 50 || c.View.StatPoints != 30 {
|
||||
t.Fatal("incorrect boss progression")
|
||||
}
|
||||
if w.Intent(c.View.Entity.ID, p.Intent{Op: "attack", Seq: 2, Target: "boss"}) == nil {
|
||||
t.Fatal("repeat boss kill")
|
||||
}
|
||||
if c.BossKills != 1 || c.View.StatPoints != 15 {
|
||||
if c.BossKills != 1 || c.View.StatPoints != 30 {
|
||||
t.Fatal("duplicate boss rewards")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -183,7 +183,7 @@ func (w *World) roll(chance float64) bool {
|
||||
return float64(binary.LittleEndian.Uint64(sum[:8])>>11)/float64(uint64(1)<<53)*100 < chance
|
||||
}
|
||||
func (w *World) yieldAmount(rate float64) int64 {
|
||||
amount := math.Max(0, math.Min(100, rate/100))
|
||||
amount := math.Max(0, math.Min(float64(w.Balance.MaxYieldPerAction), rate/100))
|
||||
n := int64(math.Floor(amount))
|
||||
if w.roll((amount - float64(n)) * 100) {
|
||||
n++
|
||||
|
||||
@@ -1,83 +1,169 @@
|
||||
package game
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"math"
|
||||
"testing"
|
||||
"time"
|
||||
"encoding/json"
|
||||
"math"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"aeternalis/server/content"
|
||||
p "aeternalis/server/internal/protocol"
|
||||
"aeternalis/server/content"
|
||||
p "aeternalis/server/internal/protocol"
|
||||
)
|
||||
|
||||
func TestLevelRewardsAndPrimaryAllocation(t *testing.T) {
|
||||
w,c:=fixture(t)
|
||||
w.grantXP(c,100)
|
||||
if c.View.Level!=2||c.View.StatPoints!=10||c.View.PendingVitalChoices!=1||c.View.Stats["stamina"].Final!=105{t.Fatalf("wrong level rewards: %+v",c.View)}
|
||||
for i:=0;i<3;i++{if err:=w.allocateStat(c,"constitution");err!=nil{t.Fatal(err)}}
|
||||
if c.View.StatPoints!=7||c.View.Stats["constitution"].Final!=3||c.View.Entity.MaxHP!=115{t.Fatal("constitution did not update derived health")}
|
||||
if err:=w.chooseVital(c,"health");err!=nil{t.Fatal(err)}
|
||||
if c.View.Entity.MaxHP!=120||c.View.HealthChoices!=1||c.View.PendingVitalChoices!=0{t.Fatal("health choice not applied")}
|
||||
if w.chooseVital(c,"mana")==nil||w.allocateStat(c,"healthPoints")==nil{t.Fatal("duplicate vital or direct derived allocation accepted")}
|
||||
w.grantXP(c,150)
|
||||
if err:=w.chooseVital(c,"mana");err!=nil{t.Fatal(err)}
|
||||
if c.View.Stats["manaPoints"].Final!=55||c.View.Stats["stamina"].Final!=110||c.View.StatPoints!=17{t.Fatal("second level rewards incorrect")}
|
||||
for c.View.StatPoints>0 {if err:=w.allocateStat(c,"dexterity");err!=nil{t.Fatal(err)}}
|
||||
before:=c.View.Stats["dexterity"].Final
|
||||
if w.allocateStat(c,"dexterity")==nil||c.View.Stats["dexterity"].Final!=before{t.Fatal("overspent banked points")}
|
||||
w, c := fixture(t)
|
||||
w.grantXP(c, 100)
|
||||
if c.View.Level != 2 || c.View.StatPoints != 10 || c.View.PendingVitalChoices != 1 || c.View.Stats["stamina"].Final != 105 {
|
||||
t.Fatalf("wrong level rewards: %+v", c.View)
|
||||
}
|
||||
for i := 0; i < 3; i++ {
|
||||
if err := w.allocateStat(c, "constitution"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if c.View.StatPoints != 7 || c.View.Stats["constitution"].Final != 3 || c.View.Entity.MaxHP != 115 {
|
||||
t.Fatal("constitution did not update derived health")
|
||||
}
|
||||
if err := w.chooseVital(c, "health"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if c.View.Entity.MaxHP != 120 || c.View.HealthChoices != 1 || c.View.PendingVitalChoices != 0 {
|
||||
t.Fatal("health choice not applied")
|
||||
}
|
||||
if w.chooseVital(c, "mana") == nil || w.allocateStat(c, "healthPoints") == nil {
|
||||
t.Fatal("duplicate vital or direct derived allocation accepted")
|
||||
}
|
||||
w.grantXP(c, 150)
|
||||
if err := w.chooseVital(c, "mana"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if c.View.Stats["manaPoints"].Final != 55 || c.View.Stats["stamina"].Final != 110 || c.View.StatPoints != 17 {
|
||||
t.Fatal("second level rewards incorrect")
|
||||
}
|
||||
for c.View.StatPoints > 0 {
|
||||
if err := w.allocateStat(c, "dexterity"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
before := c.View.Stats["dexterity"].Final
|
||||
if w.allocateStat(c, "dexterity") == nil || c.View.Stats["dexterity"].Final != before {
|
||||
t.Fatal("overspent banked points")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStatBreakdownUsesEffectivePrimaryThenFlatAndPercent(t *testing.T) {
|
||||
w,c:=fixture(t);w.grantXP(c,100)
|
||||
for i:=0;i<4;i++{if err:=w.allocateStat(c,"strength");err!=nil{t.Fatal(err)}}
|
||||
c.View.Titles=[]p.TitleAward{{ID:"mixed",Effects:p.TitleEffects{Modifiers:[]p.StatModifier{{Stat:"strength",Flat:2,Percent:50},{Stat:"meleeDamage",Flat:3,Percent:20},{Stat:"moveSpeed",Percent:-25}}}}}
|
||||
w.RefreshStats(c)
|
||||
strength:=c.View.Stats["strength"]
|
||||
if strength.Base!=4||strength.Flat!=2||strength.Percent!=50||strength.Final!=9{t.Fatalf("bad primary breakdown: %+v",strength)}
|
||||
damage:=c.View.Stats["meleeDamage"]
|
||||
if damage.Base!=27||damage.Flat!=3||damage.Percent!=20||math.Abs(damage.Final-36)>1e-8{t.Fatalf("bad derived breakdown: %+v",damage)}
|
||||
if w.playerSpeed(c)!=9{t.Fatal("negative percentage movement not applied")}
|
||||
c.View.Titles=append(c.View.Titles,p.TitleAward{ID:"curse",Effects:p.TitleEffects{Modifiers:[]p.StatModifier{{Stat:"healthPoints",Percent:-100},{Stat:"moveSpeed",Percent:-100}}}})
|
||||
w.RefreshStats(c)
|
||||
if c.View.Entity.MaxHP!=50||w.playerSpeed(c)!=0{t.Fatal("vital safety floor or zero speed bound failed")}
|
||||
w, c := fixture(t)
|
||||
w.grantXP(c, 100)
|
||||
for i := 0; i < 4; i++ {
|
||||
if err := w.allocateStat(c, "strength"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
c.View.Titles = []p.TitleAward{{ID: "mixed", Effects: p.TitleEffects{Modifiers: []p.StatModifier{{Stat: "strength", Flat: 2, Percent: 50}, {Stat: "meleeDamage", Flat: 3, Percent: 20}, {Stat: "moveSpeed", Percent: -25}}}}}
|
||||
w.RefreshStats(c)
|
||||
strength := c.View.Stats["strength"]
|
||||
if strength.Base != 4 || strength.Flat != 2 || strength.Percent != 50 || strength.Final != 9 {
|
||||
t.Fatalf("bad primary breakdown: %+v", strength)
|
||||
}
|
||||
damage := c.View.Stats["meleeDamage"]
|
||||
if damage.Base != 27 || damage.Flat != 3 || damage.Percent != 20 || math.Abs(damage.Final-36) > 1e-8 {
|
||||
t.Fatalf("bad derived breakdown: %+v", damage)
|
||||
}
|
||||
if w.playerSpeed(c) != 9 {
|
||||
t.Fatal("negative percentage movement not applied")
|
||||
}
|
||||
c.View.Titles = append(c.View.Titles, p.TitleAward{ID: "curse", Effects: p.TitleEffects{Modifiers: []p.StatModifier{{Stat: "healthPoints", Percent: -100}, {Stat: "moveSpeed", Percent: -100}}}})
|
||||
w.RefreshStats(c)
|
||||
if c.View.Entity.MaxHP != 50 || w.playerSpeed(c) != 0 {
|
||||
t.Fatal("vital safety floor or zero speed bound failed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStatsMigrationAndTransferPreserveEarnedRewards(t *testing.T) {
|
||||
w,c:=fixture(t)
|
||||
c.View.Level=3;c.View.Experience=25;c.View.StatPoints=10;c.StatsVersion=0
|
||||
c.View.AllocatedStats=nil;c.View.Stats=nil;c.View.PendingVitalChoices=0
|
||||
old:=*c.Progression;old.StatPointsPerLevel=5;old.StaminaPerLevel=0;old.VitalPointsPerChoice=0;c.Progression=&old
|
||||
w.Balance.Stats=nil
|
||||
c.DailySeconds=321
|
||||
raw,err:=json.Marshal(w);if err!=nil{t.Fatal(err)}
|
||||
var restored World;if err=json.Unmarshal(raw,&restored);err!=nil{t.Fatal(err)}
|
||||
if err=restored.Restore(w.now);err!=nil{t.Fatal(err)}
|
||||
migrated:=restored.Characters[c.View.Entity.ID]
|
||||
if migrated.View.StatPoints!=20||migrated.View.PendingVitalChoices!=2||migrated.View.Stats["stamina"].Final!=110||migrated.DailySeconds!=321{t.Fatal("legacy level rewards not migrated once")}
|
||||
if err=restored.Restore(w.now);err!=nil{t.Fatal(err)}
|
||||
if migrated.View.StatPoints!=20||migrated.View.PendingVitalChoices!=2{t.Fatal("repeated restore duplicated rewards")}
|
||||
if err=restored.allocateStat(migrated,"wisdom");err!=nil{t.Fatal(err)}
|
||||
if err=restored.chooseVital(migrated,"mana");err!=nil{t.Fatal(err)}
|
||||
migrated.View.Entity.State="eligible"
|
||||
next:=New("stats-next",999,w.now,restored.Balance)
|
||||
if err=next.Import(migrated);err!=nil{t.Fatal(err)}
|
||||
if migrated.View.StatPoints!=19||migrated.View.AllocatedStats["wisdom"]!=1||migrated.View.PendingVitalChoices!=1||migrated.View.ManaChoices!=1||migrated.DailySeconds!=321{t.Fatal("transfer altered rewards or daily budget")}
|
||||
next.kill(migrated,"test")
|
||||
if next.Connect(migrated.View.Entity.ID)==nil{t.Fatal("stat feature resurrected a life")}
|
||||
if next.Intent(migrated.View.Entity.ID,p.Intent{Op:"allocate-stat",Target:"strength",Seq:1})==nil{t.Fatal("dead life allocated a point")}
|
||||
w, c := fixture(t)
|
||||
c.View.Level = 3
|
||||
c.View.Experience = 25
|
||||
c.View.StatPoints = 10
|
||||
c.StatsVersion = 0
|
||||
c.View.AllocatedStats = nil
|
||||
c.View.Stats = nil
|
||||
c.View.PendingVitalChoices = 0
|
||||
old := *c.Progression
|
||||
old.StatPointsPerLevel = 5
|
||||
old.StaminaPerLevel = 0
|
||||
old.VitalPointsPerChoice = 0
|
||||
c.Progression = &old
|
||||
w.Balance.Stats = nil
|
||||
c.DailySeconds = 321
|
||||
raw, err := json.Marshal(w)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var restored World
|
||||
if err = json.Unmarshal(raw, &restored); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = restored.Restore(w.now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
migrated := restored.Characters[c.View.Entity.ID]
|
||||
if migrated.View.StatPoints != 20 || migrated.View.PendingVitalChoices != 2 || migrated.View.Stats["stamina"].Final != 110 || migrated.DailySeconds != 321 {
|
||||
t.Fatal("legacy level rewards not migrated once")
|
||||
}
|
||||
if err = restored.Restore(w.now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if migrated.View.StatPoints != 20 || migrated.View.PendingVitalChoices != 2 {
|
||||
t.Fatal("repeated restore duplicated rewards")
|
||||
}
|
||||
if err = restored.allocateStat(migrated, "wisdom"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = restored.chooseVital(migrated, "mana"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
migrated.View.Entity.State = "eligible"
|
||||
next := New("stats-next", 999, w.now, restored.Balance)
|
||||
if err = next.Import(migrated); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if migrated.View.StatPoints != 19 || migrated.View.AllocatedStats["wisdom"] != 1 || migrated.View.PendingVitalChoices != 1 || migrated.View.ManaChoices != 1 || migrated.DailySeconds != 321 {
|
||||
t.Fatal("transfer altered rewards or daily budget")
|
||||
}
|
||||
next.kill(migrated, "test")
|
||||
if next.Connect(migrated.View.Entity.ID) == nil {
|
||||
t.Fatal("stat feature resurrected a life")
|
||||
}
|
||||
if next.Intent(migrated.View.Entity.ID, p.Intent{Op: "allocate-stat", Target: "strength", Seq: 1}) == nil {
|
||||
t.Fatal("dead life allocated a point")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCatalogChangesDoNotHealOrRewriteDeadStats(t *testing.T) {
|
||||
w,c:=fixture(t)
|
||||
dead,err:=w.Join("dead-stats","Dead");if err!=nil{t.Fatal(err)}
|
||||
w.kill(dead,"test")
|
||||
prior:=dead.View.Stats["healthPoints"].Final
|
||||
c.View.Entity.HP=20;c.DailySeconds=123
|
||||
catalog,err:=content.DefaultCatalog();if err!=nil{t.Fatal(err)}
|
||||
catalog.Version=2;catalog.Stats.Base["healthPoints"]=200
|
||||
if err=w.ApplyCatalog(catalog);err!=nil{t.Fatal(err)}
|
||||
if c.View.Entity.MaxHP!=200||c.View.Entity.HP!=20||c.DailySeconds!=123||dead.View.Entity.State!="dead"||dead.View.Stats["healthPoints"].Final!=prior{t.Fatal("catalog changed life/budget/history")}
|
||||
w.Balance.DailyPlaySeconds=124
|
||||
w.Advance(w.now.Add(2*time.Second),2)
|
||||
if c.Online||c.View.RemainingSeconds!=0||c.View.Entity.HP!=50{t.Fatal("expanded stats weakened daily cap")}
|
||||
w, c := fixture(t)
|
||||
dead, err := w.Join("dead-stats", "Dead")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
w.kill(dead, "test")
|
||||
prior := dead.View.Stats["healthPoints"].Final
|
||||
c.View.Entity.HP = 20
|
||||
c.DailySeconds = 123
|
||||
catalog, err := content.DefaultCatalog()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
catalog.Version = 2
|
||||
catalog.Stats.Base["healthPoints"] = 200
|
||||
if err = w.ApplyCatalog(catalog); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if c.View.Entity.MaxHP != 200 || c.View.Entity.HP != 20 || c.DailySeconds != 123 || dead.View.Entity.State != "dead" || dead.View.Stats["healthPoints"].Final != prior {
|
||||
t.Fatal("catalog changed life/budget/history")
|
||||
}
|
||||
w.Balance.DailyPlaySeconds = 124
|
||||
w.Advance(w.now.Add(2*time.Second), 2)
|
||||
if c.Online || c.View.RemainingSeconds != 0 || c.View.Entity.HP != 50 {
|
||||
t.Fatal("expanded stats weakened daily cap")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"maps"
|
||||
"math"
|
||||
"sort"
|
||||
"time"
|
||||
@@ -118,10 +119,16 @@ func (w *World) Restore(now time.Time) error {
|
||||
}
|
||||
if w.Balance.CriticalMultiplier == 0 {
|
||||
defaults, err := content.Load()
|
||||
if err != nil { return err }
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
w.Balance.CriticalMultiplier = defaults.CriticalMultiplier
|
||||
w.dirty = true
|
||||
}
|
||||
if w.Balance.MaxYieldPerAction == 0 {
|
||||
defaults, err := content.Load(); if err != nil { return err }
|
||||
w.Balance.MaxYieldPerAction = defaults.MaxYieldPerAction; w.dirty = true
|
||||
}
|
||||
if err := w.Balance.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -147,7 +154,7 @@ func (w *World) Restore(now time.Time) error {
|
||||
c.MoveZ = 0
|
||||
c.View.ACK = 0
|
||||
}
|
||||
return nil
|
||||
return w.restoreCorpseEquipment()
|
||||
}
|
||||
func (w *World) Age() float64 {
|
||||
now := w.now
|
||||
@@ -235,8 +242,12 @@ func (w *World) Join(account, name string) (*Character, error) {
|
||||
for k, v := range w.Balance.StartingKit {
|
||||
c.View.Inventory[k] = v
|
||||
}
|
||||
if err := w.restoreEquipment(c); err != nil { return nil, err }
|
||||
if err := w.initializeStats(c); err != nil { return nil, err }
|
||||
if err := w.restoreEquipment(c); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := w.initializeStats(c); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
w.Characters[c.View.Entity.ID] = c
|
||||
c.BornAt = w.now
|
||||
w.evaluateTitles(c)
|
||||
@@ -253,8 +264,15 @@ func (w *World) Import(c *Character) error {
|
||||
if err := w.restoreProgression(c); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := w.restoreEquipment(c); err != nil { return err }
|
||||
if err := w.initializeStats(c); err != nil { return err }
|
||||
if err := w.restoreEquipment(c); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := w.checkImportedEquipment(c); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := w.initializeStats(c); err != nil {
|
||||
return err
|
||||
}
|
||||
pos, err := w.spawn("")
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -440,12 +458,17 @@ func (w *World) craft(c *Character, name string) error {
|
||||
return errors.New("missing crafting materials")
|
||||
}
|
||||
}
|
||||
inventory := maps.Clone(c.View.Inventory)
|
||||
items := append([]p.ItemInstance{}, c.View.Items...)
|
||||
for k, v := range r.Inputs {
|
||||
c.View.Inventory[k] -= v
|
||||
inventory[k] -= v
|
||||
}
|
||||
for k, v := range r.Outputs {
|
||||
if err := w.grantItems(c, k, v); err != nil { return err }
|
||||
if err := w.addInventoryItems(&inventory, &items, k, v); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
c.View.Inventory, c.View.Items = inventory, items
|
||||
w.RefreshStats(c)
|
||||
c.View.Skills["crafting"] += w.Balance.SkillXpPerAction
|
||||
c.Message = "Crafted " + name
|
||||
@@ -502,8 +525,10 @@ func (w *World) attack(c *Character, target string) error {
|
||||
c.WorldKills++
|
||||
c.View.Inventory["herb"] += w.yieldAmount(c.View.Stats["dropRate"].Final)
|
||||
for _, item := range w.Balance.Items {
|
||||
if w.roll(item.DropChance*c.View.Stats["dropRate"].Final/100) {
|
||||
if err := w.grantItems(c, item.ID, 1); err != nil { return err }
|
||||
if w.roll(item.DropChance * c.View.Stats["dropRate"].Final / 100) {
|
||||
if err := w.grantItems(c, item.ID, 1); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
w.grantXP(c, w.Balance.Progression.MobKillXP)
|
||||
@@ -627,7 +652,9 @@ func (w *World) Advance(now time.Time, dt float64) {
|
||||
}
|
||||
}
|
||||
if c.Online {
|
||||
if c.View.Entity.HP > 0 { c.View.Entity.HP = math.Min(c.View.Entity.MaxHP, c.View.Entity.HP+c.View.Stats["healthRecovery"].Final*dt) }
|
||||
if c.View.Entity.HP > 0 {
|
||||
c.View.Entity.HP = math.Min(c.View.Entity.MaxHP, c.View.Entity.HP+c.View.Stats["healthRecovery"].Final*dt)
|
||||
}
|
||||
c.View.Mana = math.Min(c.View.Stats["manaPoints"].Final, c.View.Mana+c.View.Stats["manaRecovery"].Final*dt)
|
||||
c.View.Stamina = math.Min(c.View.Stats["stamina"].Final, c.View.Stamina+c.View.Stats["staminaRecovery"].Final*dt)
|
||||
// A generous window: the client resends its move intent well under this on every
|
||||
|
||||
@@ -122,7 +122,7 @@ func TestGatherCraftAndPermanentDeath(t *testing.T) {
|
||||
if err := w.Intent(id, p.Intent{Op: "craft", Seq: 5, Target: "spear"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if c.View.Inventory["spear"] != 1 || c.View.Inventory["wood"] != 0 || c.View.Inventory["ore"] != 0 {
|
||||
if gearCount(c.View.Items,"spear") != 1 || c.View.Inventory["wood"] != 0 || c.View.Inventory["ore"] != 0 {
|
||||
t.Fatal("recipe not atomic")
|
||||
}
|
||||
w.kill(c, "test death")
|
||||
@@ -143,7 +143,7 @@ func TestGatherCraftAndPermanentDeath(t *testing.T) {
|
||||
if c.DiedAt == nil || c.DeathReason != "test death" {
|
||||
t.Fatal("missing durable death record")
|
||||
}
|
||||
if len(c.View.Inventory) != 0 || w.Corpses["corpse:"+id].Inventory["spear"] != 1 {
|
||||
if len(c.View.Inventory) != 0 || gearCount(w.Corpses["corpse:"+id].Items,"spear") != 1 {
|
||||
t.Fatal("corpse inventory")
|
||||
}
|
||||
raw, _ := json.Marshal(w)
|
||||
@@ -283,7 +283,7 @@ func TestSpawnAndTransferPreserveBudget(t *testing.T) {
|
||||
if err := next.Import(c); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if c.DailySeconds != 123 || c.View.PlayedSeconds != 456 || c.View.Skills["combat"] != 9 || c.View.Inventory["spear"] != 1 {
|
||||
if c.DailySeconds != 123 || c.View.PlayedSeconds != 456 || c.View.Skills["combat"] != 9 || gearCount(c.View.Items,"spear") != 1 {
|
||||
t.Fatal("transfer changed progress or budget")
|
||||
}
|
||||
if err := next.Import(c); err == nil {
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
"aeternalis/server/content"
|
||||
)
|
||||
|
||||
var ErrCatalogConflict = errors.New("catalog changed; refresh before publishing")
|
||||
var ErrCatalogRequest = errors.New("request ID already used for a different catalog change")
|
||||
var ErrCatalogInvalid = errors.New("invalid catalog change")
|
||||
var catalogRequestID = regexp.MustCompile(`^[a-f0-9-]{32,36}$`)
|
||||
type CatalogChange struct {
|
||||
ID string `json:"id"`
|
||||
ExpectedVersion int64 `json:"expectedVersion"`
|
||||
Op string `json:"op"`
|
||||
Reason string `json:"reason"`
|
||||
Title *content.Title `json:"title,omitempty"`
|
||||
Item *content.ItemDefinition `json:"item,omitempty"`
|
||||
Stats *content.StatsRules `json:"stats,omitempty"`
|
||||
}
|
||||
type CatalogResult struct { Version int64 `json:"version"` }
|
||||
type CatalogAudit struct {
|
||||
ID string `json:"id"`
|
||||
Actor string `json:"actor"`
|
||||
Op string `json:"op"`
|
||||
Target string `json:"target"`
|
||||
Reason string `json:"reason"`
|
||||
Version int64 `json:"version"`
|
||||
CreatedAt int64 `json:"createdAt"`
|
||||
}
|
||||
func (d *DB) ensureCatalog(ctx context.Context) error {
|
||||
defaults,err:=content.DefaultCatalog();if err!=nil{return err}
|
||||
if err=defaults.Validate();err!=nil{return err}
|
||||
raw,err:=json.Marshal(defaults);if err!=nil{return err}
|
||||
tx,err:=d.sql.BeginTx(ctx,nil);if err!=nil{return err};defer tx.Rollback()
|
||||
if d.postgres { if _,err=tx.ExecContext(ctx,`SELECT pg_advisory_xact_lock(7362771)`);err!=nil{return err} }
|
||||
for _,stmt:=range []string{
|
||||
`CREATE TABLE IF NOT EXISTS control_catalog(id INTEGER PRIMARY KEY CHECK(id=1),version BIGINT NOT NULL,document TEXT NOT NULL)`,
|
||||
`CREATE TABLE IF NOT EXISTS catalog_changes(id TEXT PRIMARY KEY,actor TEXT NOT NULL,op TEXT NOT NULL,target TEXT NOT NULL,reason TEXT NOT NULL,expected_version BIGINT NOT NULL,result_version BIGINT NOT NULL,request_json TEXT NOT NULL,created_at BIGINT NOT NULL)`,
|
||||
`CREATE INDEX IF NOT EXISTS catalog_changes_version ON catalog_changes(result_version)`,
|
||||
}{if _,err=tx.ExecContext(ctx,stmt);err!=nil{return err}}
|
||||
if _,err=tx.ExecContext(ctx,d.q(`INSERT INTO control_catalog(id,version,document) VALUES(1,1,?) ON CONFLICT(id) DO NOTHING`),string(raw));err!=nil{return err}
|
||||
return tx.Commit()
|
||||
}
|
||||
func decodeCatalog(version int64,raw string)(content.Catalog,error){
|
||||
var catalog content.Catalog
|
||||
if err:=json.Unmarshal([]byte(raw),&catalog);err!=nil{return catalog,err}
|
||||
if catalog.Version!=version{return catalog,errors.New("catalog version mismatch")}
|
||||
return catalog,catalog.Validate()
|
||||
}
|
||||
func(d *DB) Catalog(ctx context.Context)(content.Catalog,error){
|
||||
var version int64;var raw string
|
||||
if err:=d.sql.QueryRowContext(ctx,`SELECT version,document FROM control_catalog WHERE id=1`).Scan(&version,&raw);err!=nil{return content.Catalog{},err}
|
||||
return decodeCatalog(version,raw)
|
||||
}
|
||||
func(d *DB) CatalogAfter(ctx context.Context,after int64)(*content.Catalog,error){
|
||||
var version int64;var raw string
|
||||
err:=d.sql.QueryRowContext(ctx,d.q(`SELECT version,document FROM control_catalog WHERE id=1 AND version>?`),after).Scan(&version,&raw)
|
||||
if errors.Is(err,sql.ErrNoRows){return nil,nil};if err!=nil{return nil,err}
|
||||
catalog,err:=decodeCatalog(version,raw);return &catalog,err
|
||||
}
|
||||
func(c CatalogChange) validate()error{
|
||||
if !catalogRequestID.MatchString(c.ID)||c.ExpectedVersion<1||len(c.Reason)<5||len(c.Reason)>240{return fmt.Errorf("%w: request ID, current version and 5-240 character reason required",ErrCatalogInvalid)}
|
||||
valid:=false
|
||||
switch c.Op{
|
||||
case "create-title":valid=c.Title!=nil&&c.Item==nil&&c.Stats==nil
|
||||
case "create-item":valid=c.Item!=nil&&c.Title==nil&&c.Stats==nil
|
||||
case "update-stats":valid=c.Stats!=nil&&c.Title==nil&&c.Item==nil
|
||||
}
|
||||
if !valid{return fmt.Errorf("%w: operation must have exactly its matching payload",ErrCatalogInvalid)};return nil
|
||||
}
|
||||
func(d *DB) PublishCatalog(ctx context.Context,actor string,change CatalogChange)(CatalogResult,error){
|
||||
change.Reason=strings.TrimSpace(change.Reason)
|
||||
if actor==""{return CatalogResult{},fmt.Errorf("%w: actor required",ErrCatalogInvalid)}
|
||||
if err:=change.validate();err!=nil{return CatalogResult{},err}
|
||||
request,err:=json.Marshal(change);if err!=nil{return CatalogResult{},fmt.Errorf("%w: %v",ErrCatalogInvalid,err)}
|
||||
tx,err:=d.sql.BeginTx(ctx,nil);if err!=nil{return CatalogResult{},err};defer tx.Rollback()
|
||||
// Serialize editors without locking world/character/passage/award rows.
|
||||
locked,err:=tx.ExecContext(ctx,`UPDATE control_catalog SET version=version WHERE id=1`);if err!=nil{return CatalogResult{},err}
|
||||
n,err:=locked.RowsAffected();if err!=nil{return CatalogResult{},err};if n!=1{return CatalogResult{},errors.New("catalog unavailable")}
|
||||
var previousActor,previousRequest string;var result CatalogResult
|
||||
err=tx.QueryRowContext(ctx,d.q(`SELECT actor,request_json,result_version FROM catalog_changes WHERE id=?`),change.ID).Scan(&previousActor,&previousRequest,&result.Version)
|
||||
if err==nil{if previousActor!=actor||previousRequest!=string(request){return CatalogResult{},ErrCatalogRequest};return result,tx.Commit()}
|
||||
if !errors.Is(err,sql.ErrNoRows){return CatalogResult{},err}
|
||||
var version int64;var raw string
|
||||
if err=tx.QueryRowContext(ctx,`SELECT version,document FROM control_catalog WHERE id=1`).Scan(&version,&raw);err!=nil{return CatalogResult{},err}
|
||||
if version!=change.ExpectedVersion{return CatalogResult{},ErrCatalogConflict}
|
||||
catalog,err:=decodeCatalog(version,raw);if err!=nil{return CatalogResult{},err}
|
||||
target:="stats"
|
||||
switch change.Op{
|
||||
case "create-title":catalog.Titles=append(catalog.Titles,*change.Title);target=change.Title.ID
|
||||
case "create-item":catalog.Items=append(catalog.Items,*change.Item);target=change.Item.ID
|
||||
case "update-stats":catalog.Stats=*change.Stats
|
||||
}
|
||||
catalog.Version=version+1
|
||||
if err=catalog.Validate();err!=nil{return CatalogResult{},fmt.Errorf("%w: %v",ErrCatalogInvalid,err)}
|
||||
encoded,err:=json.Marshal(catalog);if err!=nil{return CatalogResult{},err}
|
||||
if _,err=tx.ExecContext(ctx,d.q(`UPDATE control_catalog SET version=?,document=? WHERE id=1`),catalog.Version,string(encoded));err!=nil{return CatalogResult{},err}
|
||||
if _,err=tx.ExecContext(ctx,d.q(`INSERT INTO catalog_changes(id,actor,op,target,reason,expected_version,result_version,request_json,created_at) VALUES(?,?,?,?,?,?,?,?,`+d.now()+`)`),change.ID,actor,change.Op,target,change.Reason,change.ExpectedVersion,catalog.Version,string(request));err!=nil{return CatalogResult{},err}
|
||||
if err=tx.Commit();err!=nil{return CatalogResult{},err};return CatalogResult{Version:catalog.Version},nil
|
||||
}
|
||||
func(d *DB) CatalogChanges(ctx context.Context)([]CatalogAudit,error){
|
||||
rows,err:=d.sql.QueryContext(ctx,`SELECT id,actor,op,target,reason,result_version,created_at FROM catalog_changes ORDER BY result_version DESC LIMIT 100`);if err!=nil{return nil,err};defer rows.Close()
|
||||
changes:=[]CatalogAudit{}
|
||||
for rows.Next(){var c CatalogAudit;if err=rows.Scan(&c.ID,&c.Actor,&c.Op,&c.Target,&c.Reason,&c.Version,&c.CreatedAt);err!=nil{return nil,err};changes=append(changes,c)}
|
||||
return changes,rows.Err()
|
||||
}
|
||||
@@ -24,16 +24,17 @@ type CharacterRecord struct {
|
||||
Character *game.Character `json:"character"`
|
||||
}
|
||||
type WorldRecord struct {
|
||||
ID string `json:"id"`
|
||||
Phase string `json:"phase"`
|
||||
Living int `json:"living"`
|
||||
Dead int `json:"dead"`
|
||||
Capacity int `json:"capacity"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
BossAt time.Time `json:"bossAt"`
|
||||
Closed bool `json:"closed"`
|
||||
Available bool `json:"available"`
|
||||
Revision int64 `json:"revision"`
|
||||
ID string `json:"id"`
|
||||
Phase string `json:"phase"`
|
||||
Living int `json:"living"`
|
||||
Dead int `json:"dead"`
|
||||
Capacity int `json:"capacity"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
BossAt time.Time `json:"bossAt"`
|
||||
Closed bool `json:"closed"`
|
||||
Available bool `json:"available"`
|
||||
Revision int64 `json:"revision"`
|
||||
CatalogVersion int64 `json:"catalogVersion"`
|
||||
}
|
||||
type Command struct {
|
||||
ID string `json:"id"`
|
||||
@@ -228,6 +229,7 @@ func (d *DB) Worlds(ctx context.Context) ([]WorldRecord, error) {
|
||||
return nil, err
|
||||
}
|
||||
r.ID = w.ID
|
||||
r.CatalogVersion = w.CatalogVersion
|
||||
r.Phase = w.Phase
|
||||
r.Living = w.LivingCount()
|
||||
r.Dead = len(w.Characters) - r.Living
|
||||
|
||||
@@ -73,6 +73,10 @@ func Open(ctx context.Context, dsn string) (*DB, error) {
|
||||
conn.Close()
|
||||
return nil, err
|
||||
}
|
||||
if err = db.ensureCatalog(ctx); err != nil {
|
||||
conn.Close()
|
||||
return nil, err
|
||||
}
|
||||
return db, nil
|
||||
}
|
||||
func (d *DB) Close() error { return d.sql.Close() }
|
||||
|
||||
@@ -5,12 +5,14 @@ import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"aeternalis/server/content"
|
||||
"aeternalis/server/internal/game"
|
||||
p "aeternalis/server/internal/protocol"
|
||||
)
|
||||
|
||||
func TestStoreLifecycle(t *testing.T) {
|
||||
@@ -173,7 +175,7 @@ func runStoreTests(t *testing.T, dsn string) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
loaded := restored.Characters[c.View.Entity.ID]
|
||||
if loaded == nil || loaded.DailySeconds != 123 || loaded.View.Inventory["spear"] != 1 {
|
||||
if loaded == nil || loaded.DailySeconds != 123 || !slices.ContainsFunc(loaded.View.Items,func(item p.ItemInstance)bool{return item.DefinitionID=="spear"}) {
|
||||
t.Fatal("transfer not durable")
|
||||
}
|
||||
if err = targetLease.Save(ctx, target, ""); err == nil {
|
||||
|
||||
@@ -12,7 +12,7 @@ import (
|
||||
p "aeternalis/server/internal/protocol"
|
||||
)
|
||||
|
||||
// Only title slices change in this staged view. The live simulation is untouched
|
||||
// Title grants and their derived stats/equipment eligibility change in this staged view. The live simulation is untouched
|
||||
// until its snapshot, claim ledger, character records and passages all commit.
|
||||
func stageTitleWorld(w *game.World) *game.World {
|
||||
staged := *w
|
||||
|
||||
@@ -241,7 +241,8 @@ func runTitleTests(t *testing.T, dsn string) {
|
||||
c.View.Level = 2
|
||||
c.View.Experience = 20
|
||||
c.View.ExperienceToNextLevel = 150
|
||||
c.View.StatPoints = 5
|
||||
c.View.StatPoints = 10
|
||||
c.View.PendingVitalChoices = 1
|
||||
c.DailySeconds = 123
|
||||
c.View.Entity.State = "eligible"
|
||||
source.Phase = "won"
|
||||
@@ -267,7 +268,7 @@ func runTitleTests(t *testing.T, dsn string) {
|
||||
if err = lt.Save(ctx, target, c.View.Entity.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !has(survivor, id) || survivor.View.StatPoints != 5 || survivor.View.Experience != 20 || survivor.DailySeconds != 123 {
|
||||
if !has(survivor, id) || survivor.View.StatPoints != 10 || survivor.View.Experience != 20 || survivor.DailySeconds != 123 {
|
||||
t.Fatal("passage lost progression")
|
||||
}
|
||||
forbidden := prefix + "-source-forbidden"
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
package transport
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"time"
|
||||
"aeternalis/server/internal/store"
|
||||
)
|
||||
func(h *HTTP) catalogRoutes(mux *http.ServeMux){
|
||||
mux.HandleFunc("GET /api/control/catalog",func(w http.ResponseWriter,r *http.Request){
|
||||
if _,ok:=h.admin(w,r);!ok{return}
|
||||
ctx,cancel:=context.WithTimeout(r.Context(),5*time.Second);defer cancel()
|
||||
catalog,err:=h.auth.db.Catalog(ctx);if err!=nil{fail(w,503,"catalog unavailable");return}
|
||||
changes,err:=h.auth.db.CatalogChanges(ctx);if err!=nil{fail(w,503,"catalog audit unavailable");return}
|
||||
respond(w,200,map[string]any{"catalog":catalog,"changes":changes})
|
||||
})
|
||||
mux.HandleFunc("POST /api/control/catalog",func(w http.ResponseWriter,r *http.Request){
|
||||
actor,ok:=h.admin(w,r);if !ok{return}
|
||||
var change store.CatalogChange
|
||||
r.Body=http.MaxBytesReader(w,r.Body,32768)
|
||||
decoder:=json.NewDecoder(r.Body);decoder.DisallowUnknownFields()
|
||||
if err:=decoder.Decode(&change);err!=nil{fail(w,400,"invalid catalog change");return}
|
||||
var extra any;if err:=decoder.Decode(&extra);err!=io.EOF{fail(w,400,"invalid catalog change");return}
|
||||
ctx,cancel:=context.WithTimeout(r.Context(),5*time.Second);defer cancel()
|
||||
result,err:=h.auth.db.PublishCatalog(ctx,actor,change)
|
||||
switch{
|
||||
case errors.Is(err,store.ErrCatalogConflict),errors.Is(err,store.ErrCatalogRequest):fail(w,409,err.Error())
|
||||
case errors.Is(err,store.ErrCatalogInvalid):fail(w,400,err.Error())
|
||||
case err!=nil:fail(w,503,"catalog publication unavailable")
|
||||
default:respond(w,200,result)
|
||||
}
|
||||
})
|
||||
}
|
||||
// Caller holds s.mu. Checkpoint a catalog before it can reach a snapshot.
|
||||
func(s *Service) refreshCatalog(ctx context.Context)error{
|
||||
ctx,cancel:=context.WithTimeout(ctx,5*time.Second);defer cancel()
|
||||
catalog,err:=s.lease.DB.CatalogAfter(ctx,s.world.CatalogVersion);if err!=nil{return err};if catalog==nil{return nil}
|
||||
if err=s.world.ApplyCatalog(*catalog);err!=nil{return err};return s.persist(ctx,"")
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package transport
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
"aeternalis/server/content"
|
||||
"aeternalis/server/internal/game"
|
||||
"aeternalis/server/internal/store"
|
||||
)
|
||||
|
||||
func TestPublishedTitlesAndStatsReachDurableCharacterViews(t *testing.T) {
|
||||
ctx:=context.Background()
|
||||
db,err:=store.Open(ctx,"file:"+filepath.ToSlash(filepath.Join(t.TempDir(),"catalog-owner.db")));if err!=nil{t.Fatal(err)};defer db.Close()
|
||||
b,err:=content.Load();if err!=nil{t.Fatal(err)}
|
||||
w:=game.New("catalog-owner",23,time.Now(),b)
|
||||
lease,_,err:=db.Acquire(ctx,w);if err!=nil{t.Fatal(err)}
|
||||
svc:=NewService(w,lease)
|
||||
initial,err:=db.Catalog(ctx);if err!=nil{t.Fatal(err)}
|
||||
title:=content.Title{ID:"published_strength",Name:"Published Strength",Scope:"personal",Requirements:[]content.TitleRequirement{{Metric:"level",AtLeast:1}},Effects:content.TitleEffects{Modifiers:[]content.StatModifier{{Stat:"strength",Flat:4,Percent:50}}}}
|
||||
result,err:=db.PublishCatalog(ctx,"operator",store.CatalogChange{ID:game.ID(),ExpectedVersion:initial.Version,Op:"create-title",Reason:"Integration title",Title:&title});if err!=nil{t.Fatal(err)}
|
||||
view,err:=svc.join(ctx,"catalog-player","Catalog Player","");if err!=nil{t.Fatal(err)}
|
||||
if len(view.Titles)!=1||view.Titles[0].ID!=title.ID||view.Stats["strength"].Final!=6||view.Stats["meleeDamage"].Final!=24{t.Fatal("published title missing from committed join",view)}
|
||||
c:=w.Characters[view.Entity.ID];c.View.Entity.HP=20;c.DailySeconds=321
|
||||
rules:=initial.Stats;rules.Base["healthPoints"]=150
|
||||
result,err=db.PublishCatalog(ctx,"operator",store.CatalogChange{ID:game.ID(),ExpectedVersion:result.Version,Op:"update-stats",Reason:"Integration formula",Stats:&rules});if err!=nil{t.Fatal(err)}
|
||||
if err=svc.controls(ctx);err!=nil{t.Fatal(err)}
|
||||
record,err:=db.ActiveCharacter(ctx,c.Account);if err!=nil{t.Fatal(err)}
|
||||
if record.Character.View.Entity.MaxHP!=150||record.Character.View.Entity.HP!=20||record.Character.DailySeconds!=321||record.Character.View.Titles[0].Effects.Modifiers[0].Flat!=4{t.Fatal("catalog changed health, budget or earned title")}
|
||||
worlds,err:=db.Worlds(ctx);if err!=nil||worlds[0].CatalogVersion!=result.Version{t.Fatal("applied version not checkpointed",err)}
|
||||
if err=lease.Release(ctx);err!=nil{t.Fatal(err)}
|
||||
nextLease,raw,err:=db.Acquire(ctx,game.New(w.ID,23,time.Now(),b));if err!=nil{t.Fatal(err)};defer nextLease.Release(ctx)
|
||||
var restored game.World;if err=json.Unmarshal(raw,&restored);err!=nil{t.Fatal(err)}
|
||||
if err=restored.Restore(time.Now());err!=nil{t.Fatal(err)}
|
||||
if restored.CatalogVersion!=result.Version||restored.Characters[c.View.Entity.ID].View.Stats["healthPoints"].Final!=150{t.Fatal("restart lost published stats")}
|
||||
// Old ownership may no longer expose a speculative formula revision.
|
||||
rules.Base["healthPoints"]=200
|
||||
if _,err=db.PublishCatalog(ctx,"operator",store.CatalogChange{ID:game.ID(),ExpectedVersion:result.Version,Op:"update-stats",Reason:"Stale owner test",Stats:&rules});err!=nil{t.Fatal(err)}
|
||||
if err=svc.refreshCatalog(ctx);err==nil||svc.ready.Load(){t.Fatal("stale owner continued after failed catalog checkpoint")}
|
||||
record,err=db.ActiveCharacter(ctx,c.Account);if err!=nil{t.Fatal(err)}
|
||||
if record.Character.View.Entity.MaxHP!=150{t.Fatal("failed checkpoint published speculative stats")}
|
||||
}
|
||||
@@ -97,6 +97,7 @@ func (h *HTTP) allow(r *http.Request) bool {
|
||||
func (h *HTTP) Handler() http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
h.portalRoutes(mux)
|
||||
h.catalogRoutes(mux)
|
||||
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) {
|
||||
if !h.s.ready.Load() {
|
||||
fail(w, 503, "world frozen")
|
||||
@@ -175,6 +176,7 @@ func (h *HTTP) Handler() http.Handler {
|
||||
h.s.mu.Lock()
|
||||
defer h.s.mu.Unlock()
|
||||
if c := h.s.world.ForAccount(account); c != nil && active != nil && active.WorldID == h.s.world.ID && active.ID == c.View.Entity.ID {
|
||||
if !h.s.ready.Load() { fail(w, 503, "world unavailable"); return }
|
||||
respond(w, 200, map[string]any{"character": c.View, "world": h.s.world.Info()})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -132,6 +132,9 @@ func (s *Service) join(ctx context.Context, account, name, claim string) (p.Char
|
||||
if !s.ready.Load() {
|
||||
return p.Character{}, errors.New("world unavailable")
|
||||
}
|
||||
if err := s.refreshCatalog(ctx); err != nil {
|
||||
return p.Character{}, err
|
||||
}
|
||||
var c *game.Character
|
||||
var err error
|
||||
active, err := s.lease.DB.ActiveCharacter(ctx, account)
|
||||
@@ -188,6 +191,9 @@ func (s *Service) join(ctx context.Context, account, name, claim string) (p.Char
|
||||
func (s *Service) controls(ctx context.Context) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
defer cancel()
|
||||
if err := s.refreshCatalog(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
commands, err := s.lease.DB.Commands(ctx, s.world.ID, true)
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
Reference in New Issue
Block a user