Checkpoint stats equipment and control catalog implementation
This commit is contained in:
@@ -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