Add housing storage, guest permissions, and timed key destruction
This commit is contained in:
@@ -214,6 +214,8 @@ items:
|
||||
modifiers: [{ stat: meleeDamage, flat: 14, percent: 0 }]
|
||||
|
||||
# Milestone 6 provisional crafting tuning. Percentages use 0-100.
|
||||
- {"id": "storage_chest", "name": "Storage chest", "description": "Furniture for a house.", "slot": "bag", "weight": 5, "dropChance": 0, "requirements": {"level": 1, "stats": {}, "titles": []}, "modifiers": [], "furniture": {"width": 2, "depth": 1, "container": true}}
|
||||
- {"id": "house_table", "name": "House table", "description": "Furniture for a house.", "slot": "bag", "weight": 5, "dropChance": 0, "requirements": {"level": 1, "stats": {}, "titles": []}, "modifiers": [], "furniture": {"width": 2, "depth": 2, "container": false}}
|
||||
crafting:
|
||||
rules: { baseFailure: 25, minFailure: 1, maxFailure: 99.9, overLevelDecay: 0.12, underLevelGrowth: 0.25, baseLoss: 80, minLoss: 10, lossDecay: 0.025, qualityPerLevel: 0.03, maxQualityBias: 8, cooldown: 1 }
|
||||
professions:
|
||||
@@ -258,3 +260,5 @@ building:
|
||||
- {"id": "timber_wall", "name": "Timber wall", "description": "A persistent, destructible timber wall.", "model": "wall", "width": 4, "depth": 1, "height": 2, "hp": 250, "profession": "builder", "level": 1}
|
||||
- {"id": "camp_platform", "name": "Camp platform", "description": "A persistent, destructible camp platform.", "model": "camp", "width": 4, "depth": 4, "height": 0.75, "hp": 300, "profession": "builder", "level": 1}
|
||||
- {"id": "fort_block", "name": "Fort block", "description": "A persistent, destructible fort block.", "model": "fort", "width": 6, "depth": 3, "height": 3, "hp": 800, "profession": "builder", "level": 5}
|
||||
|
||||
housing: { roomSize: 12, maxFurniture: 64, maxItems: 256, maxGuests: 64, keySeconds: 3 }
|
||||
|
||||
@@ -19,6 +19,7 @@ type Recipe struct {
|
||||
}
|
||||
|
||||
type Balance struct {
|
||||
Housing *HousingRules `yaml:"housing"`
|
||||
Building *BuildingContent `yaml:"building"`
|
||||
Powers *PowerContent `yaml:"powers"`
|
||||
Crafting *CraftingContent `yaml:"crafting"`
|
||||
@@ -83,6 +84,11 @@ func Parse(data []byte) (Balance, error) {
|
||||
return b, b.Validate()
|
||||
}
|
||||
func (b Balance) Validate() error {
|
||||
if b.Housing != nil {
|
||||
if e := b.Housing.Validate(); e != nil {
|
||||
return e
|
||||
}
|
||||
}
|
||||
if e := (Catalog{Building: b.Building, Crafting: b.Crafting, Items: b.Items}).validateBuilding(); e != nil {
|
||||
return e
|
||||
}
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
package content
|
||||
|
||||
import "fmt"
|
||||
|
||||
type FurnitureProfile struct {
|
||||
Width float64 `json:"width" yaml:"width"`
|
||||
Depth float64 `json:"depth" yaml:"depth"`
|
||||
Container bool `json:"container" yaml:"container"`
|
||||
}
|
||||
|
||||
func (f FurnitureProfile) Validate() error {
|
||||
if !finiteRange(f.Width, .5, 4) || !finiteRange(f.Depth, .5, 4) {
|
||||
return fmt.Errorf("invalid furniture footprint")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type HousingRules struct {
|
||||
RoomSize float64 `yaml:"roomSize"`
|
||||
MaxFurniture int `yaml:"maxFurniture"`
|
||||
MaxItems int `yaml:"maxItems"`
|
||||
MaxGuests int `yaml:"maxGuests"`
|
||||
KeySeconds float64 `yaml:"keySeconds"`
|
||||
}
|
||||
|
||||
func (r HousingRules) Validate() error {
|
||||
if !finiteRange(r.RoomSize, 8, 32) || r.MaxFurniture < 1 || r.MaxFurniture > 128 || r.MaxItems < 1 || r.MaxItems > 512 || r.MaxGuests < 1 || r.MaxGuests > 128 || r.KeySeconds != 3 {
|
||||
return fmt.Errorf("invalid housing rules")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (c *Catalog) RestoreFurniture(b Balance) {
|
||||
if c.HousingVersion != 0 {
|
||||
return
|
||||
}
|
||||
c.Items = append([]ItemDefinition{}, c.Items...)
|
||||
for _, v := range b.Items {
|
||||
if v.Furniture == nil {
|
||||
continue
|
||||
}
|
||||
found := false
|
||||
for _, i := range c.Items {
|
||||
if i.ID == v.ID {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
c.Items = append(c.Items, v)
|
||||
}
|
||||
}
|
||||
c.HousingVersion = 1
|
||||
}
|
||||
+23
-13
@@ -35,20 +35,22 @@ type ItemRequirements struct {
|
||||
Titles []string `json:"titles" yaml:"titles"`
|
||||
}
|
||||
type ItemDefinition struct {
|
||||
WeaponType string `json:"weaponType,omitempty" yaml:"weaponType"`
|
||||
CraftPool []CraftStat `json:"craftPool,omitempty" yaml:"craftPool"`
|
||||
CraftRolls int64 `json:"craftRolls,omitempty" yaml:"craftRolls"`
|
||||
AttackID string `json:"attackId,omitempty" yaml:"attackId"`
|
||||
ID string `json:"id" yaml:"id"`
|
||||
Name string `json:"name" yaml:"name"`
|
||||
Description string `json:"description" yaml:"description"`
|
||||
Slot string `json:"slot" yaml:"slot"`
|
||||
Weight float64 `json:"weight" yaml:"weight"`
|
||||
DropChance float64 `json:"dropChance" yaml:"dropChance"`
|
||||
Requirements ItemRequirements `json:"requirements" yaml:"requirements"`
|
||||
Modifiers []StatModifier `json:"modifiers" yaml:"modifiers"`
|
||||
Furniture *FurnitureProfile `json:"furniture,omitempty" yaml:"furniture"`
|
||||
WeaponType string `json:"weaponType,omitempty" yaml:"weaponType"`
|
||||
CraftPool []CraftStat `json:"craftPool,omitempty" yaml:"craftPool"`
|
||||
CraftRolls int64 `json:"craftRolls,omitempty" yaml:"craftRolls"`
|
||||
AttackID string `json:"attackId,omitempty" yaml:"attackId"`
|
||||
ID string `json:"id" yaml:"id"`
|
||||
Name string `json:"name" yaml:"name"`
|
||||
Description string `json:"description" yaml:"description"`
|
||||
Slot string `json:"slot" yaml:"slot"`
|
||||
Weight float64 `json:"weight" yaml:"weight"`
|
||||
DropChance float64 `json:"dropChance" yaml:"dropChance"`
|
||||
Requirements ItemRequirements `json:"requirements" yaml:"requirements"`
|
||||
Modifiers []StatModifier `json:"modifiers" yaml:"modifiers"`
|
||||
}
|
||||
type Catalog struct {
|
||||
HousingVersion int `json:"housingVersion,omitempty"`
|
||||
Building *BuildingContent `json:"building,omitempty"`
|
||||
Powers *PowerContent `json:"powers,omitempty"`
|
||||
Crafting *CraftingContent `json:"crafting,omitempty"`
|
||||
@@ -105,6 +107,14 @@ 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 item.Furniture != nil {
|
||||
if item.Slot != "bag" {
|
||||
return fmt.Errorf("furniture must use bag slot")
|
||||
}
|
||||
if e := item.Furniture.Validate(); e != nil {
|
||||
return e
|
||||
}
|
||||
}
|
||||
if err := ValidateCraftPool(item); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -219,5 +229,5 @@ func DefaultCatalog() (Catalog, error) {
|
||||
if err != nil {
|
||||
return Catalog{}, err
|
||||
}
|
||||
return Catalog{Building: b.Building, Powers: b.Powers, Crafting: b.Crafting, Combat: b.Combat, Gathering: b.Gathering, Version: 1, Titles: b.Titles, Items: b.Items, Stats: *b.Stats}, nil
|
||||
return Catalog{HousingVersion: 1, Building: b.Building, Powers: b.Powers, Crafting: b.Crafting, Combat: b.Combat, Gathering: b.Gathering, Version: 1, Titles: b.Titles, Items: b.Items, Stats: *b.Stats}, nil
|
||||
}
|
||||
|
||||
@@ -75,6 +75,9 @@ func (w *World) AdminItems(c *Character, op, value string) error {
|
||||
}
|
||||
return w.grantItems(c, id, n)
|
||||
}
|
||||
if item := ownedItem(c, id); item != nil && item.HouseID != nil {
|
||||
return errors.New("house keys require the holder's three-second destruction action")
|
||||
}
|
||||
if op != "remove-item" {
|
||||
return errors.New("unknown item operation")
|
||||
}
|
||||
|
||||
@@ -66,7 +66,7 @@ func (w *World) sourceActive(source string, player bool) bool {
|
||||
}
|
||||
if player {
|
||||
c := w.Characters[source]
|
||||
return c != nil && c.View.Entity.State == "alive" && !c.Sheltered
|
||||
return c != nil && HouseID(c) == "" && c.View.Entity.State == "alive" && !c.Sheltered
|
||||
}
|
||||
m := w.Mobs[source]
|
||||
return m != nil && m.Entity.HP > 0
|
||||
@@ -75,7 +75,7 @@ func (w *World) combatTargets(player bool, effect string) []p.Entity {
|
||||
out := []p.Entity{}
|
||||
if (player && effect == "heal") || (!player && effect == "damage") {
|
||||
for _, c := range w.orderedCharacters() {
|
||||
if c.Online && c.View.Entity.State == "alive" && !c.Sheltered {
|
||||
if HouseID(c) == "" && c.Online && c.View.Entity.State == "alive" && !c.Sheltered {
|
||||
out = append(out, c.View.Entity)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -145,7 +145,7 @@ func (w *World) CraftProfessions(c *Character) []p.CraftProgress {
|
||||
// requirement requests do not consume materials or advance the random stream.
|
||||
func (w *World) AttemptCraft(c *Character, req p.CraftRequest) (p.CraftResult, error) {
|
||||
result := p.CraftResult{ID: req.ID, Consumed: map[string]int64{}, Created: []string{}}
|
||||
if c == nil || !c.Online || c.Sheltered || c.View.Entity.State != "alive" || c.View.RemainingSeconds <= 0 || (!w.IsHub() && w.Phase != "gathering" && w.Phase != "cataclysm") {
|
||||
if c == nil || HouseID(c) != "" || !c.Online || c.Sheltered || c.View.Entity.State != "alive" || c.View.RemainingSeconds <= 0 || (!w.IsHub() && w.Phase != "gathering" && w.Phase != "cataclysm") {
|
||||
return result, errors.New("character cannot craft")
|
||||
}
|
||||
now := float64(w.now.UnixMilli()) / 1000
|
||||
|
||||
@@ -19,6 +19,9 @@ func validEquipmentSlot(slot string) bool {
|
||||
return false
|
||||
}
|
||||
func itemFitsSlot(item p.ItemInstance, slot string) bool {
|
||||
if item.HouseID != nil || item.Furniture != nil {
|
||||
return false
|
||||
}
|
||||
if !validEquipmentSlot(slot) {
|
||||
return false
|
||||
}
|
||||
@@ -58,6 +61,10 @@ func (w *World) addInventoryItems(inventory *map[string]int64, items *[]p.ItemIn
|
||||
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,
|
||||
WeaponType: stringPtr(definition.WeaponType), Requirements: p.ItemRequirements{Level: definition.Requirements.Level, Stats: map[string]float64{}, Titles: append([]string{}, definition.Requirements.Titles...)}, Modifiers: []p.StatModifier{}}
|
||||
if definition.Furniture != nil {
|
||||
f := definition.Furniture
|
||||
item.Furniture = &p.FurnitureProfile{Width: f.Width, Depth: f.Depth, Container: f.Container}
|
||||
}
|
||||
for stat, value := range definition.Requirements.Stats {
|
||||
item.Requirements.Stats[stat] = value
|
||||
}
|
||||
@@ -133,6 +140,15 @@ func validateOwnedItems(items []p.ItemInstance, seen map[string]bool) error {
|
||||
return errors.New("invalid or duplicate persisted equipment")
|
||||
}
|
||||
seen[item.ID] = true
|
||||
if item.Furniture != nil {
|
||||
f := item.Furniture
|
||||
if math.IsNaN(f.Width) || math.IsNaN(f.Depth) || f.Width < .5 || f.Width > 4 || f.Depth < .5 || f.Depth > 4 {
|
||||
return errors.New("invalid saved furniture")
|
||||
}
|
||||
}
|
||||
if item.HouseID != nil && (len(*item.HouseID) != 32 || item.DefinitionID != "house_key") {
|
||||
return errors.New("invalid saved house key")
|
||||
}
|
||||
for _, value := range item.Requirements.Stats {
|
||||
if math.IsNaN(value) || math.IsInf(value, 0) || value < 0 {
|
||||
return errors.New("invalid equipment requirement")
|
||||
@@ -198,6 +214,9 @@ func (w *World) restoreCorpseEquipment() error {
|
||||
return nil
|
||||
}
|
||||
func equipmentRequirementError(c *Character, item p.ItemInstance, stats map[string]p.StatValue) error {
|
||||
if item.HouseID != nil || item.Furniture != nil {
|
||||
return errors.New("house items cannot be equipped")
|
||||
}
|
||||
if c.View.Level < item.Requirements.Level {
|
||||
return fmt.Errorf("requires level %d", item.Requirements.Level)
|
||||
}
|
||||
@@ -291,6 +310,9 @@ func (w *World) dropItem(c *Character, target string) error {
|
||||
index := -1
|
||||
for i, item := range c.View.Items {
|
||||
if item.ID == target {
|
||||
if c.View.DestroyKey != nil && c.View.DestroyKey.KeyID == target {
|
||||
c.View.DestroyKey = nil
|
||||
}
|
||||
index = i
|
||||
name = item.Name
|
||||
break
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
package game
|
||||
|
||||
import (
|
||||
"aeternalis/server/content"
|
||||
p "aeternalis/server/internal/protocol"
|
||||
"errors"
|
||||
"math"
|
||||
)
|
||||
|
||||
var HousePermissions = []string{"moveFurniture", "openFurniture", "placeFurniture", "depositItems", "pickupItems", "dropItems"}
|
||||
|
||||
func (w *World) NowSeconds() float64 { return float64(w.now.UnixMilli()) / 1000 }
|
||||
func HouseID(c *Character) string {
|
||||
if c == nil || c.View.HouseID == nil {
|
||||
return ""
|
||||
}
|
||||
return *c.View.HouseID
|
||||
}
|
||||
func LeaveHouse(c *Character) { c.View.HouseID = nil; c.MoveX = 0; c.MoveZ = 0 }
|
||||
func (w *World) restoreHousing() error {
|
||||
if w.Balance.Housing == nil {
|
||||
b, e := content.Load()
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
w.Balance.Housing = b.Housing
|
||||
cat := content.Catalog{Items: w.Balance.Items}
|
||||
cat.RestoreFurniture(b)
|
||||
w.Balance.Items = cat.Items
|
||||
}
|
||||
for _, c := range w.Characters {
|
||||
LeaveHouse(c)
|
||||
c.View.DestroyKey = nil
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (w *World) updateHousingActions() {
|
||||
for _, c := range w.Characters {
|
||||
if c.View.DestroyKey != nil {
|
||||
key := ownedItem(c, c.View.DestroyKey.KeyID)
|
||||
if !c.Online || c.View.RemainingSeconds <= 0 || c.Sheltered || c.View.Entity.State == "dead" || key == nil || key.HouseID == nil {
|
||||
c.View.DestroyKey = nil
|
||||
w.dirty = true
|
||||
} else if w.NowSeconds() >= c.View.DestroyKey.FinishesAt {
|
||||
w.dirty = true
|
||||
}
|
||||
}
|
||||
if HouseID(c) != "" && (!c.Online || c.View.Entity.State == "dead" || c.View.RemainingSeconds <= 0) {
|
||||
LeaveHouse(c)
|
||||
w.dirty = true
|
||||
}
|
||||
}
|
||||
}
|
||||
func EmptyHouseInventory() p.HouseInventory {
|
||||
return p.HouseInventory{Inventory: map[string]int64{}, Items: []p.ItemInstance{}, CraftedStacks: []p.CraftedStack{}, StackNames: map[string]string{}}
|
||||
}
|
||||
func ValidateHouseInventory(v p.HouseInventory, seen map[string]bool) error {
|
||||
if len(v.Inventory) > 512 || len(v.Items) > 512 || len(v.StackNames) > 1024 {
|
||||
return errors.New("house inventory limit")
|
||||
}
|
||||
for _, n := range v.Inventory {
|
||||
if n < 0 || n > 1000000000000 {
|
||||
return errors.New("invalid stored quantity")
|
||||
}
|
||||
}
|
||||
if e := validateOwnedItems(v.Items, seen); e != nil {
|
||||
return e
|
||||
}
|
||||
return ValidateCraftedStacks(v.Inventory, v.CraftedStacks, seen)
|
||||
}
|
||||
func HouseInventoryOf(c *Character) p.HouseInventory {
|
||||
return p.HouseInventory{Inventory: c.View.Inventory, Items: c.View.Items, CraftedStacks: c.View.CraftedStacks, StackNames: c.View.StackNames}
|
||||
}
|
||||
func SetHouseInventory(c *Character, v p.HouseInventory) {
|
||||
c.View.Inventory = v.Inventory
|
||||
c.View.Items = v.Items
|
||||
c.View.CraftedStacks = v.CraftedStacks
|
||||
c.View.StackNames = v.StackNames
|
||||
}
|
||||
|
||||
// Move one unique instance or a bounded stack quantity; provenance travels with it.
|
||||
// Call on staged/transaction-owned inventories and validate before publishing.
|
||||
func MoveHouseItem(from, to *p.HouseInventory, id string, quantity int64) error {
|
||||
if quantity < 1 || quantity > 1000 || len(to.Items) >= 512 || len(to.Inventory) >= 512 {
|
||||
return errors.New("invalid quantity or destination full")
|
||||
}
|
||||
for i, item := range from.Items {
|
||||
if item.ID == id {
|
||||
if quantity != 1 {
|
||||
return errors.New("unique item quantity must be one")
|
||||
}
|
||||
to.Items = append(to.Items, item)
|
||||
from.Items = append(from.Items[:i:i], from.Items[i+1:]...)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
if from.Inventory[id] < quantity || to.Inventory[id] > 1000000000000-quantity {
|
||||
return errors.New("item quantity unavailable")
|
||||
}
|
||||
temp := &Character{}
|
||||
SetHouseInventory(temp, *from)
|
||||
batches := TakeStack(temp, id, quantity)
|
||||
*from = HouseInventoryOf(temp)
|
||||
if to.Inventory == nil {
|
||||
to.Inventory = map[string]int64{}
|
||||
}
|
||||
if to.StackNames == nil {
|
||||
to.StackNames = map[string]string{}
|
||||
}
|
||||
to.Inventory[id] += quantity
|
||||
to.CraftedStacks = append(to.CraftedStacks, batches...)
|
||||
if name := from.StackNames[id]; name != "" {
|
||||
to.StackNames[id] = name
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func FurnitureFits(h p.House, id string, item p.ItemInstance, x, z float64) bool {
|
||||
f := item.Furniture
|
||||
if f == nil || math.IsNaN(x) || math.IsNaN(z) || math.IsInf(x, 0) || math.IsInf(z, 0) || math.Abs(x)+f.Width/2 > h.Size/2 || math.Abs(z)+f.Depth/2 > h.Size/2 {
|
||||
return false
|
||||
}
|
||||
for other, v := range h.Furniture {
|
||||
if other == id {
|
||||
continue
|
||||
}
|
||||
g := v.Item.Furniture
|
||||
if g != nil && math.Abs(x-v.X) < (g.Width+f.Width)/2 && math.Abs(z-v.Z) < (g.Depth+f.Depth)/2 {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package game
|
||||
|
||||
import (
|
||||
"aeternalis/server/content"
|
||||
p "aeternalis/server/internal/protocol"
|
||||
"encoding/json"
|
||||
"math"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestHouseInventoryPreservesCraftedProvenance(t *testing.T) {
|
||||
b, _ := content.Load()
|
||||
w := New("craft-origin", 1, time.Now(), b)
|
||||
c, _ := w.Join("crafter", "Crafter")
|
||||
c.View.Inventory["bandage"] = 5
|
||||
provenance := p.CraftProvenance{At: 1, CharacterID: c.View.Entity.ID, CrafterName: "Crafter", Level: 1, Profession: "alchemist", RecipeID: "recipe_bandage", RecipeRevision: 1, WorldID: w.ID}
|
||||
c.View.CraftedStacks = []p.CraftedStack{{ID: ID(), Item: "bandage", Quantity: 5, Provenance: provenance}}
|
||||
from, to := HouseInventoryOf(c), EmptyHouseInventory()
|
||||
if e := MoveHouseItem(&from, &to, "bandage", 2); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if from.Inventory["bandage"] != 3 || to.Inventory["bandage"] != 2 || to.CraftedStacks[0].Provenance != provenance || from.CraftedStacks[0].ID == to.CraftedStacks[0].ID {
|
||||
t.Fatal("split damaged provenance or duplicated batch ID")
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
if e := ValidateHouseInventory(from, seen); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e := ValidateHouseInventory(to, seen); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e := w.AdminItems(c, "grant-item", "storage_chest:1"); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
item := c.View.Items[len(c.View.Items)-1]
|
||||
h := p.House{Size: 12, Furniture: map[string]p.HouseFurniture{item.ID: {Item: item, X: 0, Z: 0}}}
|
||||
if FurnitureFits(h, "", item, 0, 0) || FurnitureFits(h, "", item, 6, 0) || FurnitureFits(h, "", item, math.NaN(), 0) || !FurnitureFits(h, item.ID, item, 3, 0) {
|
||||
t.Fatal("furniture collision validation")
|
||||
}
|
||||
before, _ := json.Marshal(to)
|
||||
if e := MoveHouseItem(&from, &to, "bandage", 999); e == nil {
|
||||
t.Fatal("overdraw accepted")
|
||||
}
|
||||
after, _ := json.Marshal(to)
|
||||
if string(before) != string(after) {
|
||||
t.Fatal("overdraw changed destination")
|
||||
}
|
||||
}
|
||||
func TestHousingDailyLimitAndNoMovement(t *testing.T) {
|
||||
b, _ := content.Load()
|
||||
now := time.Date(2026, 9, 10, 12, 0, 0, 0, time.UTC)
|
||||
w := New("daily-house", 1, now, b)
|
||||
c, _ := w.Join("owner", "Owner")
|
||||
_ = w.Connect(c.View.Entity.ID)
|
||||
w.Kind = "hub"
|
||||
w.Phase = "hub"
|
||||
id := ID()
|
||||
c.View.HouseID = &id
|
||||
before := c.View.Entity.Position
|
||||
c.MoveX = 1
|
||||
c.LastMove = now
|
||||
c.DailySeconds = b.DailyPlaySeconds - 1
|
||||
w.Advance(now.Add(500*time.Millisecond), .5)
|
||||
if c.View.Entity.Position != before || c.DailySeconds != b.DailyPlaySeconds-.5 {
|
||||
t.Fatal("housing moved avatar or stopped daily budget")
|
||||
}
|
||||
w.Advance(now.Add(2*time.Second), 1.5)
|
||||
if c.Online || c.View.HouseID != nil || c.View.RemainingSeconds != 0 {
|
||||
t.Fatal("daily cap did not exit housing")
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,9 @@ func (w *World) PortalPosition() p.Vec3 { return w.terrain.Position(0, 0) }
|
||||
|
||||
// Escape is an explicit one-item action. It grants no victory/survival credit.
|
||||
func (w *World) Departure(c *Character, route string) error {
|
||||
if HouseID(c) != "" {
|
||||
return errors.New("leave the house before traveling")
|
||||
}
|
||||
if c == nil || !c.Online || c.Sheltered || c.View.RemainingSeconds <= 0 || (c.View.Entity.State != "alive" && c.View.Entity.State != "eligible") {
|
||||
return errors.New("character cannot travel")
|
||||
}
|
||||
|
||||
@@ -190,6 +190,9 @@ func (w *World) Restore(now time.Time) error {
|
||||
}
|
||||
w.dirty = true
|
||||
}
|
||||
if e := w.restoreHousing(); e != nil {
|
||||
return e
|
||||
}
|
||||
if e := w.restoreBuilding(); e != nil {
|
||||
return e
|
||||
}
|
||||
@@ -467,6 +470,10 @@ func (w *World) Connect(id string) error {
|
||||
return nil
|
||||
}
|
||||
func (w *World) Disconnect(id string) {
|
||||
if c := w.Characters[id]; c != nil {
|
||||
c.View.DestroyKey = nil
|
||||
LeaveHouse(c)
|
||||
}
|
||||
if c := w.Characters[id]; c != nil {
|
||||
c.Online = false
|
||||
c.MoveX = 0
|
||||
@@ -517,6 +524,9 @@ func (w *World) Intent(id string, i p.Intent) error {
|
||||
return errors.New("invalid intent")
|
||||
}
|
||||
c.View.ACK = i.Seq
|
||||
if HouseID(c) != "" {
|
||||
return errors.New("leave the house to use world actions")
|
||||
}
|
||||
if c.Sheltered && ((i.Op == "move" && (i.X != 0 || i.Z != 0)) || (i.Op != "move" && i.Op != "heal" && i.Op != "allocate-stat" && i.Op != "choose-vital" && i.Op != "equip" && i.Op != "unequip" && i.Op != "drop")) {
|
||||
c.Sheltered = false
|
||||
w.dirty = true
|
||||
@@ -622,6 +632,8 @@ func (w *World) kill(c *Character, reason string) {
|
||||
e.Position = w.terrain.Position(e.Position.X, e.Position.Z)
|
||||
c.View.Entity.Position = e.Position
|
||||
c.DeathCount++
|
||||
c.View.DestroyKey = nil
|
||||
LeaveHouse(c)
|
||||
c.PendingCast = nil
|
||||
c.RevivalAllowed = false
|
||||
e.ID = "corpse:" + e.ID + ":" + ID()
|
||||
@@ -776,7 +788,9 @@ func (w *World) Advance(now time.Time, dt float64) {
|
||||
c.MoveX = 0
|
||||
c.MoveZ = 0
|
||||
}
|
||||
w.moveCharacter(c, dt)
|
||||
if HouseID(c) == "" {
|
||||
w.moveCharacter(c, dt)
|
||||
}
|
||||
for _, ch := range w.neighbors(c.View.Entity.Position) {
|
||||
active[ch.Key] = true
|
||||
if !w.IsHub() && w.Phase != "won" {
|
||||
@@ -795,6 +809,7 @@ func (w *World) Advance(now time.Time, dt float64) {
|
||||
if !w.IsHub() && w.Phase != "won" {
|
||||
w.updateMobs(active, dt)
|
||||
}
|
||||
w.updateHousingActions()
|
||||
w.updatePowers()
|
||||
if w.Phase != "won" {
|
||||
w.updateCombat(dt)
|
||||
@@ -892,7 +907,7 @@ func (w *World) Snapshot(id string, known map[string]bool) p.Snapshot {
|
||||
}
|
||||
}
|
||||
for _, other := range w.Characters {
|
||||
if other.View.Entity.ID != id && other.Online && other.View.Entity.State != "dead" && visible(other.View.Entity.Position) {
|
||||
if HouseID(other) == "" && other.View.Entity.ID != id && other.Online && other.View.Entity.State != "dead" && visible(other.View.Entity.Position) {
|
||||
s.Entities = append(s.Entities, other.View.Entity)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,6 +8,8 @@ type Protocol struct {
|
||||
CatalogResult *ContentResult `json:"catalogResult,omitempty"`
|
||||
CraftRequest *CraftRequest `json:"craftRequest,omitempty"`
|
||||
CraftResult *CraftResult `json:"craftResult,omitempty"`
|
||||
HouseRequest *HouseRequest `json:"houseRequest,omitempty"`
|
||||
HouseState *HouseState `json:"houseState,omitempty"`
|
||||
Intent Intent `json:"intent"`
|
||||
Snapshot Snapshot `json:"snapshot"`
|
||||
}
|
||||
@@ -18,6 +20,7 @@ type ContentCatalog struct {
|
||||
Crafting *CraftingContent `json:"crafting,omitempty"`
|
||||
EffectSets []EffectSet `json:"effectSets,omitempty"`
|
||||
Gathering *GatheringContent `json:"gathering,omitempty"`
|
||||
HousingVersion *int64 `json:"housingVersion,omitempty"`
|
||||
Items []ItemDefinition `json:"items"`
|
||||
Powers *PowerContent `json:"powers,omitempty"`
|
||||
RequirementSets []RequirementSet `json:"requirementSets,omitempty"`
|
||||
@@ -228,18 +231,19 @@ type ResourceDefinition struct {
|
||||
}
|
||||
|
||||
type ItemDefinition struct {
|
||||
AttackID *string `json:"attackId,omitempty"`
|
||||
CraftPool []CraftStat `json:"craftPool,omitempty"`
|
||||
CraftRolls *int64 `json:"craftRolls,omitempty"`
|
||||
Description string `json:"description"`
|
||||
DropChance float64 `json:"dropChance"`
|
||||
ID string `json:"id"`
|
||||
Modifiers []StatModifier `json:"modifiers"`
|
||||
Name string `json:"name"`
|
||||
Requirements ItemRequirements `json:"requirements"`
|
||||
Slot string `json:"slot"`
|
||||
WeaponType *string `json:"weaponType,omitempty"`
|
||||
Weight float64 `json:"weight"`
|
||||
AttackID *string `json:"attackId,omitempty"`
|
||||
CraftPool []CraftStat `json:"craftPool,omitempty"`
|
||||
CraftRolls *int64 `json:"craftRolls,omitempty"`
|
||||
Description string `json:"description"`
|
||||
DropChance float64 `json:"dropChance"`
|
||||
Furniture *FurnitureProfile `json:"furniture,omitempty"`
|
||||
ID string `json:"id"`
|
||||
Modifiers []StatModifier `json:"modifiers"`
|
||||
Name string `json:"name"`
|
||||
Requirements ItemRequirements `json:"requirements"`
|
||||
Slot string `json:"slot"`
|
||||
WeaponType *string `json:"weaponType,omitempty"`
|
||||
Weight float64 `json:"weight"`
|
||||
}
|
||||
|
||||
type CraftStat struct {
|
||||
@@ -250,6 +254,12 @@ type CraftStat struct {
|
||||
Weight float64 `json:"weight"`
|
||||
}
|
||||
|
||||
type FurnitureProfile struct {
|
||||
Container bool `json:"container"`
|
||||
Depth float64 `json:"depth"`
|
||||
Width float64 `json:"width"`
|
||||
}
|
||||
|
||||
type ItemRequirements struct {
|
||||
Level int64 `json:"level"`
|
||||
Stats map[string]float64 `json:"stats"`
|
||||
@@ -438,18 +448,19 @@ type EffectSetDraft struct {
|
||||
}
|
||||
|
||||
type ItemDraft struct {
|
||||
AttackID *string `json:"attackId,omitempty"`
|
||||
CraftPool []CraftStat `json:"craftPool,omitempty"`
|
||||
CraftRolls *int64 `json:"craftRolls,omitempty"`
|
||||
Description string `json:"description"`
|
||||
DropChance float64 `json:"dropChance"`
|
||||
ID *string `json:"id,omitempty"`
|
||||
Modifiers []StatModifier `json:"modifiers"`
|
||||
Name string `json:"name"`
|
||||
Requirements ItemRequirements `json:"requirements"`
|
||||
Slot string `json:"slot"`
|
||||
WeaponType *string `json:"weaponType,omitempty"`
|
||||
Weight float64 `json:"weight"`
|
||||
AttackID *string `json:"attackId,omitempty"`
|
||||
CraftPool []CraftStat `json:"craftPool,omitempty"`
|
||||
CraftRolls *int64 `json:"craftRolls,omitempty"`
|
||||
Description string `json:"description"`
|
||||
DropChance float64 `json:"dropChance"`
|
||||
Furniture *FurnitureProfile `json:"furniture,omitempty"`
|
||||
ID *string `json:"id,omitempty"`
|
||||
Modifiers []StatModifier `json:"modifiers"`
|
||||
Name string `json:"name"`
|
||||
Requirements ItemRequirements `json:"requirements"`
|
||||
Slot string `json:"slot"`
|
||||
WeaponType *string `json:"weaponType,omitempty"`
|
||||
Weight float64 `json:"weight"`
|
||||
}
|
||||
|
||||
type LootTableDraft struct {
|
||||
@@ -580,6 +591,126 @@ type KnownRecipe struct {
|
||||
Recipe CraftRecipe `json:"recipe"`
|
||||
}
|
||||
|
||||
type HouseRequest struct {
|
||||
HouseID *string `json:"houseId,omitempty"`
|
||||
Item *string `json:"item,omitempty"`
|
||||
Name *string `json:"name,omitempty"`
|
||||
Op string `json:"op"`
|
||||
Permissions map[string]bool `json:"permissions,omitempty"`
|
||||
Quantity *int64 `json:"quantity,omitempty"`
|
||||
RequestID string `json:"requestId"`
|
||||
Revision *int64 `json:"revision,omitempty"`
|
||||
Role *string `json:"role,omitempty"`
|
||||
Target *string `json:"target,omitempty"`
|
||||
X *float64 `json:"x,omitempty"`
|
||||
Z *float64 `json:"z,omitempty"`
|
||||
}
|
||||
|
||||
type HouseState struct {
|
||||
Effective map[string]bool `json:"effective"`
|
||||
Houses []HouseSummary `json:"houses"`
|
||||
People []Entity `json:"people"`
|
||||
Role string `json:"role"`
|
||||
Room *House `json:"room,omitempty"`
|
||||
}
|
||||
|
||||
type HouseSummary struct {
|
||||
Creator bool `json:"creator"`
|
||||
ID string `json:"id"`
|
||||
Keys int64 `json:"keys"`
|
||||
Name string `json:"name"`
|
||||
RecoveryWorld string `json:"recoveryWorld"`
|
||||
Role string `json:"role"`
|
||||
State string `json:"state"`
|
||||
}
|
||||
|
||||
type Entity struct {
|
||||
Depth *float64 `json:"depth,omitempty"`
|
||||
HP float64 `json:"hp"`
|
||||
Height *float64 `json:"height,omitempty"`
|
||||
ID string `json:"id"`
|
||||
Kind string `json:"kind"`
|
||||
MaxHP float64 `json:"maxHp"`
|
||||
Model *string `json:"model,omitempty"`
|
||||
Name string `json:"name"`
|
||||
Position Vec3 `json:"position"`
|
||||
Radius *float64 `json:"radius,omitempty"`
|
||||
RequiredLevel *int64 `json:"requiredLevel,omitempty"`
|
||||
ResourceID *string `json:"resourceId,omitempty"`
|
||||
SkillID *string `json:"skillId,omitempty"`
|
||||
State string `json:"state"`
|
||||
Width *float64 `json:"width,omitempty"`
|
||||
}
|
||||
|
||||
type Vec3 struct {
|
||||
X float64 `json:"x"`
|
||||
Y float64 `json:"y"`
|
||||
Z float64 `json:"z"`
|
||||
}
|
||||
|
||||
type House struct {
|
||||
Floor HouseInventory `json:"floor"`
|
||||
Furniture map[string]HouseFurniture `json:"furniture"`
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Overrides map[string]map[string]bool `json:"overrides"`
|
||||
Permissions map[string]bool `json:"permissions"`
|
||||
Revision int64 `json:"revision"`
|
||||
Roles map[string]string `json:"roles"`
|
||||
Size float64 `json:"size"`
|
||||
State string `json:"state"`
|
||||
}
|
||||
|
||||
type HouseInventory struct {
|
||||
CraftedStacks []CraftedStack `json:"craftedStacks"`
|
||||
Inventory map[string]int64 `json:"inventory"`
|
||||
Items []ItemInstance `json:"items"`
|
||||
StackNames map[string]string `json:"stackNames"`
|
||||
}
|
||||
|
||||
type CraftedStack struct {
|
||||
ID string `json:"id"`
|
||||
Item string `json:"item"`
|
||||
Provenance CraftProvenance `json:"provenance"`
|
||||
Quantity int64 `json:"quantity"`
|
||||
}
|
||||
|
||||
type CraftProvenance struct {
|
||||
At float64 `json:"at"`
|
||||
CharacterID string `json:"characterId"`
|
||||
CrafterName string `json:"crafterName"`
|
||||
Level int64 `json:"level"`
|
||||
Profession string `json:"profession"`
|
||||
RecipeID string `json:"recipeId"`
|
||||
RecipeRevision int64 `json:"recipeRevision"`
|
||||
WorldID string `json:"worldId"`
|
||||
}
|
||||
|
||||
type ItemInstance struct {
|
||||
Attack *CombatAttack `json:"attack,omitempty"`
|
||||
DefinitionID string `json:"definitionId"`
|
||||
Description string `json:"description"`
|
||||
Equippable bool `json:"equippable"`
|
||||
Furniture *FurnitureProfile `json:"furniture,omitempty"`
|
||||
HouseID *string `json:"houseId,omitempty"`
|
||||
ID string `json:"id"`
|
||||
Modifiers []StatModifier `json:"modifiers"`
|
||||
Name string `json:"name"`
|
||||
Provenance *CraftProvenance `json:"provenance,omitempty"`
|
||||
RequirementMessage string `json:"requirementMessage"`
|
||||
Requirements ItemRequirements `json:"requirements"`
|
||||
Slot string `json:"slot"`
|
||||
WeaponType *string `json:"weaponType,omitempty"`
|
||||
Weight float64 `json:"weight"`
|
||||
}
|
||||
|
||||
type HouseFurniture struct {
|
||||
Contents HouseInventory `json:"contents"`
|
||||
Item ItemInstance `json:"item"`
|
||||
X float64 `json:"x"`
|
||||
Z float64 `json:"z"`
|
||||
}
|
||||
|
||||
type Intent struct {
|
||||
Op string `json:"op"`
|
||||
Seq int64 `json:"seq"`
|
||||
@@ -616,30 +747,6 @@ type Chunk struct {
|
||||
Z int64 `json:"z"`
|
||||
}
|
||||
|
||||
type Entity struct {
|
||||
Depth *float64 `json:"depth,omitempty"`
|
||||
HP float64 `json:"hp"`
|
||||
Height *float64 `json:"height,omitempty"`
|
||||
ID string `json:"id"`
|
||||
Kind string `json:"kind"`
|
||||
MaxHP float64 `json:"maxHp"`
|
||||
Model *string `json:"model,omitempty"`
|
||||
Name string `json:"name"`
|
||||
Position Vec3 `json:"position"`
|
||||
Radius *float64 `json:"radius,omitempty"`
|
||||
RequiredLevel *int64 `json:"requiredLevel,omitempty"`
|
||||
ResourceID *string `json:"resourceId,omitempty"`
|
||||
SkillID *string `json:"skillId,omitempty"`
|
||||
State string `json:"state"`
|
||||
Width *float64 `json:"width,omitempty"`
|
||||
}
|
||||
|
||||
type Vec3 struct {
|
||||
X float64 `json:"x"`
|
||||
Y float64 `json:"y"`
|
||||
Z float64 `json:"z"`
|
||||
}
|
||||
|
||||
type GatheringRisk struct {
|
||||
Allowed bool `json:"allowed"`
|
||||
Damage float64 `json:"damage"`
|
||||
@@ -669,6 +776,7 @@ type Character struct {
|
||||
Consumables []GatheringConsumable `json:"consumables,omitempty"`
|
||||
CraftedStacks []CraftedStack `json:"craftedStacks,omitempty"`
|
||||
Crafting map[string]CraftProgress `json:"crafting,omitempty"`
|
||||
DestroyKey *KeyDestruction `json:"destroyKey,omitempty"`
|
||||
DiscoveredRecipes map[string]KnownRecipe `json:"discoveredRecipes,omitempty"`
|
||||
Entity Entity `json:"entity"`
|
||||
Equipment map[string]string `json:"equipment"`
|
||||
@@ -679,6 +787,7 @@ type Character struct {
|
||||
GatheringEffects []TimedGatheringEffect `json:"gatheringEffects,omitempty"`
|
||||
HasKeystone bool `json:"hasKeystone"`
|
||||
HealthChoices int64 `json:"healthChoices"`
|
||||
HouseID *string `json:"houseId,omitempty"`
|
||||
Inventory map[string]int64 `json:"inventory"`
|
||||
Items []ItemInstance `json:"items"`
|
||||
Kills int64 `json:"kills"`
|
||||
@@ -698,24 +807,6 @@ type Character struct {
|
||||
Weapons map[string]WeaponProgress `json:"weapons,omitempty"`
|
||||
}
|
||||
|
||||
type CraftedStack struct {
|
||||
ID string `json:"id"`
|
||||
Item string `json:"item"`
|
||||
Provenance CraftProvenance `json:"provenance"`
|
||||
Quantity int64 `json:"quantity"`
|
||||
}
|
||||
|
||||
type CraftProvenance struct {
|
||||
At float64 `json:"at"`
|
||||
CharacterID string `json:"characterId"`
|
||||
CrafterName string `json:"crafterName"`
|
||||
Level int64 `json:"level"`
|
||||
Profession string `json:"profession"`
|
||||
RecipeID string `json:"recipeId"`
|
||||
RecipeRevision int64 `json:"recipeRevision"`
|
||||
WorldID string `json:"worldId"`
|
||||
}
|
||||
|
||||
type CraftProgress struct {
|
||||
ID string `json:"id"`
|
||||
Level int64 `json:"level"`
|
||||
@@ -725,6 +816,11 @@ type CraftProgress struct {
|
||||
XPToNextLevel int64 `json:"xpToNextLevel"`
|
||||
}
|
||||
|
||||
type KeyDestruction struct {
|
||||
FinishesAt float64 `json:"finishesAt"`
|
||||
KeyID string `json:"keyId"`
|
||||
}
|
||||
|
||||
type SkillProgress struct {
|
||||
EffectiveLevel int64 `json:"effectiveLevel"`
|
||||
Experience StatValue `json:"experience"`
|
||||
@@ -751,22 +847,6 @@ type TimedGatheringEffect struct {
|
||||
Source string `json:"source"`
|
||||
}
|
||||
|
||||
type ItemInstance struct {
|
||||
Attack *CombatAttack `json:"attack,omitempty"`
|
||||
DefinitionID string `json:"definitionId"`
|
||||
Description string `json:"description"`
|
||||
Equippable bool `json:"equippable"`
|
||||
ID string `json:"id"`
|
||||
Modifiers []StatModifier `json:"modifiers"`
|
||||
Name string `json:"name"`
|
||||
Provenance *CraftProvenance `json:"provenance,omitempty"`
|
||||
RequirementMessage string `json:"requirementMessage"`
|
||||
Requirements ItemRequirements `json:"requirements"`
|
||||
Slot string `json:"slot"`
|
||||
WeaponType *string `json:"weaponType,omitempty"`
|
||||
Weight float64 `json:"weight"`
|
||||
}
|
||||
|
||||
type LearnedPower struct {
|
||||
Attack CombatAttack `json:"attack"`
|
||||
Definition PowerDefinition `json:"definition"`
|
||||
|
||||
@@ -146,6 +146,13 @@ func decodeCatalog(version int64, raw string) (content.Catalog, error) {
|
||||
}
|
||||
catalog.RestoreBuilding(b)
|
||||
}
|
||||
if catalog.HousingVersion == 0 {
|
||||
b, e := content.Load()
|
||||
if e != nil {
|
||||
return catalog, e
|
||||
}
|
||||
catalog.RestoreFurniture(b)
|
||||
}
|
||||
return catalog, catalog.Validate()
|
||||
}
|
||||
func (d *DB) Catalog(ctx context.Context) (content.Catalog, error) {
|
||||
|
||||
@@ -73,7 +73,7 @@ func (l *Lease) Craft(ctx context.Context, live *game.World, account string, req
|
||||
request, _ := json.Marshal(req)
|
||||
out, _ := json.Marshal(result)
|
||||
receipt := &craftReceipt{req.ID, account, req.CharacterID, string(request), string(out)}
|
||||
if e = l.save(ctx, staged, "", nil, "", receipt, nil); e != nil {
|
||||
if e = l.save(ctx, staged, "", nil, "", receipt, nil, nil); e != nil {
|
||||
return p.CraftResult{}, e
|
||||
}
|
||||
// Retain character pointers captured by existing WebSocket handlers.
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"aeternalis/server/internal/game"
|
||||
p "aeternalis/server/internal/protocol"
|
||||
"slices"
|
||||
)
|
||||
|
||||
func houseItemAction(w *game.World, c *game.Character, h *houseRecord, r HouseRequest, allowed map[string]bool) error {
|
||||
rules := w.Balance.Housing
|
||||
switch r.Op {
|
||||
case "place":
|
||||
if !allowed["placeFurniture"] {
|
||||
return houseError("placing furniture is not permitted")
|
||||
}
|
||||
if len(h.View.Furniture) >= rules.MaxFurniture {
|
||||
return houseError("furniture limit")
|
||||
}
|
||||
for i, item := range c.View.Items {
|
||||
if item.ID == r.Item {
|
||||
if !game.FurnitureFits(h.View, "", item, r.X, r.Z) {
|
||||
return houseError("furniture overlaps or leaves the room")
|
||||
}
|
||||
h.View.Furniture[item.ID] = p.HouseFurniture{Item: item, X: r.X, Z: r.Z, Contents: game.EmptyHouseInventory()}
|
||||
c.View.Items = append(c.View.Items[:i:i], c.View.Items[i+1:]...)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return houseError("carried furniture required")
|
||||
case "move":
|
||||
if !allowed["moveFurniture"] {
|
||||
return houseError("moving furniture is not permitted")
|
||||
}
|
||||
f, ok := h.View.Furniture[r.Target]
|
||||
if !ok || !game.FurnitureFits(h.View, r.Target, f.Item, r.X, r.Z) {
|
||||
return houseError("invalid furniture position")
|
||||
}
|
||||
f.X = r.X
|
||||
f.Z = r.Z
|
||||
h.View.Furniture[r.Target] = f
|
||||
return nil
|
||||
case "pickup-furniture":
|
||||
if !allowed["pickupItems"] {
|
||||
return houseError("picking up items is not permitted")
|
||||
}
|
||||
f, ok := h.View.Furniture[r.Target]
|
||||
if !ok || len(c.View.Items) >= rules.MaxItems {
|
||||
return houseError("furniture unavailable or inventory full")
|
||||
}
|
||||
if len(f.Contents.Items) > 0 {
|
||||
return houseError("empty the furniture first")
|
||||
}
|
||||
for _, n := range f.Contents.Inventory {
|
||||
if n > 0 {
|
||||
return houseError("empty the furniture first")
|
||||
}
|
||||
}
|
||||
c.View.Items = append(c.View.Items, f.Item)
|
||||
delete(h.View.Furniture, r.Target)
|
||||
return nil
|
||||
case "deposit", "withdraw", "drop", "pickup":
|
||||
permission := map[string]string{"deposit": "depositItems", "withdraw": "pickupItems", "drop": "dropItems", "pickup": "pickupItems"}[r.Op]
|
||||
if !allowed[permission] || r.Op == "withdraw" && !allowed["openFurniture"] {
|
||||
return houseError("item movement is not permitted")
|
||||
}
|
||||
player := game.HouseInventoryOf(c)
|
||||
contents := h.View.Floor
|
||||
f := p.HouseFurniture{}
|
||||
if r.Op == "deposit" || r.Op == "withdraw" {
|
||||
var ok bool
|
||||
f, ok = h.View.Furniture[r.Target]
|
||||
if !ok || f.Item.Furniture == nil || !f.Item.Furniture.Container {
|
||||
return houseError("choose storage furniture")
|
||||
}
|
||||
contents = f.Contents
|
||||
}
|
||||
if r.Op == "deposit" || r.Op == "drop" {
|
||||
// Do not permit the house's access keys to become locked inside that same house.
|
||||
for _, i := range player.Items {
|
||||
if i.ID == r.Item && i.HouseID != nil && *i.HouseID == h.View.ID {
|
||||
return houseError("keep this house's key outside its own storage and floor")
|
||||
}
|
||||
}
|
||||
if len(contents.Items) >= rules.MaxItems {
|
||||
return houseError("storage full")
|
||||
}
|
||||
if e := game.MoveHouseItem(&player, &contents, r.Item, r.Quantity); e != nil {
|
||||
return houseError(e.Error())
|
||||
}
|
||||
if c.View.DestroyKey != nil && c.View.DestroyKey.KeyID == r.Item {
|
||||
c.View.DestroyKey = nil
|
||||
}
|
||||
} else {
|
||||
if len(player.Items) >= rules.MaxItems {
|
||||
return houseError("inventory full")
|
||||
}
|
||||
if e := game.MoveHouseItem(&contents, &player, r.Item, r.Quantity); e != nil {
|
||||
return houseError(e.Error())
|
||||
}
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
if e := game.ValidateHouseInventory(player, seen); e != nil {
|
||||
return houseError(e.Error())
|
||||
}
|
||||
if e := game.ValidateHouseInventory(contents, seen); e != nil {
|
||||
return houseError(e.Error())
|
||||
}
|
||||
game.SetHouseInventory(c, player)
|
||||
for slot, id := range c.View.Equipment {
|
||||
if !slices.ContainsFunc(c.View.Items, func(i p.ItemInstance) bool { return i.ID == id }) {
|
||||
delete(c.View.Equipment, slot)
|
||||
}
|
||||
}
|
||||
if r.Op == "deposit" || r.Op == "withdraw" {
|
||||
f.Contents = contents
|
||||
h.View.Furniture[r.Target] = f
|
||||
} else {
|
||||
h.View.Floor = contents
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return houseError("unknown house action")
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"aeternalis/server/internal/game"
|
||||
p "aeternalis/server/internal/protocol"
|
||||
"context"
|
||||
"database/sql"
|
||||
"slices"
|
||||
)
|
||||
|
||||
func (d *DB) destroyHouseKey(ctx context.Context, tx *sql.Tx, key, house string, visited map[string]bool) error {
|
||||
h, e := d.readHouse(ctx, tx, house, true)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if _, e = tx.ExecContext(ctx, d.q(`UPDATE house_keys SET state='destroyed' WHERE id=? AND house_id=? AND state='active'`), key, house); e != nil {
|
||||
return e
|
||||
}
|
||||
count, e := d.keyCount(ctx, tx, house)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if count != 0 {
|
||||
return nil
|
||||
}
|
||||
return d.archiveHouse(ctx, tx, h, visited)
|
||||
}
|
||||
func (d *DB) archiveHouse(ctx context.Context, tx *sql.Tx, h *houseRecord, visited map[string]bool) error {
|
||||
if visited[h.View.ID] {
|
||||
return nil
|
||||
}
|
||||
visited[h.View.ID] = true
|
||||
h.View.State = "archived"
|
||||
ended, e := d.recoveryEnded(ctx, tx, h)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if ended {
|
||||
// Purging stored keys also updates their houses; registry counts never retain
|
||||
// keys whose containing inventory has been permanently removed.
|
||||
keys := []p.ItemInstance{}
|
||||
keys = append(keys, h.View.Floor.Items...)
|
||||
for _, f := range h.View.Furniture {
|
||||
keys = append(keys, f.Contents.Items...)
|
||||
}
|
||||
slices.SortFunc(keys, func(a, b p.ItemInstance) int {
|
||||
if a.ID < b.ID {
|
||||
return -1
|
||||
}
|
||||
if a.ID > b.ID {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
})
|
||||
purgeHouse(h)
|
||||
if e = d.writeHouse(ctx, tx, h); e != nil {
|
||||
return e
|
||||
}
|
||||
for _, key := range keys {
|
||||
if key.HouseID != nil {
|
||||
if e = d.destroyHouseKey(ctx, tx, key.ID, *key.HouseID, visited); e != nil {
|
||||
return e
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return d.writeHouse(ctx, tx, h)
|
||||
}
|
||||
func (d *DB) syncHousing(ctx context.Context, tx *sql.Tx, w *game.World) error {
|
||||
ids := make([]string, 0, len(w.Characters))
|
||||
for id := range w.Characters {
|
||||
ids = append(ids, id)
|
||||
}
|
||||
slices.Sort(ids)
|
||||
for _, id := range ids {
|
||||
c := w.Characters[id]
|
||||
var ownerWorld, state string
|
||||
if e := tx.QueryRowContext(ctx, d.q(`SELECT world_id,state FROM character_records WHERE character_id=?`), id).Scan(&ownerWorld, &state); e != nil {
|
||||
return e
|
||||
}
|
||||
// An old source copy may checkpoint, but cannot touch a transferred key.
|
||||
if ownerWorld != w.ID || state == "transit" {
|
||||
continue
|
||||
}
|
||||
if c.View.Entity.State == "dead" && c.DiedAt != nil && c.RevivalCorpse != "" {
|
||||
// Compare death time so an old source-world copy cannot replace a later death.
|
||||
if _, e := tx.ExecContext(ctx, d.q(`UPDATE houses SET death_world=?,death_id=?,death_at=? WHERE creator_character=? AND death_at<?`), w.ID, c.RevivalCorpse, c.DiedAt.UnixMilli(), id, c.DiedAt.UnixMilli()); e != nil {
|
||||
return e
|
||||
}
|
||||
}
|
||||
if a := c.View.DestroyKey; a != nil && w.NowSeconds() >= a.FinishesAt {
|
||||
c.View.DestroyKey = nil
|
||||
if c.Online && !c.Sheltered && c.View.RemainingSeconds > 0 && (c.View.Entity.State == "alive" || c.View.Entity.State == "eligible") {
|
||||
for i, key := range c.View.Items {
|
||||
if key.ID == a.KeyID && key.HouseID != nil {
|
||||
if e := d.destroyHouseKey(ctx, tx, key.ID, *key.HouseID, map[string]bool{}); e != nil {
|
||||
return e
|
||||
}
|
||||
c.View.Items = append(c.View.Items[:i:i], c.View.Items[i+1:]...)
|
||||
w.RefreshStats(c)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if house := game.HouseID(c); house != "" {
|
||||
h, e := d.readHouse(ctx, tx, house, false)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
role, e := d.houseRole(ctx, tx, h, c)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if h.View.State != "active" || role == "" || !c.Online || c.View.Entity.State == "dead" || c.View.RemainingSeconds <= 0 {
|
||||
game.LeaveHouse(c)
|
||||
}
|
||||
}
|
||||
}
|
||||
if w.Phase == "lost" {
|
||||
rows, e := tx.QueryContext(ctx, d.q(`SELECT id FROM houses WHERE death_world=? AND state='archived' ORDER BY id`), w.ID)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
houses := []string{}
|
||||
for rows.Next() {
|
||||
var id string
|
||||
if e = rows.Scan(&id); e != nil {
|
||||
rows.Close()
|
||||
return e
|
||||
}
|
||||
houses = append(houses, id)
|
||||
}
|
||||
e = rows.Err()
|
||||
rows.Close()
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
for _, id := range houses {
|
||||
h, e := d.readHouse(ctx, tx, id, true)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if h.View.State == "archived" {
|
||||
if e = d.archiveHouse(ctx, tx, h, map[string]bool{}); e != nil {
|
||||
return e
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"aeternalis/server/content"
|
||||
"aeternalis/server/internal/game"
|
||||
p "aeternalis/server/internal/protocol"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestHouseDeathTravelAndRecovery(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
db, e := Open(ctx, "file:"+filepath.ToSlash(filepath.Join(t.TempDir(), "recovery.db")))
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
defer db.Close()
|
||||
b, _ := content.Load()
|
||||
now := time.Now().UTC()
|
||||
hub := game.New("home", 1, now, b)
|
||||
c, _ := hub.Join("creator", "Creator")
|
||||
c.WorldsSurvived = 1
|
||||
_ = hub.Connect(c.View.Entity.ID)
|
||||
hub.Kind = "hub"
|
||||
hub.Phase = "hub"
|
||||
hl, _, e := db.Acquire(ctx, hub)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e = hl.Save(ctx, hub, ""); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
act := func(l *Lease, w *game.World, c *game.Character, r HouseRequest) {
|
||||
t.Helper()
|
||||
r.RequestID = game.ID()
|
||||
if e = l.HouseAction(ctx, w, c.Account, r); e != nil {
|
||||
t.Fatal(r.Op, e)
|
||||
}
|
||||
}
|
||||
state := func(w *game.World, c *game.Character) p.HouseState {
|
||||
t.Helper()
|
||||
v, e := db.HouseState(ctx, w, c.Account)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
return v
|
||||
}
|
||||
act(hl, hub, c, HouseRequest{Op: "create", Name: "Recovery home"})
|
||||
house := state(hub, c).Houses[0].ID
|
||||
key := c.View.Items[len(c.View.Items)-1].ID
|
||||
act(hl, hub, c, HouseRequest{Op: "enter", HouseID: house})
|
||||
c.View.Inventory["wood"] = 12
|
||||
act(hl, hub, c, HouseRequest{Op: "drop", HouseID: house, Item: "wood", Quantity: 7})
|
||||
act(hl, hub, c, HouseRequest{Op: "leave"})
|
||||
next := game.New("doomed", 2, now, b)
|
||||
nl, _, e := db.Acquire(ctx, next)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
// Traveling cancels the action, retains the exact key, and never creates another owner copy.
|
||||
act(hl, hub, c, HouseRequest{Op: "destroy-key", Item: key})
|
||||
oldWorld := *hub
|
||||
oldWorld.Characters = map[string]*game.Character{c.View.Entity.ID: c}
|
||||
tr, e := hl.PrepareTravel(ctx, hub, c.Account, game.ID(), next.ID, "hub")
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
_, e = nl.AcceptTravel(ctx, next, c.Account, tr.ID)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
c = next.ForAccount(c.Account)
|
||||
_ = next.Connect(c.View.Entity.ID)
|
||||
if c.View.DestroyKey != nil || c.View.Items[len(c.View.Items)-1].ID != key {
|
||||
t.Fatal("travel lost key or retained pending destruction")
|
||||
}
|
||||
// Saving an old source-world copy cannot complete its now-expired key action.
|
||||
oldWorld.Advance(now.Add(4*time.Second), 4)
|
||||
if e = hl.Save(ctx, &oldWorld, ""); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
var keys int
|
||||
if e = db.sql.QueryRow(`SELECT COUNT(*) FROM house_keys WHERE state='active'`).Scan(&keys); e != nil || keys != 1 {
|
||||
t.Fatal("stale source destroyed traveling key", e)
|
||||
}
|
||||
act(nl, next, c, HouseRequest{Op: "destroy-key", Item: key})
|
||||
c.View.Entity.HP = 0
|
||||
next.Advance(now.Add(time.Second), 1)
|
||||
if e = nl.Save(ctx, next, ""); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
corpse := next.Corpses[c.RevivalCorpse]
|
||||
if corpse == nil || c.View.DestroyKey != nil {
|
||||
t.Fatal("death failed to interrupt")
|
||||
}
|
||||
found := false
|
||||
for _, i := range corpse.Items {
|
||||
if i.ID == key {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatal("interrupted key missing from corpse")
|
||||
}
|
||||
// Replacement inherits no key. Recovery remains gated on that replacement's survival.
|
||||
replacement, e := next.Join(c.Account, "Replacement")
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
_ = next.Connect(replacement.View.Entity.ID)
|
||||
replacement.View.Inventory["escape_stone"] = 1
|
||||
if e = nl.Save(ctx, next, ""); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
// Remove the deliberately stale fixture copy from the hub before arrival.
|
||||
delete(hub.Characters, c.View.Entity.ID)
|
||||
tr, e = nl.PrepareTravel(ctx, next, replacement.Account, game.ID(), hub.ID, "escape")
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
_, e = hl.AcceptTravel(ctx, hub, replacement.Account, tr.ID)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
replacement = hub.ForAccount(replacement.Account)
|
||||
_ = hub.Connect(replacement.View.Entity.ID)
|
||||
if len(replacement.View.Items) != 1 {
|
||||
t.Fatal("replacement unexpectedly inherited items", replacement.View.Items)
|
||||
} // Starting knife only.
|
||||
e = hl.HouseAction(ctx, hub, replacement.Account, HouseRequest{RequestID: game.ID(), Op: "recover", HouseID: house})
|
||||
if !errors.Is(e, ErrHousing) {
|
||||
t.Fatal("unproven replacement recovered", e)
|
||||
}
|
||||
replacement.WorldsSurvived = 1
|
||||
act(hl, hub, replacement, HouseRequest{Op: "recover", HouseID: house})
|
||||
if v := state(hub, replacement); v.Houses[0].Keys != 2 {
|
||||
t.Fatal("creator recovery invalidated corpse key")
|
||||
}
|
||||
act(hl, hub, replacement, HouseRequest{Op: "enter", HouseID: house})
|
||||
if state(hub, replacement).Room.Floor.Inventory["wood"] != 7 {
|
||||
t.Fatal("recovery recreated or lost contents")
|
||||
}
|
||||
// Restart exits the room and cancels an unfinished destruction, retaining its key and contents.
|
||||
key2 := replacement.View.Items[len(replacement.View.Items)-1].ID
|
||||
act(hl, hub, replacement, HouseRequest{Op: "destroy-key", Item: key2})
|
||||
raw, _ := json.Marshal(hub)
|
||||
var restored game.World
|
||||
if e = json.Unmarshal(raw, &restored); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e = restored.Restore(now.Add(10 * time.Second)); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
rc := restored.ForAccount(replacement.Account)
|
||||
if rc == nil || rc.View.DestroyKey != nil || game.HouseID(rc) != "" {
|
||||
t.Fatal("restart preserved pending room/action")
|
||||
}
|
||||
next.Phase = "lost"
|
||||
if e = nl.Save(ctx, next, ""); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
// An active house remains owned by valid keys when the recovery world is destroyed.
|
||||
if state(hub, replacement).Houses[0].State != "active" {
|
||||
t.Fatal("death-world loss deleted key-owned house")
|
||||
}
|
||||
e = hl.HouseAction(ctx, hub, replacement.Account, HouseRequest{RequestID: game.ID(), Op: "recover", HouseID: house})
|
||||
if !errors.Is(e, ErrHousing) {
|
||||
t.Fatal("recovery after world destruction", e)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"aeternalis/server/internal/game"
|
||||
p "aeternalis/server/internal/protocol"
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"slices"
|
||||
)
|
||||
|
||||
func (d *DB) HouseState(ctx context.Context, w *game.World, account string) (p.HouseState, error) {
|
||||
out := p.HouseState{Houses: []p.HouseSummary{}, People: []p.Entity{}, Effective: map[string]bool{}}
|
||||
c := w.ForAccount(account)
|
||||
if c == nil {
|
||||
return out, houseError("living character required")
|
||||
}
|
||||
tx, e := d.sql.BeginTx(ctx, nil)
|
||||
if e != nil {
|
||||
return out, e
|
||||
}
|
||||
defer tx.Rollback()
|
||||
var world string
|
||||
e = tx.QueryRowContext(ctx, d.q(`SELECT world_id FROM character_records WHERE character_id=? AND state IN ('alive','eligible')`), c.View.Entity.ID).Scan(&world)
|
||||
if errors.Is(e, sql.ErrNoRows) || e == nil && world != w.ID {
|
||||
return out, houseError("character is in another world")
|
||||
}
|
||||
if e != nil {
|
||||
return out, e
|
||||
}
|
||||
ids := map[string]bool{}
|
||||
rows, e := tx.QueryContext(ctx, d.q(`SELECT id FROM houses WHERE creator_account=? UNION SELECT house_id FROM house_invites WHERE character_id=?`), account, c.View.Entity.ID)
|
||||
if e != nil {
|
||||
return out, e
|
||||
}
|
||||
for rows.Next() {
|
||||
var id string
|
||||
if e = rows.Scan(&id); e != nil {
|
||||
rows.Close()
|
||||
return out, e
|
||||
}
|
||||
ids[id] = true
|
||||
}
|
||||
e = rows.Err()
|
||||
rows.Close()
|
||||
if e != nil {
|
||||
return out, e
|
||||
}
|
||||
for _, i := range c.View.Items {
|
||||
if i.HouseID != nil {
|
||||
ids[*i.HouseID] = true
|
||||
}
|
||||
}
|
||||
sorted := make([]string, 0, len(ids))
|
||||
for id := range ids {
|
||||
sorted = append(sorted, id)
|
||||
}
|
||||
slices.Sort(sorted)
|
||||
for _, id := range sorted {
|
||||
h, e := d.readHouse(ctx, tx, id, false)
|
||||
if e != nil {
|
||||
return out, e
|
||||
}
|
||||
role, e := d.houseRole(ctx, tx, h, c)
|
||||
if e != nil {
|
||||
return out, e
|
||||
}
|
||||
n, e := d.keyCount(ctx, tx, id)
|
||||
if e != nil {
|
||||
return out, e
|
||||
}
|
||||
out.Houses = append(out.Houses, p.HouseSummary{ID: id, Name: h.View.Name, State: h.View.State, Role: role, Creator: h.CreatorAccount == account, RecoveryWorld: h.DeathWorld, Keys: n})
|
||||
if game.HouseID(c) == id && h.View.State == "active" && role != "" {
|
||||
out.Role = role
|
||||
out.Effective = housePermissions(h, c, role)
|
||||
if !out.Effective["openFurniture"] {
|
||||
for key, f := range h.View.Furniture {
|
||||
f.Contents = game.EmptyHouseInventory()
|
||||
h.View.Furniture[key] = f
|
||||
}
|
||||
}
|
||||
if role != "owner" && role != "co-owner" {
|
||||
h.View.Roles = map[string]string{}
|
||||
h.View.Overrides = map[string]map[string]bool{}
|
||||
h.View.Permissions = map[string]bool{}
|
||||
}
|
||||
out.Room = &h.View
|
||||
}
|
||||
}
|
||||
for _, other := range w.Characters {
|
||||
if other.View.Entity.State == "alive" || other.View.Entity.State == "eligible" {
|
||||
v := p.Entity{ID: other.View.Entity.ID, Name: other.View.Entity.Name, Kind: "player"}
|
||||
out.People = append(out.People, v)
|
||||
}
|
||||
}
|
||||
// Keep invitations understandable after guests switch hubs or disconnect.
|
||||
if out.Room != nil && (out.Role == "owner" || out.Role == "co-owner") {
|
||||
for id := range out.Room.Roles {
|
||||
if slices.ContainsFunc(out.People, func(v p.Entity) bool { return v.ID == id }) {
|
||||
continue
|
||||
}
|
||||
var name string
|
||||
e := tx.QueryRowContext(ctx, d.q(`SELECT name FROM character_records WHERE character_id=?`), id).Scan(&name)
|
||||
if errors.Is(e, sql.ErrNoRows) {
|
||||
continue
|
||||
}
|
||||
if e != nil {
|
||||
return out, e
|
||||
}
|
||||
out.People = append(out.People, p.Entity{ID: id, Name: name, Kind: "player"})
|
||||
}
|
||||
}
|
||||
slices.SortFunc(out.People, func(a, b p.Entity) int {
|
||||
if a.Name < b.Name {
|
||||
return -1
|
||||
}
|
||||
if a.Name > b.Name {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
})
|
||||
return out, tx.Commit()
|
||||
}
|
||||
@@ -0,0 +1,386 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"aeternalis/server/internal/game"
|
||||
p "aeternalis/server/internal/protocol"
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"slices"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var ErrHousing = errors.New("housing action rejected")
|
||||
|
||||
func houseError(s string) error { return fmt.Errorf("%w: %s", ErrHousing, s) }
|
||||
|
||||
type HouseRequest struct {
|
||||
RequestID string `json:"requestId"`
|
||||
Op string `json:"op"`
|
||||
HouseID string `json:"houseId"`
|
||||
Target string `json:"target"`
|
||||
Item string `json:"item"`
|
||||
Quantity int64 `json:"quantity"`
|
||||
X float64 `json:"x"`
|
||||
Z float64 `json:"z"`
|
||||
Role string `json:"role"`
|
||||
Name string `json:"name"`
|
||||
Permissions map[string]bool `json:"permissions"`
|
||||
Revision int64 `json:"revision"`
|
||||
}
|
||||
type houseMutation struct {
|
||||
Account string
|
||||
Request HouseRequest
|
||||
}
|
||||
type houseRecord struct {
|
||||
View p.House
|
||||
CreatorAccount, CreatorCharacter, DeathWorld, DeathID string
|
||||
}
|
||||
|
||||
func (d *DB) readHouse(ctx context.Context, tx *sql.Tx, id string, lock bool) (*houseRecord, error) {
|
||||
if lock {
|
||||
if _, e := tx.ExecContext(ctx, d.q(`UPDATE houses SET state=state WHERE id=?`), id); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
}
|
||||
var raw string
|
||||
h := &houseRecord{}
|
||||
e := tx.QueryRowContext(ctx, d.q(`SELECT creator_account,creator_character,death_world,death_id,document FROM houses WHERE id=?`), id).Scan(&h.CreatorAccount, &h.CreatorCharacter, &h.DeathWorld, &h.DeathID, &raw)
|
||||
if errors.Is(e, sql.ErrNoRows) {
|
||||
return nil, houseError("house not found")
|
||||
}
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
if e = json.Unmarshal([]byte(raw), &h.View); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
return h, nil
|
||||
}
|
||||
func (d *DB) writeHouse(ctx context.Context, tx *sql.Tx, h *houseRecord) error {
|
||||
seen := map[string]bool{}
|
||||
if e := game.ValidateHouseInventory(h.View.Floor, seen); e != nil {
|
||||
return houseError(e.Error())
|
||||
}
|
||||
for id, f := range h.View.Furniture {
|
||||
if id != f.Item.ID || seen[id] || f.Item.Furniture == nil {
|
||||
return houseError("invalid furniture identity")
|
||||
}
|
||||
seen[id] = true
|
||||
if e := game.ValidateHouseInventory(f.Contents, seen); e != nil {
|
||||
return houseError(e.Error())
|
||||
}
|
||||
}
|
||||
h.View.Revision++
|
||||
raw, e := json.Marshal(h.View)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
_, e = tx.ExecContext(ctx, d.q(`UPDATE houses SET state=?,document=? WHERE id=?`), h.View.State, string(raw), h.View.ID)
|
||||
return e
|
||||
}
|
||||
func (d *DB) houseRole(ctx context.Context, tx *sql.Tx, h *houseRecord, c *game.Character) (string, error) {
|
||||
for _, i := range c.View.Items {
|
||||
if i.HouseID == nil || *i.HouseID != h.View.ID {
|
||||
continue
|
||||
}
|
||||
var n int
|
||||
if e := tx.QueryRowContext(ctx, d.q(`SELECT COUNT(*) FROM house_keys WHERE id=? AND house_id=? AND state='active'`), i.ID, h.View.ID).Scan(&n); e != nil {
|
||||
return "", e
|
||||
}
|
||||
if n == 1 {
|
||||
return "owner", nil
|
||||
}
|
||||
}
|
||||
return h.View.Roles[c.View.Entity.ID], nil
|
||||
}
|
||||
func housePermissions(h *houseRecord, c *game.Character, role string) map[string]bool {
|
||||
out := map[string]bool{}
|
||||
for _, key := range game.HousePermissions {
|
||||
out[key] = role == "owner" || role == "co-owner" || h.View.Permissions[key]
|
||||
if role != "owner" && role != "co-owner" {
|
||||
if v, ok := h.View.Overrides[c.View.Entity.ID][key]; ok {
|
||||
out[key] = v
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
func (d *DB) keyCount(ctx context.Context, tx *sql.Tx, id string) (int64, error) {
|
||||
var n int64
|
||||
e := tx.QueryRowContext(ctx, d.q(`SELECT COUNT(*) FROM house_keys WHERE house_id=? AND state='active'`), id).Scan(&n)
|
||||
return n, e
|
||||
}
|
||||
func (d *DB) issueKey(ctx context.Context, tx *sql.Tx, h *houseRecord, c *game.Character, max int) error {
|
||||
if len(c.View.Items) >= max {
|
||||
return houseError("inventory full")
|
||||
}
|
||||
count, e := d.keyCount(ctx, tx, h.View.ID)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if count >= 128 {
|
||||
return houseError("house key limit reached")
|
||||
}
|
||||
id := game.ID()
|
||||
_, e = tx.ExecContext(ctx, d.q(`INSERT INTO house_keys(id,house_id,state) VALUES(?,?,'active')`), id, h.View.ID)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
houseID := h.View.ID
|
||||
c.View.Items = append(c.View.Items, p.ItemInstance{ID: id, DefinitionID: "house_key", Name: h.View.Name + " key", Description: "A bearer key granting owner rights. Destroying it takes three seconds.", Slot: "bag", Weight: .1, HouseID: &houseID, Requirements: p.ItemRequirements{Level: 1, Stats: map[string]float64{}, Titles: []string{}}, Modifiers: []p.StatModifier{}})
|
||||
return nil
|
||||
}
|
||||
func (d *DB) recoveryEnded(ctx context.Context, tx *sql.Tx, h *houseRecord) (bool, error) {
|
||||
if h.DeathWorld == "" {
|
||||
return false, nil
|
||||
}
|
||||
var raw string
|
||||
e := tx.QueryRowContext(ctx, d.q(`SELECT snapshot FROM worlds WHERE id=?`), h.DeathWorld).Scan(&raw)
|
||||
if errors.Is(e, sql.ErrNoRows) {
|
||||
return false, nil
|
||||
}
|
||||
if e != nil {
|
||||
return false, e
|
||||
}
|
||||
var w struct{ Phase string }
|
||||
if e = json.Unmarshal([]byte(raw), &w); e != nil {
|
||||
return false, e
|
||||
}
|
||||
return w.Phase == "lost", nil
|
||||
}
|
||||
func purgeHouse(h *houseRecord) {
|
||||
h.View.State = "purged"
|
||||
h.View.Floor = game.EmptyHouseInventory()
|
||||
h.View.Furniture = map[string]p.HouseFurniture{}
|
||||
h.View.Roles = map[string]string{}
|
||||
h.View.Overrides = map[string]map[string]bool{}
|
||||
}
|
||||
func (l *Lease) HouseAction(ctx context.Context, w *game.World, account string, r HouseRequest) error {
|
||||
if !catalogRequestID.MatchString(r.RequestID) || len(r.HouseID) > 64 || len(r.Item) > 100 || len(r.Target) > 100 || len(r.Name) > 80 || len(r.Permissions) > 6 {
|
||||
return houseError("invalid request")
|
||||
}
|
||||
if e := l.save(ctx, w, "", nil, "", nil, nil, &houseMutation{account, r}); e != nil {
|
||||
return e
|
||||
}
|
||||
if c := w.ForAccount(account); c != nil && game.HouseID(c) != "" {
|
||||
c.MoveX = 0
|
||||
c.MoveZ = 0
|
||||
c.PendingCast = nil
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (d *DB) applyHouse(ctx context.Context, tx *sql.Tx, w *game.World, m *houseMutation) error {
|
||||
r := m.Request
|
||||
c := w.ForAccount(m.Account)
|
||||
if c == nil || !c.Online || c.Sheltered || c.View.RemainingSeconds <= 0 || w.Phase == "lost" {
|
||||
return houseError("active character required")
|
||||
}
|
||||
var current, world, state string
|
||||
if e := tx.QueryRowContext(ctx, d.q(`SELECT character_id,world_id,state FROM character_records WHERE account_id=? AND state IN ('alive','eligible','transit')`), m.Account).Scan(¤t, &world, &state); e != nil {
|
||||
return e
|
||||
}
|
||||
if current != c.View.Entity.ID || world != w.ID || state == "transit" {
|
||||
return houseError("character has moved")
|
||||
}
|
||||
raw, _ := json.Marshal(r)
|
||||
var previous string
|
||||
e := tx.QueryRowContext(ctx, d.q(`SELECT request FROM house_receipts WHERE account_id=? AND id=?`), m.Account, r.RequestID).Scan(&previous)
|
||||
if e == nil {
|
||||
if previous != string(raw) {
|
||||
return houseError("request already used")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if !errors.Is(e, sql.ErrNoRows) {
|
||||
return e
|
||||
}
|
||||
if e = d.mutateHouse(ctx, tx, w, c, r); e != nil {
|
||||
return e
|
||||
}
|
||||
w.RefreshStats(c)
|
||||
_, e = tx.ExecContext(ctx, d.q(`INSERT INTO house_receipts(account_id,id,request) VALUES(?,?,?)`), m.Account, r.RequestID, string(raw))
|
||||
return e
|
||||
}
|
||||
func (d *DB) mutateHouse(ctx context.Context, tx *sql.Tx, w *game.World, c *game.Character, r HouseRequest) error {
|
||||
rules := w.Balance.Housing
|
||||
if r.Op == "cancel-key" {
|
||||
c.View.DestroyKey = nil
|
||||
return nil
|
||||
}
|
||||
if r.Op == "destroy-key" {
|
||||
if c.View.DestroyKey != nil {
|
||||
return houseError("already destroying a key")
|
||||
}
|
||||
for _, i := range c.View.Items {
|
||||
if i.ID == r.Item && i.HouseID != nil {
|
||||
h, e := d.readHouse(ctx, tx, *i.HouseID, true)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
var n int
|
||||
if e = tx.QueryRowContext(ctx, d.q(`SELECT COUNT(*) FROM house_keys WHERE id=? AND house_id=? AND state='active'`), i.ID, h.View.ID).Scan(&n); e != nil {
|
||||
return e
|
||||
}
|
||||
if n != 1 {
|
||||
return houseError("key is invalid")
|
||||
}
|
||||
c.View.DestroyKey = &p.KeyDestruction{KeyID: i.ID, FinishesAt: w.NowSeconds() + rules.KeySeconds}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return houseError("carried key required")
|
||||
}
|
||||
if !w.IsHub() {
|
||||
return houseError("housing is accessed from a hub")
|
||||
}
|
||||
if r.Op == "leave" {
|
||||
game.LeaveHouse(c)
|
||||
return nil
|
||||
}
|
||||
if r.Op == "create" {
|
||||
if c.WorldsSurvived < 1 || game.HouseID(c) != "" {
|
||||
return houseError("survive a world and return to the hub before creating a house")
|
||||
}
|
||||
var count int
|
||||
if e := tx.QueryRowContext(ctx, d.q(`SELECT COUNT(*) FROM houses WHERE creator_account=? AND state<>'purged'`), c.Account).Scan(&count); e != nil {
|
||||
return e
|
||||
}
|
||||
if count > 0 {
|
||||
return houseError("you already created a recoverable house")
|
||||
}
|
||||
name := strings.TrimSpace(r.Name)
|
||||
if name == "" {
|
||||
return houseError("house name required")
|
||||
}
|
||||
h := &houseRecord{CreatorAccount: c.Account, CreatorCharacter: c.View.Entity.ID, View: p.House{ID: game.ID(), Name: name, State: "active", Size: rules.RoomSize, Permissions: map[string]bool{}, Overrides: map[string]map[string]bool{}, Roles: map[string]string{}, Furniture: map[string]p.HouseFurniture{}, Floor: game.EmptyHouseInventory()}}
|
||||
raw, _ := json.Marshal(h.View)
|
||||
if _, e := tx.ExecContext(ctx, d.q(`INSERT INTO houses(id,creator_account,creator_character,death_world,death_id,state,document) VALUES(?,?,?,'','','active',?)`), h.View.ID, c.Account, c.View.Entity.ID, string(raw)); e != nil {
|
||||
return e
|
||||
}
|
||||
if e := d.issueKey(ctx, tx, h, c, rules.MaxItems); e != nil {
|
||||
return e
|
||||
}
|
||||
return d.writeHouse(ctx, tx, h)
|
||||
}
|
||||
h, e := d.readHouse(ctx, tx, r.HouseID, true)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
ended, e := d.recoveryEnded(ctx, tx, h)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if r.Op == "recover" {
|
||||
if h.CreatorAccount != c.Account || c.WorldsSurvived < 1 || h.DeathID == "" || h.DeathWorld == "" || ended || h.View.State == "purged" {
|
||||
return houseError("creator recovery unavailable")
|
||||
}
|
||||
var known int
|
||||
if e = tx.QueryRowContext(ctx, d.q(`SELECT COUNT(*) FROM worlds WHERE id=?`), h.DeathWorld).Scan(&known); e != nil {
|
||||
return e
|
||||
}
|
||||
if known != 1 {
|
||||
return houseError("recovery world unavailable")
|
||||
}
|
||||
if e = d.issueKey(ctx, tx, h, c, rules.MaxItems); e != nil {
|
||||
return e
|
||||
}
|
||||
h.View.State = "active"
|
||||
return d.writeHouse(ctx, tx, h)
|
||||
}
|
||||
if h.View.State != "active" {
|
||||
return houseError("house is unavailable")
|
||||
}
|
||||
role, e := d.houseRole(ctx, tx, h, c)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if role == "" {
|
||||
return houseError("a carried key or invitation is required")
|
||||
}
|
||||
if r.Op == "enter" {
|
||||
if c.WorldsSurvived < 1 {
|
||||
return houseError("survive a world before entering housing")
|
||||
}
|
||||
if game.HouseID(c) != "" {
|
||||
return houseError("leave the current house first")
|
||||
}
|
||||
id := h.View.ID
|
||||
c.View.HouseID = &id
|
||||
c.View.DestroyKey = nil
|
||||
c.View.Casting = nil
|
||||
return nil
|
||||
}
|
||||
if game.HouseID(c) != h.View.ID {
|
||||
return houseError("enter this house first")
|
||||
}
|
||||
if r.Revision > 0 && r.Revision != h.View.Revision {
|
||||
return houseError("house changed; refresh before editing")
|
||||
}
|
||||
allowed := housePermissions(h, c, role)
|
||||
manager := role == "owner" || role == "co-owner"
|
||||
switch r.Op {
|
||||
case "issue-key":
|
||||
if role != "owner" {
|
||||
return houseError("only key holders issue keys")
|
||||
}
|
||||
if e = d.issueKey(ctx, tx, h, c, rules.MaxItems); e != nil {
|
||||
return e
|
||||
}
|
||||
case "invite":
|
||||
if !manager || (!slices.Contains([]string{"guest", "co-owner", "remove"}, r.Role)) || (role != "owner" && (r.Role == "co-owner" || h.View.Roles[r.Target] == "co-owner")) {
|
||||
return houseError("invitation role not allowed")
|
||||
}
|
||||
if r.Target == c.View.Entity.ID {
|
||||
return houseError("cannot change your own invitation")
|
||||
}
|
||||
if r.Role == "remove" {
|
||||
delete(h.View.Roles, r.Target)
|
||||
delete(h.View.Overrides, r.Target)
|
||||
if _, e = tx.ExecContext(ctx, d.q(`DELETE FROM house_invites WHERE house_id=? AND character_id=?`), h.View.ID, r.Target); e != nil {
|
||||
return e
|
||||
}
|
||||
} else {
|
||||
var n int
|
||||
if e = tx.QueryRowContext(ctx, d.q(`SELECT COUNT(*) FROM character_records WHERE character_id=? AND state IN ('alive','eligible')`), r.Target).Scan(&n); e != nil {
|
||||
return e
|
||||
}
|
||||
if n != 1 {
|
||||
return houseError("living guest not found")
|
||||
}
|
||||
if h.View.Roles[r.Target] == "" && len(h.View.Roles) >= rules.MaxGuests {
|
||||
return houseError("guest limit")
|
||||
}
|
||||
h.View.Roles[r.Target] = r.Role
|
||||
if _, e = tx.ExecContext(ctx, d.q(`INSERT INTO house_invites(house_id,character_id) VALUES(?,?) ON CONFLICT(house_id,character_id) DO NOTHING`), h.View.ID, r.Target); e != nil {
|
||||
return e
|
||||
}
|
||||
}
|
||||
case "permissions":
|
||||
if !manager {
|
||||
return houseError("only owners and co-owners manage guest permissions")
|
||||
}
|
||||
for key := range r.Permissions {
|
||||
if !slices.Contains(game.HousePermissions, key) {
|
||||
return houseError("unknown guest permission")
|
||||
}
|
||||
}
|
||||
if r.Target == "" {
|
||||
for k, v := range r.Permissions {
|
||||
h.View.Permissions[k] = v
|
||||
}
|
||||
} else {
|
||||
if h.View.Roles[r.Target] == "" {
|
||||
return houseError("invite this person first")
|
||||
}
|
||||
h.View.Overrides[r.Target] = r.Permissions
|
||||
}
|
||||
default:
|
||||
if e = houseItemAction(w, c, h, r, allowed); e != nil {
|
||||
return e
|
||||
}
|
||||
}
|
||||
return d.writeHouse(ctx, tx, h)
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"aeternalis/server/content"
|
||||
"aeternalis/server/internal/game"
|
||||
p "aeternalis/server/internal/protocol"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestHousingLifecycle(t *testing.T) {
|
||||
testHousingLifecycle(t, "file:"+filepath.ToSlash(filepath.Join(t.TempDir(), "housing.db")))
|
||||
}
|
||||
func TestPostgresHousingLifecycle(t *testing.T) {
|
||||
dsn := os.Getenv("TEST_DATABASE_URL")
|
||||
if dsn == "" {
|
||||
t.Skip("TEST_DATABASE_URL not configured")
|
||||
}
|
||||
testHousingLifecycle(t, dsn)
|
||||
}
|
||||
func testHousingLifecycle(t *testing.T, dsn string) {
|
||||
ctx := context.Background()
|
||||
db, e := Open(ctx, dsn)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
defer db.Close()
|
||||
b, _ := content.Load()
|
||||
now := time.Now().UTC()
|
||||
w := game.New("housing-"+game.ID(), 1, now, b)
|
||||
l, _, e := db.Acquire(ctx, w)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
join := func(name string) *game.Character {
|
||||
c, e := w.Join(name+game.ID(), name)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e = w.Connect(c.View.Entity.ID); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
return c
|
||||
}
|
||||
owner, guest, coowner := join("Owner"), join("Guest"), join("Co-owner")
|
||||
// Seed arrivals before making this fixture a hub; travel itself has separate coverage.
|
||||
w.Kind = "hub"
|
||||
w.Phase = "hub"
|
||||
save := func() {
|
||||
t.Helper()
|
||||
if e := l.Save(ctx, w, ""); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
}
|
||||
save()
|
||||
act := func(c *game.Character, r HouseRequest) {
|
||||
t.Helper()
|
||||
if r.RequestID == "" {
|
||||
r.RequestID = game.ID()
|
||||
}
|
||||
if e := l.HouseAction(ctx, w, c.Account, r); e != nil {
|
||||
t.Fatal(r.Op, e)
|
||||
}
|
||||
}
|
||||
reject := func(c *game.Character, r HouseRequest) {
|
||||
t.Helper()
|
||||
r.RequestID = game.ID()
|
||||
before, _ := json.Marshal(w)
|
||||
e := l.HouseAction(ctx, w, c.Account, r)
|
||||
if !errors.Is(e, ErrHousing) {
|
||||
t.Fatal("expected housing rejection", r.Op, e)
|
||||
}
|
||||
after, _ := json.Marshal(w)
|
||||
if string(before) != string(after) {
|
||||
t.Fatal("rejected action mutated world", r.Op)
|
||||
}
|
||||
}
|
||||
view := func(c *game.Character) p.HouseState {
|
||||
t.Helper()
|
||||
s, e := db.HouseState(ctx, w, c.Account)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
return s
|
||||
}
|
||||
tick := func(seconds float64) {
|
||||
now = now.Add(time.Duration(seconds * float64(time.Second)))
|
||||
w.Advance(now, seconds)
|
||||
save()
|
||||
}
|
||||
reject(owner, HouseRequest{Op: "create", Name: "Home"})
|
||||
owner.WorldsSurvived = 1
|
||||
guest.WorldsSurvived = 1
|
||||
coowner.WorldsSurvived = 1
|
||||
save()
|
||||
create := HouseRequest{RequestID: game.ID(), Op: "create", Name: "Home"}
|
||||
act(owner, create)
|
||||
act(owner, create)
|
||||
s := view(owner)
|
||||
if len(s.Houses) != 1 || s.Houses[0].Keys != 1 {
|
||||
t.Fatal("create replay duplicated house or key", s)
|
||||
}
|
||||
house := s.Houses[0].ID
|
||||
key := owner.View.Items[len(owner.View.Items)-1].ID
|
||||
reject(owner, HouseRequest{Op: "create", Name: "Duplicate"})
|
||||
reject(guest, HouseRequest{Op: "enter", HouseID: house})
|
||||
act(owner, HouseRequest{Op: "enter", HouseID: house})
|
||||
if e := w.Intent(owner.View.Entity.ID, p.Intent{Seq: 1, Op: "jump"}); e == nil {
|
||||
t.Fatal("world action inside house")
|
||||
}
|
||||
if _, e := w.AttemptCraft(owner, p.CraftRequest{Profession: "carver", Ingredients: map[string]int64{"wood": 1}}); e == nil {
|
||||
t.Fatal("house craft accepted")
|
||||
}
|
||||
stale := *l
|
||||
stale.Revision--
|
||||
if e := stale.HouseAction(ctx, w, owner.Account, HouseRequest{RequestID: game.ID(), Op: "issue-key", HouseID: house}); !errors.Is(e, ErrOwnership) {
|
||||
t.Fatal("stale owner mutation", e)
|
||||
}
|
||||
if view(owner).Houses[0].Keys != 1 {
|
||||
t.Fatal("stale lease issued key")
|
||||
}
|
||||
act(owner, HouseRequest{Op: "invite", HouseID: house, Target: guest.View.Entity.ID, Role: "guest"})
|
||||
act(owner, HouseRequest{Op: "invite", HouseID: house, Target: coowner.View.Entity.ID, Role: "co-owner"})
|
||||
act(guest, HouseRequest{Op: "enter", HouseID: house})
|
||||
act(coowner, HouseRequest{Op: "enter", HouseID: house})
|
||||
reject(guest, HouseRequest{Op: "permissions", HouseID: house, Permissions: map[string]bool{"pickupItems": true}})
|
||||
reject(coowner, HouseRequest{Op: "issue-key", HouseID: house})
|
||||
act(coowner, HouseRequest{Op: "permissions", HouseID: house, Permissions: map[string]bool{"moveFurniture": true, "openFurniture": true, "depositItems": true}})
|
||||
act(coowner, HouseRequest{Op: "permissions", HouseID: house, Target: guest.View.Entity.ID, Permissions: map[string]bool{"moveFurniture": false}})
|
||||
if v := view(guest); v.Effective["moveFurniture"] || !v.Effective["depositItems"] {
|
||||
t.Fatal("baseline/override not enforced")
|
||||
}
|
||||
if e = w.AdminItems(owner, "grant-item", "storage_chest:1"); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
chest := owner.View.Items[len(owner.View.Items)-1].ID
|
||||
owner.View.Inventory["wood"] = 20
|
||||
save()
|
||||
act(owner, HouseRequest{Op: "place", HouseID: house, Item: chest, X: 0, Z: 0})
|
||||
reject(owner, HouseRequest{Op: "move", HouseID: house, Target: chest, X: 100, Z: 0})
|
||||
reject(guest, HouseRequest{Op: "move", HouseID: house, Target: chest, X: 3, Z: 0})
|
||||
act(owner, HouseRequest{Op: "deposit", HouseID: house, Target: chest, Item: "wood", Quantity: 10})
|
||||
reject(guest, HouseRequest{Op: "withdraw", HouseID: house, Target: chest, Item: "wood", Quantity: 1})
|
||||
reject(owner, HouseRequest{Op: "pickup-furniture", HouseID: house, Target: chest})
|
||||
reject(owner, HouseRequest{Op: "deposit", HouseID: house, Target: chest, Item: key, Quantity: 1})
|
||||
act(coowner, HouseRequest{Op: "permissions", HouseID: house, Target: guest.View.Entity.ID, Permissions: map[string]bool{"pickupItems": true, "openFurniture": false}})
|
||||
if len(view(guest).Room.Furniture[chest].Contents.Inventory) != 0 {
|
||||
t.Fatal("closed container contents leaked")
|
||||
}
|
||||
reject(guest, HouseRequest{Op: "withdraw", HouseID: house, Target: chest, Item: "wood", Quantity: 1})
|
||||
act(coowner, HouseRequest{Op: "permissions", HouseID: house, Target: guest.View.Entity.ID, Permissions: map[string]bool{"pickupItems": true}})
|
||||
act(guest, HouseRequest{Op: "withdraw", HouseID: house, Target: chest, Item: "wood", Quantity: 2})
|
||||
if view(owner).Room.Furniture[chest].Contents.Inventory["wood"] != 8 || guest.View.Inventory["wood"] != 2 {
|
||||
t.Fatal("stored inventory transfer")
|
||||
}
|
||||
// Furniture movement preserves exact instance and contents.
|
||||
act(guest, HouseRequest{Op: "move", HouseID: house, Target: chest, X: 3, Z: 0})
|
||||
if f := view(owner).Room.Furniture[chest]; f.Item.ID != chest || f.Contents.Inventory["wood"] != 8 {
|
||||
t.Fatal("move lost furniture or contents")
|
||||
}
|
||||
act(owner, HouseRequest{Op: "issue-key", HouseID: house})
|
||||
if view(owner).Houses[0].Keys != 2 {
|
||||
t.Fatal("extra key missing")
|
||||
}
|
||||
act(owner, HouseRequest{Op: "destroy-key", Item: key})
|
||||
tick(2.9)
|
||||
if view(owner).Houses[0].Keys != 2 || owner.View.DestroyKey == nil {
|
||||
t.Fatal("key destroyed early")
|
||||
}
|
||||
tick(.11)
|
||||
if view(owner).Houses[0].Keys != 1 || view(owner).Houses[0].State != "active" {
|
||||
t.Fatal("non-last key archived house")
|
||||
}
|
||||
key = owner.View.Items[len(owner.View.Items)-1].ID
|
||||
act(owner, HouseRequest{Op: "leave"})
|
||||
act(owner, HouseRequest{Op: "destroy-key", Item: key})
|
||||
w.Disconnect(owner.View.Entity.ID)
|
||||
save()
|
||||
tick(4)
|
||||
if view(owner).Houses[0].Keys != 1 || owner.View.DestroyKey != nil {
|
||||
t.Fatal("disconnect failed to cancel key action")
|
||||
}
|
||||
_ = w.Connect(owner.View.Entity.ID)
|
||||
act(owner, HouseRequest{Op: "destroy-key", Item: key})
|
||||
if e = w.Intent(owner.View.Entity.ID, p.Intent{Seq: 2, Op: "drop", Target: key}); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if owner.View.DestroyKey != nil {
|
||||
t.Fatal("drop failed to cancel")
|
||||
}
|
||||
save()
|
||||
var pile string
|
||||
for id, c := range w.Corpses {
|
||||
for _, i := range c.Items {
|
||||
if i.ID == key {
|
||||
pile = id
|
||||
}
|
||||
}
|
||||
}
|
||||
if pile == "" {
|
||||
t.Fatal("key not dropped")
|
||||
}
|
||||
act(guest, HouseRequest{Op: "leave"})
|
||||
guest.View.Entity.Position = owner.View.Entity.Position
|
||||
if e = w.Intent(guest.View.Entity.ID, p.Intent{Seq: 1, Op: "loot", Target: pile}); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
save()
|
||||
act(guest, HouseRequest{Op: "enter", HouseID: house})
|
||||
if view(guest).Role != "owner" {
|
||||
t.Fatal("looted key did not grant ownership")
|
||||
}
|
||||
act(coowner, HouseRequest{Op: "invite", HouseID: house, Target: guest.View.Entity.ID, Role: "remove"})
|
||||
if view(guest).Role != "owner" {
|
||||
t.Fatal("invitation removal stripped key owner")
|
||||
}
|
||||
// Last-key destruction archives contents immediately on completion; no invented purge deadline.
|
||||
act(guest, HouseRequest{Op: "destroy-key", Item: key})
|
||||
tick(3.01)
|
||||
if v := view(owner); v.Houses[0].State != "archived" || v.Houses[0].Keys != 0 {
|
||||
t.Fatal("last-key archive", v)
|
||||
}
|
||||
tx, _ := db.sql.BeginTx(ctx, nil)
|
||||
stored, e := db.readHouse(ctx, tx, house, false)
|
||||
tx.Rollback()
|
||||
if e != nil || stored.View.Furniture[chest].Contents.Inventory["wood"] != 8 {
|
||||
t.Fatal("archive lost recoverable contents", e)
|
||||
}
|
||||
reject(owner, HouseRequest{Op: "recover", HouseID: house})
|
||||
reject(coowner, HouseRequest{Op: "enter", HouseID: house})
|
||||
// Creator death establishes the recovery world. World loss finally purges archived data.
|
||||
owner.View.Entity.HP = 0
|
||||
tick(.1)
|
||||
if owner.DiedAt == nil {
|
||||
t.Fatal("creator death absent")
|
||||
}
|
||||
tx, _ = db.sql.BeginTx(ctx, nil)
|
||||
stored, e = db.readHouse(ctx, tx, house, false)
|
||||
tx.Rollback()
|
||||
if e != nil || stored.DeathWorld != w.ID {
|
||||
t.Fatal("recovery world not captured", e)
|
||||
}
|
||||
w.Phase = "lost"
|
||||
save()
|
||||
tx, _ = db.sql.BeginTx(ctx, nil)
|
||||
stored, e = db.readHouse(ctx, tx, house, false)
|
||||
tx.Rollback()
|
||||
if e != nil || stored.View.State != "purged" || len(stored.View.Furniture) != 0 {
|
||||
t.Fatal("world loss did not purge archived house", e)
|
||||
}
|
||||
}
|
||||
@@ -65,6 +65,12 @@ func (d *DB) migrate(ctx context.Context) error {
|
||||
}
|
||||
}
|
||||
for _, stmt := range []string{
|
||||
`CREATE TABLE IF NOT EXISTS houses(id TEXT PRIMARY KEY,creator_account TEXT NOT NULL,creator_character TEXT NOT NULL,death_world TEXT NOT NULL,death_id TEXT NOT NULL,death_at BIGINT NOT NULL DEFAULT 0,state TEXT NOT NULL,document TEXT NOT NULL)`,
|
||||
`CREATE UNIQUE INDEX IF NOT EXISTS one_created_house ON houses(creator_account) WHERE state<>'purged'`,
|
||||
`CREATE TABLE IF NOT EXISTS house_keys(id TEXT PRIMARY KEY,house_id TEXT NOT NULL,state TEXT NOT NULL)`,
|
||||
`CREATE INDEX IF NOT EXISTS keys_house ON house_keys(house_id,state)`,
|
||||
`CREATE TABLE IF NOT EXISTS house_invites(house_id TEXT NOT NULL,character_id TEXT NOT NULL,PRIMARY KEY(house_id,character_id))`,
|
||||
`CREATE TABLE IF NOT EXISTS house_receipts(account_id TEXT NOT NULL,id TEXT NOT NULL,request TEXT NOT NULL,PRIMARY KEY(account_id,id))`,
|
||||
`CREATE TABLE IF NOT EXISTS account_lives(account_id TEXT PRIMARY KEY,character_id TEXT NOT NULL)`,
|
||||
`CREATE TABLE IF NOT EXISTS character_deaths(corpse_id TEXT PRIMARY KEY,character_id TEXT NOT NULL,world_id TEXT NOT NULL,character TEXT NOT NULL,revived INTEGER NOT NULL)`,
|
||||
`CREATE TABLE IF NOT EXISTS craft_receipts(id TEXT NOT NULL,account_id TEXT NOT NULL,character_id TEXT NOT NULL,request_json TEXT NOT NULL,result_json TEXT NOT NULL,PRIMARY KEY(account_id,id))`,
|
||||
|
||||
@@ -124,7 +124,7 @@ func (l *Lease) RevivalConsent(ctx context.Context, w *game.World, account, id s
|
||||
}
|
||||
func (l *Lease) Revive(ctx context.Context, w *game.World, account, corpse, power string) error {
|
||||
caster := w.ForAccount(account)
|
||||
if caster == nil {
|
||||
if caster == nil || game.HouseID(caster) != "" {
|
||||
return ErrRevival
|
||||
}
|
||||
active, e := l.DB.ActiveCharacter(ctx, account)
|
||||
@@ -141,7 +141,7 @@ func (l *Lease) Revive(ctx context.Context, w *game.World, account, corpse, powe
|
||||
return fmt.Errorf("%w: %v", ErrRevival, e)
|
||||
}
|
||||
claim := &reviveClaim{target.Account, target.View.Entity.ID, corpse, w.ID}
|
||||
if e = l.save(ctx, staged, "", nil, "", nil, claim); e != nil {
|
||||
if e = l.save(ctx, staged, "", nil, "", nil, claim, nil); e != nil {
|
||||
return e
|
||||
}
|
||||
for id, c := range staged.Characters {
|
||||
|
||||
@@ -139,9 +139,9 @@ func (l *Lease) Save(ctx context.Context, w *game.World, claimID string) error {
|
||||
return l.SaveCommand(ctx, w, claimID, nil, "")
|
||||
}
|
||||
func (l *Lease) SaveCommand(ctx context.Context, w *game.World, claimID string, command *Command, outcome string) error {
|
||||
return l.save(ctx, w, claimID, command, outcome, nil, nil)
|
||||
return l.save(ctx, w, claimID, command, outcome, nil, nil, nil)
|
||||
}
|
||||
func (l *Lease) save(ctx context.Context, w *game.World, claimID string, command *Command, outcome string, receipt *craftReceipt, revival *reviveClaim) error {
|
||||
func (l *Lease) save(ctx context.Context, w *game.World, claimID string, command *Command, outcome string, receipt *craftReceipt, revival *reviveClaim, housing *houseMutation) error {
|
||||
live := w
|
||||
w = stageTitleWorld(w)
|
||||
data, err := json.Marshal(w)
|
||||
@@ -198,6 +198,14 @@ func (l *Lease) save(ctx context.Context, w *game.World, claimID string, command
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err = d.syncHousing(ctx, tx, w); err != nil {
|
||||
return err
|
||||
}
|
||||
if housing != nil {
|
||||
if err = d.applyHouse(ctx, tx, w, housing); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err = d.syncTitles(ctx, tx, w); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -26,6 +26,7 @@ func stageTitleWorld(w *game.World) *game.World {
|
||||
copy.View.Powers = maps.Clone(c.View.Powers)
|
||||
copy.View.Weapons = maps.Clone(c.View.Weapons)
|
||||
copy.View.Inventory = maps.Clone(c.View.Inventory)
|
||||
copy.View.StackNames = maps.Clone(c.View.StackNames)
|
||||
copy.View.Equipment = maps.Clone(c.View.Equipment)
|
||||
copy.View.AllocatedStats = maps.Clone(c.View.AllocatedStats)
|
||||
copy.View.Stats = maps.Clone(c.View.Stats)
|
||||
|
||||
@@ -107,6 +107,8 @@ func (l *Lease) PrepareTravel(ctx context.Context, live *game.World, account, re
|
||||
return nil, err
|
||||
}
|
||||
departing.PendingCast = nil
|
||||
departing.View.DestroyKey = nil
|
||||
game.LeaveHouse(&departing)
|
||||
departing.View.Casting = nil
|
||||
if route == "escape" {
|
||||
game.TakeStack(&departing, "escape_stone", 1)
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
package transport
|
||||
|
||||
import (
|
||||
"aeternalis/server/internal/store"
|
||||
"errors"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
func (h *HTTP) housingRoutes(mux *http.ServeMux) {
|
||||
mux.HandleFunc("GET /api/housing", func(w http.ResponseWriter, r *http.Request) {
|
||||
account, e := h.auth.account(r)
|
||||
if e != nil {
|
||||
fail(w, 401, "sign in required")
|
||||
return
|
||||
}
|
||||
h.s.mu.Lock()
|
||||
defer h.s.mu.Unlock()
|
||||
if !h.s.ready.Load() {
|
||||
fail(w, 503, "world unavailable")
|
||||
return
|
||||
}
|
||||
state, e := h.auth.db.HouseState(r.Context(), h.s.world, account)
|
||||
if e != nil {
|
||||
h.housingFailure(w, e)
|
||||
return
|
||||
}
|
||||
respond(w, 200, state)
|
||||
})
|
||||
mux.HandleFunc("POST /api/housing", func(w http.ResponseWriter, r *http.Request) {
|
||||
account, e := h.auth.account(r)
|
||||
if e != nil {
|
||||
fail(w, 401, "sign in required")
|
||||
return
|
||||
}
|
||||
var req store.HouseRequest
|
||||
if decode(w, r, &req) != nil {
|
||||
fail(w, 400, "invalid housing request")
|
||||
return
|
||||
}
|
||||
h.s.mu.Lock()
|
||||
defer h.s.mu.Unlock()
|
||||
if !h.s.ready.Load() {
|
||||
fail(w, 503, "world unavailable")
|
||||
return
|
||||
}
|
||||
if e = h.s.persist(r.Context(), ""); e != nil {
|
||||
fail(w, 503, "save unavailable")
|
||||
return
|
||||
}
|
||||
if e = h.s.lease.HouseAction(r.Context(), h.s.world, account, req); e != nil {
|
||||
h.housingFailure(w, e)
|
||||
return
|
||||
}
|
||||
respond(w, 200, map[string]bool{"saved": true})
|
||||
})
|
||||
}
|
||||
func (h *HTTP) housingFailure(w http.ResponseWriter, e error) {
|
||||
if errors.Is(e, store.ErrHousing) || errors.Is(e, store.ErrLivingCharacter) {
|
||||
fail(w, 409, e.Error())
|
||||
return
|
||||
}
|
||||
h.s.ready.Store(false)
|
||||
for _, p := range h.s.peers {
|
||||
p.close()
|
||||
}
|
||||
fail(w, 503, "housing save unavailable; reconnect to check the result")
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package transport
|
||||
|
||||
import (
|
||||
"aeternalis/server/content"
|
||||
"aeternalis/server/internal/game"
|
||||
"aeternalis/server/internal/store"
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestHousingHTTPAuthorization(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
db, e := store.Open(ctx, "file:"+filepath.ToSlash(filepath.Join(t.TempDir(), "house.db")))
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
defer db.Close()
|
||||
b, _ := content.Load()
|
||||
w := game.New("house-auth", 1, time.Now(), b)
|
||||
c, _ := w.Join("owner", "Owner")
|
||||
c.WorldsSurvived = 1
|
||||
_ = w.Connect(c.View.Entity.ID)
|
||||
w.Kind = "hub"
|
||||
w.Phase = "hub"
|
||||
l, _, e := db.Acquire(ctx, w)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e = l.Save(ctx, w, ""); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
auth, _ := NewAuth(ctx, db, true, "http://127.0.0.1", "", "", "")
|
||||
out := httptest.NewRecorder()
|
||||
if e = auth.session(out, httptest.NewRequest("POST", auth.base+"/auth/dev", nil), "owner"); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
cookie := out.Result().Cookies()[0]
|
||||
s := NewService(w, l)
|
||||
h := NewHTTP(s, auth, t.TempDir(), nil).Handler()
|
||||
request := func(method, origin, body string, cookie *http.Cookie) int {
|
||||
r := httptest.NewRequest(method, auth.base+"/api/housing", strings.NewReader(body))
|
||||
r.RemoteAddr = "127.0.0.1:1234"
|
||||
if origin != "" {
|
||||
r.Header.Set("Origin", origin)
|
||||
}
|
||||
if cookie != nil {
|
||||
r.AddCookie(cookie)
|
||||
}
|
||||
out := httptest.NewRecorder()
|
||||
h.ServeHTTP(out, r)
|
||||
return out.Code
|
||||
}
|
||||
body := `{"requestId":"` + game.ID() + `","op":"create","name":"Home"}`
|
||||
if code := request("GET", "", "", nil); code != 401 {
|
||||
t.Fatal("anonymous directory", code)
|
||||
}
|
||||
if code := request("POST", auth.base, body, nil); code != 401 {
|
||||
t.Fatal("anonymous mutation", code)
|
||||
}
|
||||
if code := request("POST", "https://evil.example", body, cookie); code != 403 {
|
||||
t.Fatal("cross-origin mutation", code)
|
||||
}
|
||||
if code := request("POST", auth.base, body, cookie); code != 200 {
|
||||
t.Fatal("authorized create", code)
|
||||
}
|
||||
if code := request("GET", "", "", cookie); code != 200 {
|
||||
t.Fatal("authorized directory", code)
|
||||
}
|
||||
if code := request("POST", auth.base, `{"requestId":"`+game.ID()+`","op":"create","account":"other"}`, cookie); code != 400 {
|
||||
t.Fatal("actor spoofing", code)
|
||||
}
|
||||
if !s.ready.Load() {
|
||||
t.Fatal("ordinary rejection froze world")
|
||||
}
|
||||
}
|
||||
@@ -100,6 +100,7 @@ func (h *HTTP) Handler() http.Handler {
|
||||
h.travelRoutes(mux)
|
||||
h.craftingRoutes(mux)
|
||||
h.powerRoutes(mux)
|
||||
h.housingRoutes(mux)
|
||||
h.catalogRoutes(mux)
|
||||
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) {
|
||||
if !h.s.ready.Load() {
|
||||
|
||||
Reference in New Issue
Block a user