Add character levels and permanent player titles
This commit is contained in:
@@ -0,0 +1,162 @@
|
||||
package game
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
p "aeternalis/server/internal/protocol"
|
||||
)
|
||||
|
||||
// Candidates are produced in simulation event order. Only a successful store
|
||||
// transaction may turn them into permanent awards and enable their effects.
|
||||
type TitleCandidate struct {
|
||||
CharacterID string
|
||||
Award p.TitleAward
|
||||
}
|
||||
|
||||
func (w *World) orderedCharacters() []*Character {
|
||||
ids := make([]string, 0, len(w.Characters))
|
||||
for id := range w.Characters {
|
||||
ids = append(ids, id)
|
||||
}
|
||||
sort.Strings(ids)
|
||||
characters := make([]*Character, 0, len(ids))
|
||||
for _, id := range ids {
|
||||
characters = append(characters, w.Characters[id])
|
||||
}
|
||||
return characters
|
||||
}
|
||||
|
||||
func (w *World) restoreProgression(c *Character) error {
|
||||
if c.Progression == nil {
|
||||
rules := *w.Balance.Progression
|
||||
c.Progression = &rules
|
||||
}
|
||||
if err := c.Progression.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
if c.View.Level == 0 {
|
||||
c.View.Level = 1
|
||||
}
|
||||
if c.View.Level < 1 || c.View.Level > c.Progression.MaxLevel || c.View.Experience < 0 || c.View.StatPoints < 0 {
|
||||
return errors.New("invalid persisted character progression")
|
||||
}
|
||||
c.View.ExperienceToNextLevel = c.nextLevelXP()
|
||||
if (c.View.ExperienceToNextLevel == 0 && c.View.Experience != 0) || (c.View.ExperienceToNextLevel > 0 && c.View.Experience >= c.View.ExperienceToNextLevel) {
|
||||
return errors.New("invalid persisted level XP")
|
||||
}
|
||||
if c.View.Titles == nil {
|
||||
c.View.Titles = []p.TitleAward{}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Character) nextLevelXP() int64 {
|
||||
if c.View.Level >= c.Progression.MaxLevel {
|
||||
return 0
|
||||
}
|
||||
return c.Progression.BaseXP + (c.View.Level-1)*c.Progression.XPPerLevel
|
||||
}
|
||||
|
||||
func (w *World) grantXP(c *Character, amount int64) {
|
||||
if amount <= 0 || c.View.Entity.State != "alive" || c.View.Level >= c.Progression.MaxLevel {
|
||||
return
|
||||
}
|
||||
c.View.Experience += amount
|
||||
before := c.View.Level
|
||||
for c.View.Level < c.Progression.MaxLevel && c.View.Experience >= c.nextLevelXP() {
|
||||
c.View.Experience -= c.nextLevelXP()
|
||||
c.View.Level++
|
||||
c.View.StatPoints += c.Progression.StatPointsPerLevel
|
||||
}
|
||||
c.View.ExperienceToNextLevel = c.nextLevelXP()
|
||||
if c.View.ExperienceToNextLevel == 0 {
|
||||
c.View.Experience = 0
|
||||
}
|
||||
if c.View.Level > before {
|
||||
c.Message = fmt.Sprintf("Level %d reached. %d stat points banked.", c.View.Level, c.View.StatPoints)
|
||||
}
|
||||
w.dirty = true
|
||||
}
|
||||
|
||||
func (w *World) evaluateTitles(c *Character) {
|
||||
metric := func(name string) int64 {
|
||||
switch name {
|
||||
case "level":
|
||||
return c.View.Level
|
||||
case "kills":
|
||||
return c.View.Kills
|
||||
case "worldKills":
|
||||
return c.WorldKills
|
||||
case "bossKills":
|
||||
return c.BossKills
|
||||
case "worldsSurvived":
|
||||
return c.WorldsSurvived
|
||||
case "deaths":
|
||||
if c.View.Entity.State == "dead" {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
default:
|
||||
return c.View.Skills[name]
|
||||
}
|
||||
}
|
||||
for _, title := range w.Balance.Titles {
|
||||
owned := false
|
||||
for _, award := range c.View.Titles {
|
||||
if award.ID == title.ID {
|
||||
owned = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if owned {
|
||||
continue
|
||||
}
|
||||
for _, pending := range w.PendingTitles {
|
||||
if pending.CharacterID == c.View.Entity.ID && pending.Award.ID == title.ID {
|
||||
owned = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if owned {
|
||||
continue
|
||||
}
|
||||
eligible := true
|
||||
for _, requirement := range title.Requirements {
|
||||
if metric(requirement.Metric) < requirement.AtLeast {
|
||||
eligible = false
|
||||
break
|
||||
}
|
||||
}
|
||||
if !eligible {
|
||||
continue
|
||||
}
|
||||
w.PendingTitles = append(w.PendingTitles, TitleCandidate{CharacterID: c.View.Entity.ID, Award: p.TitleAward{
|
||||
ID: title.ID, Name: title.Name, Description: title.Description, Scope: title.Scope, WorldID: w.ID,
|
||||
EarnedAt: w.now.UTC().Format(time.RFC3339Nano), Effects: p.TitleEffects{Damage: title.Effects.Damage, MoveSpeed: title.Effects.MoveSpeed},
|
||||
}})
|
||||
w.dirty = true
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Character) titleEffects() p.TitleEffects {
|
||||
var effects p.TitleEffects
|
||||
// One effect per permanent title ID, even if legacy data contains duplicates.
|
||||
seen := map[string]bool{}
|
||||
for _, title := range c.View.Titles {
|
||||
if seen[title.ID] {
|
||||
continue
|
||||
}
|
||||
seen[title.ID] = true
|
||||
effects.Damage += title.Effects.Damage
|
||||
effects.MoveSpeed += title.Effects.MoveSpeed
|
||||
}
|
||||
return effects
|
||||
}
|
||||
|
||||
func (w *World) playerSpeed(c *Character) float64 {
|
||||
return math.Max(0, w.Balance.PlayerSpeed+c.titleEffects().MoveSpeed)
|
||||
}
|
||||
@@ -0,0 +1,286 @@
|
||||
package game
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"math"
|
||||
"reflect"
|
||||
"sort"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"aeternalis/server/content"
|
||||
p "aeternalis/server/internal/protocol"
|
||||
)
|
||||
|
||||
func TestLevelUpsBankPointsAndCap(t *testing.T) {
|
||||
w, c := fixture(t)
|
||||
if c.View.Level != 1 || c.View.StatPoints != 0 || c.View.ExperienceToNextLevel != 100 {
|
||||
t.Fatal("incorrect new life progression")
|
||||
}
|
||||
w.grantXP(c, 99)
|
||||
if c.View.Level != 1 || c.View.Experience != 99 {
|
||||
t.Fatal("premature level")
|
||||
}
|
||||
w.grantXP(c, 151)
|
||||
if c.View.Level != 3 || c.View.Experience != 0 || c.View.StatPoints != 10 || c.View.ExperienceToNextLevel != 200 {
|
||||
t.Fatalf("multi-level award lost points or XP: %+v", c.View)
|
||||
}
|
||||
c.Progression.MaxLevel = 4
|
||||
w.grantXP(c, 1000000)
|
||||
if c.View.Level != 4 || c.View.StatPoints != 15 || c.View.Experience != 0 || c.View.ExperienceToNextLevel != 0 {
|
||||
t.Fatal("level cap failed")
|
||||
}
|
||||
w.grantXP(c, 1000000)
|
||||
if c.View.StatPoints != 15 {
|
||||
t.Fatal("cap farming granted extra points")
|
||||
}
|
||||
}
|
||||
|
||||
func TestOnlySuccessfulActionsGrantXP(t *testing.T) {
|
||||
w, c := fixture(t)
|
||||
id := c.View.Entity.ID
|
||||
w.now = w.now.Add(2 * time.Second)
|
||||
for seq, op := range []string{"grant-xp", "level-up", "spend-stat", "grant-title", "remove-title", "gather", "craft", "attack"} {
|
||||
if w.Intent(id, p.Intent{Op: op, Seq: int64(seq + 1), Target: "invalid"}) == nil {
|
||||
t.Fatalf("invalid %s accepted", op)
|
||||
}
|
||||
}
|
||||
if c.View.Experience != 0 || c.View.StatPoints != 0 || len(w.PendingTitles) != 0 {
|
||||
t.Fatal("failed intent awarded progression")
|
||||
}
|
||||
c.View.Entity.Position = w.terrain.Position(17, 12)
|
||||
if err := w.Intent(id, p.Intent{Op: "gather", Seq: 9, Target: "arrival:ore"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if c.View.Experience != w.Balance.Progression.GatherXP {
|
||||
t.Fatal("missing gather XP")
|
||||
}
|
||||
if w.Intent(id, p.Intent{Op: "gather", Seq: 10, Target: "arrival:ore"}) == nil {
|
||||
t.Fatal("duplicate gather")
|
||||
}
|
||||
if c.View.Experience != w.Balance.Progression.GatherXP {
|
||||
t.Fatal("failed gather gained XP")
|
||||
}
|
||||
c.View.Inventory["herb"] = 2
|
||||
if err := w.Intent(id, p.Intent{Op: "craft", Seq: 11, Target: "bandage"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
before := c.View.Experience
|
||||
if before != w.Balance.Progression.GatherXP+w.Balance.Progression.CraftXP {
|
||||
t.Fatal("missing craft XP")
|
||||
}
|
||||
w.Mobs["test"] = &Mob{Entity: p.Entity{ID: "test", HP: w.Balance.PlayerDamage + 1, Position: c.View.Entity.Position}}
|
||||
if err := w.Intent(id, p.Intent{Op: "attack", Seq: 12, Target: "test"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if c.View.Experience != before {
|
||||
t.Fatal("nonlethal hit granted kill XP")
|
||||
}
|
||||
w.now = w.now.Add(time.Second)
|
||||
if err := w.Intent(id, p.Intent{Op: "attack", Seq: 13, Target: "test"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if c.View.Experience != before+w.Balance.Progression.MobKillXP || c.WorldKills != 1 {
|
||||
t.Fatal("missing kill XP")
|
||||
}
|
||||
w.now = w.now.Add(time.Second)
|
||||
if w.Intent(id, p.Intent{Op: "attack", Seq: 14, Target: "test"}) == nil {
|
||||
t.Fatal("dead mob killed twice")
|
||||
}
|
||||
if c.View.Kills != 1 || c.View.Experience != before+w.Balance.Progression.MobKillXP {
|
||||
t.Fatal("duplicate kill progression")
|
||||
}
|
||||
}
|
||||
|
||||
func TestProgressionSurvivesRestartDeathAndTransfer(t *testing.T) {
|
||||
w, c := fixture(t)
|
||||
w.grantXP(c, 275)
|
||||
c.View.Titles = []p.TitleAward{{ID: "bound", Name: "Bound", Scope: "personal", Effects: p.TitleEffects{Damage: 2}}}
|
||||
c.DailySeconds = 123
|
||||
c.WorldKills = 7
|
||||
raw, err := json.Marshal(w)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var restored World
|
||||
if err = json.Unmarshal(raw, &restored); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = restored.Restore(w.now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
loaded := restored.Characters[c.View.Entity.ID]
|
||||
if loaded.View.Level != 3 || loaded.View.Experience != 25 || loaded.View.StatPoints != 10 || !reflect.DeepEqual(loaded.View.Titles, c.View.Titles) {
|
||||
t.Fatal("restart reset progression")
|
||||
}
|
||||
loaded.View.Entity.State = "eligible"
|
||||
changed := w.Balance
|
||||
rules := *changed.Progression
|
||||
rules.BaseXP = 1
|
||||
rules.StatPointsPerLevel = 100
|
||||
changed.Progression = &rules
|
||||
destination := New("destination", 999, w.now, changed)
|
||||
if err = destination.Import(loaded); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if loaded.View.ExperienceToNextLevel != 200 || loaded.Progression.StatPointsPerLevel != 5 || loaded.DailySeconds != 123 || loaded.WorldKills != 0 || loaded.View.StatPoints != 10 || len(loaded.View.Titles) != 1 {
|
||||
t.Fatal("transfer altered progression, titles, or daily budget")
|
||||
}
|
||||
destination.kill(loaded, "test death")
|
||||
destination.grantXP(loaded, 1000)
|
||||
if loaded.View.StatPoints != 10 || loaded.View.Experience != 25 || len(loaded.View.Titles) != 1 {
|
||||
t.Fatal("death erased progression or allowed postmortem XP")
|
||||
}
|
||||
replacement, err := destination.Join(loaded.Account, "Replacement")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if replacement.View.Level != 1 || replacement.View.StatPoints != 0 || replacement.View.Entity.ID == loaded.View.Entity.ID {
|
||||
t.Fatal("replacement inherited character levels")
|
||||
}
|
||||
if destination.Connect(loaded.View.Entity.ID) == nil {
|
||||
t.Fatal("progression resurrected dead character")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLegacySnapshotProgressionMigrationIsIdempotent(t *testing.T) {
|
||||
w, c := fixture(t)
|
||||
w.Balance.Progression = nil
|
||||
w.Balance.Titles = nil
|
||||
c.Progression = nil
|
||||
c.View.Level = 0
|
||||
c.View.ExperienceToNextLevel = 0
|
||||
c.View.Titles = nil
|
||||
c.View.Kills = 42
|
||||
c.View.Skills["gathering"] = 99
|
||||
c.DailySeconds = 456
|
||||
c.View.Entity.State = "dead"
|
||||
if err := w.Restore(w.now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if c.View.Level != 1 || c.View.Experience != 0 || c.View.StatPoints != 0 || c.View.Titles == nil || c.DailySeconds != 456 || c.View.Entity.State != "dead" {
|
||||
t.Fatal("legacy migration changed life/budget or backfilled XP")
|
||||
}
|
||||
if err := w.Restore(w.now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if c.View.StatPoints != 0 || len(w.PendingTitles) != 0 {
|
||||
t.Fatal("migration minted grants")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTitleRequirementsAndPendingAwardsHaveNoEffects(t *testing.T) {
|
||||
w, c := fixture(t)
|
||||
w.Balance.Titles = []content.Title{{ID: "trial", Name: "Trial", Scope: "world", Requirements: []content.TitleRequirement{{Metric: "level", AtLeast: 2}, {Metric: "worldKills", AtLeast: 1}}, Effects: content.TitleEffects{Damage: 3, MoveSpeed: -2}}}
|
||||
w.grantXP(c, 100)
|
||||
w.evaluateTitles(c)
|
||||
if len(w.PendingTitles) != 0 {
|
||||
t.Fatal("requirements were not ANDed")
|
||||
}
|
||||
c.WorldKills = 1
|
||||
w.evaluateTitles(c)
|
||||
w.evaluateTitles(c)
|
||||
if len(w.PendingTitles) != 1 || len(c.View.Titles) != 0 || w.playerSpeed(c) != w.Balance.PlayerSpeed {
|
||||
t.Fatal("candidate duplicated or applied before durable award")
|
||||
}
|
||||
award := w.PendingTitles[0].Award
|
||||
if award.WorldID != w.ID || award.Scope != "world" || award.Effects.MoveSpeed != -2 || award.EarnedAt == "" {
|
||||
t.Fatal("candidate lost provenance or negative effect")
|
||||
}
|
||||
c.View.Titles = append(c.View.Titles, award)
|
||||
w.PendingTitles = nil
|
||||
w.Balance.Titles[0].Effects.MoveSpeed = 99
|
||||
c.WorldKills = 0
|
||||
w.evaluateTitles(c)
|
||||
if len(w.PendingTitles) != 0 || w.playerSpeed(c) != w.Balance.PlayerSpeed-2 {
|
||||
t.Fatal("lost requirement or edited catalog changed earned award")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSignedTitleEffectsAreServerAuthoritative(t *testing.T) {
|
||||
w, c := fixture(t)
|
||||
c.View.Titles = []p.TitleAward{{ID: "blessing", Effects: p.TitleEffects{Damage: 5, MoveSpeed: 2}}, {ID: "curse", Effects: p.TitleEffects{Damage: -2, MoveSpeed: -1}}}
|
||||
w.now = w.now.Add(2 * time.Second)
|
||||
if err := w.Intent(c.View.Entity.ID, p.Intent{Op: "move", Seq: 1, X: 1}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
before := c.View.Entity.Position
|
||||
w.Advance(w.now.Add(50*time.Millisecond), .05)
|
||||
if math.Abs(distance(before, c.View.Entity.Position)-(w.Balance.PlayerSpeed+1)*.05) > 1e-8 {
|
||||
t.Fatal("title movement effect not applied")
|
||||
}
|
||||
w.Mobs["target"] = &Mob{Entity: p.Entity{ID: "target", HP: 100, Position: c.View.Entity.Position}}
|
||||
if err := w.Intent(c.View.Entity.ID, p.Intent{Op: "attack", Seq: 2, Target: "target"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if w.Mobs["target"].Entity.HP != 100-w.Balance.PlayerDamage-3 {
|
||||
t.Fatal("signed damage effects not applied")
|
||||
}
|
||||
c.View.Titles = append(c.View.Titles, p.TitleAward{ID: "heavy", Effects: p.TitleEffects{Damage: -1000, MoveSpeed: -1000}})
|
||||
if w.playerSpeed(c) != 0 {
|
||||
t.Fatal("negative speed reversed movement")
|
||||
}
|
||||
w.now = w.now.Add(time.Second)
|
||||
hp := w.Mobs["target"].Entity.HP
|
||||
if err := w.Intent(c.View.Entity.ID, p.Intent{Op: "attack", Seq: 3, Target: "target"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if w.Mobs["target"].Entity.HP != hp {
|
||||
t.Fatal("negative damage healed target")
|
||||
}
|
||||
w.Balance.DailyPlaySeconds = 1
|
||||
c.View.Entity.HP = 20
|
||||
w.Advance(w.now.Add(2*time.Second), 2)
|
||||
if c.Online || c.View.RemainingSeconds != 0 || c.View.Entity.HP != 50 {
|
||||
t.Fatal("title effects weakened daily cap")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBossXPAndSurvivalMilestoneGrantedOnce(t *testing.T) {
|
||||
w, c := fixture(t)
|
||||
offline, _ := w.Join("offline", "Offline")
|
||||
dead, _ := w.Join("dead", "Dead")
|
||||
w.kill(dead, "test")
|
||||
w.now = w.now.Add(time.Second)
|
||||
if err := w.TriggerBoss(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
w.BossHP = 1
|
||||
if err := w.Intent(c.View.Entity.ID, p.Intent{Op: "attack", Seq: 1, Target: "boss"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if c.BossKills != 1 || c.WorldsSurvived != 1 || offline.WorldsSurvived != 1 || dead.WorldsSurvived != 0 || c.View.Level != 4 || c.View.Experience != 50 || c.View.StatPoints != 15 {
|
||||
t.Fatal("incorrect boss progression")
|
||||
}
|
||||
if w.Intent(c.View.Entity.ID, p.Intent{Op: "attack", Seq: 2, Target: "boss"}) == nil {
|
||||
t.Fatal("repeat boss kill")
|
||||
}
|
||||
if c.BossKills != 1 || c.View.StatPoints != 15 {
|
||||
t.Fatal("duplicate boss rewards")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCollapseTitleMilestonesKeepDeterministicOrderAndDeath(t *testing.T) {
|
||||
w, c := fixture(t)
|
||||
w.Balance.Titles = []content.Title{{ID: "worlds_fallen", Name: "World's Fallen", Scope: "world", Requirements: []content.TitleRequirement{{Metric: "deaths", AtLeast: 1}}, Effects: content.TitleEffects{Damage: -1}}}
|
||||
other, err := w.Join("other", "Other")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c.Online = false
|
||||
ids := []string{c.View.Entity.ID, other.View.Entity.ID}
|
||||
sort.Strings(ids)
|
||||
w.Advance(w.CreatedAt.Add(time.Duration(w.Balance.SeasonSeconds+w.Balance.CollapseSeconds+1)*time.Second), .05)
|
||||
if w.Phase != "lost" || len(w.PendingTitles) != 2 {
|
||||
t.Fatal("collapse did not queue death milestones")
|
||||
}
|
||||
for i, id := range ids {
|
||||
if w.PendingTitles[i].CharacterID != id || w.Characters[id].View.Entity.State != "dead" || len(w.Characters[id].View.Titles) != 0 {
|
||||
t.Fatal("simultaneous deaths changed award order, life state, or prematurely granted title")
|
||||
}
|
||||
w.kill(w.Characters[id], "duplicate")
|
||||
}
|
||||
if len(w.PendingTitles) != 2 {
|
||||
t.Fatal("duplicate death milestone")
|
||||
}
|
||||
}
|
||||
@@ -14,22 +14,26 @@ import (
|
||||
)
|
||||
|
||||
type Character struct {
|
||||
View p.Character `json:"view"`
|
||||
Account string `json:"account"`
|
||||
Day string `json:"day"`
|
||||
DailySeconds float64 `json:"dailySeconds"`
|
||||
ReturnPosition *p.Vec3 `json:"returnPosition,omitempty"`
|
||||
Sheltered bool `json:"sheltered"`
|
||||
LastAttack float64 `json:"lastAttack"`
|
||||
LastGather float64 `json:"lastGather"`
|
||||
Online bool `json:"-"`
|
||||
MoveX float64 `json:"-"`
|
||||
MoveZ float64 `json:"-"`
|
||||
LastMove time.Time `json:"-"`
|
||||
Message string `json:"-"`
|
||||
BornAt time.Time `json:"bornAt"`
|
||||
DiedAt *time.Time `json:"diedAt,omitempty"`
|
||||
DeathReason string `json:"deathReason,omitempty"`
|
||||
View p.Character `json:"view"`
|
||||
Account string `json:"account"`
|
||||
Day string `json:"day"`
|
||||
DailySeconds float64 `json:"dailySeconds"`
|
||||
ReturnPosition *p.Vec3 `json:"returnPosition,omitempty"`
|
||||
Sheltered bool `json:"sheltered"`
|
||||
LastAttack float64 `json:"lastAttack"`
|
||||
LastGather float64 `json:"lastGather"`
|
||||
Online bool `json:"-"`
|
||||
MoveX float64 `json:"-"`
|
||||
MoveZ float64 `json:"-"`
|
||||
LastMove time.Time `json:"-"`
|
||||
Message string `json:"-"`
|
||||
BornAt time.Time `json:"bornAt"`
|
||||
DiedAt *time.Time `json:"diedAt,omitempty"`
|
||||
DeathReason string `json:"deathReason,omitempty"`
|
||||
Progression *content.Progression `json:"progression,omitempty"`
|
||||
WorldKills int64 `json:"worldKills"`
|
||||
BossKills int64 `json:"bossKills"`
|
||||
WorldsSurvived int64 `json:"worldsSurvived"`
|
||||
}
|
||||
type Corpse struct {
|
||||
Entity p.Entity `json:"entity"`
|
||||
@@ -58,6 +62,7 @@ type World struct {
|
||||
Depleted map[string]float64 `json:"depleted"`
|
||||
Mobs map[string]*Mob `json:"mobs"`
|
||||
Balance content.Balance `json:"balance"`
|
||||
PendingTitles []TitleCandidate `json:"-"`
|
||||
terrain *Terrain
|
||||
chunks map[string]p.Chunk
|
||||
now time.Time
|
||||
@@ -80,6 +85,19 @@ func (w *World) Restore(now time.Time) error {
|
||||
if w.Version != GeneratorVersion {
|
||||
return errors.New("unsupported persisted generator version")
|
||||
}
|
||||
// Snapshots predating progression receive the YAML defaults once. Existing
|
||||
// world tuning and character lives remain intact; old actions grant no backfill XP.
|
||||
if w.Balance.Progression == nil {
|
||||
defaults, err := content.Load()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
w.Balance.Progression = defaults.Progression
|
||||
if w.Balance.Titles == nil {
|
||||
w.Balance.Titles = defaults.Titles
|
||||
}
|
||||
w.dirty = true
|
||||
}
|
||||
if err := w.Balance.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -89,7 +107,11 @@ func (w *World) Restore(now time.Time) error {
|
||||
w.terrain = NewTerrain(w.Seed, w.Balance)
|
||||
w.chunks = map[string]p.Chunk{}
|
||||
w.now = now
|
||||
w.PendingTitles = nil
|
||||
for _, c := range w.Characters {
|
||||
if err := w.restoreProgression(c); err != nil {
|
||||
return err
|
||||
}
|
||||
c.Online = false
|
||||
c.MoveX = 0
|
||||
c.MoveZ = 0
|
||||
@@ -177,11 +199,15 @@ func (w *World) Join(account, name string) (*Character, error) {
|
||||
return nil, err
|
||||
}
|
||||
c := &Character{Account: account, Day: w.now.UTC().Format(time.DateOnly), View: p.Character{Entity: p.Entity{ID: ID(), Kind: "player", Name: name, Position: pos, HP: w.Balance.PlayerHp, MaxHP: w.Balance.PlayerHp, State: "alive"}, Inventory: map[string]int64{}, Skills: map[string]int64{}, RemainingSeconds: w.Balance.DailyPlaySeconds}}
|
||||
if err := w.restoreProgression(c); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for k, v := range w.Balance.StartingKit {
|
||||
c.View.Inventory[k] = v
|
||||
}
|
||||
w.Characters[c.View.Entity.ID] = c
|
||||
c.BornAt = w.now
|
||||
w.evaluateTitles(c)
|
||||
w.dirty = true
|
||||
return c, nil
|
||||
}
|
||||
@@ -192,6 +218,9 @@ func (w *World) Import(c *Character) error {
|
||||
if c.View.Entity.State != "eligible" || c.View.Entity.HP <= 0 {
|
||||
return errors.New("character is not a living survivor")
|
||||
}
|
||||
if err := w.restoreProgression(c); err != nil {
|
||||
return err
|
||||
}
|
||||
pos, err := w.spawn("")
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -207,6 +236,7 @@ func (w *World) Import(c *Character) error {
|
||||
c.ReturnPosition = nil
|
||||
c.Sheltered = false
|
||||
c.View.HasKeystone = false
|
||||
c.WorldKills = 0
|
||||
w.resetDay(c)
|
||||
w.Characters[c.View.Entity.ID] = c
|
||||
w.dirty = true
|
||||
@@ -356,6 +386,8 @@ func (w *World) gather(c *Character, target string) error {
|
||||
w.Depleted[target] = w.Age() + w.Balance.ResourceRespawnSeconds
|
||||
w.dirty = true
|
||||
c.Message = "Gathered " + item
|
||||
w.grantXP(c, w.Balance.Progression.GatherXP)
|
||||
w.evaluateTitles(c)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -379,6 +411,8 @@ func (w *World) craft(c *Character, name string) error {
|
||||
}
|
||||
c.View.Skills["crafting"] += w.Balance.SkillXpPerAction
|
||||
c.Message = "Crafted " + name
|
||||
w.grantXP(c, w.Balance.Progression.CraftXP)
|
||||
w.evaluateTitles(c)
|
||||
w.dirty = true
|
||||
return nil
|
||||
}
|
||||
@@ -390,17 +424,24 @@ func (w *World) attack(c *Character, target string) error {
|
||||
if c.View.Inventory["spear"] > 0 {
|
||||
damage = w.Balance.SpearDamage
|
||||
}
|
||||
damage = math.Max(0, damage+c.titleEffects().Damage)
|
||||
if target == "boss" {
|
||||
if w.Phase != "cataclysm" || distance(c.View.Entity.Position, w.terrain.Position(0, 0)) > w.Balance.AttackRange+4 {
|
||||
return errors.New("boss out of reach")
|
||||
}
|
||||
w.BossHP = math.Max(0, w.BossHP-damage)
|
||||
if w.BossHP == 0 {
|
||||
c.BossKills++
|
||||
w.grantXP(c, w.Balance.Progression.BossKillXP)
|
||||
w.evaluateTitles(c)
|
||||
w.Phase = "won"
|
||||
ended := w.now
|
||||
w.EndedAt = &ended
|
||||
for _, survivor := range w.Characters {
|
||||
// Stable order for simultaneous survivor milestone candidates.
|
||||
for _, survivor := range w.orderedCharacters() {
|
||||
if survivor.View.Entity.State == "alive" {
|
||||
survivor.WorldsSurvived++
|
||||
w.evaluateTitles(survivor)
|
||||
survivor.View.Entity.State = "eligible"
|
||||
survivor.MoveX = 0
|
||||
survivor.MoveZ = 0
|
||||
@@ -418,11 +459,14 @@ func (w *World) attack(c *Character, target string) error {
|
||||
m.Entity.State = "dead"
|
||||
m.RespawnAt = w.Age() + w.Balance.MobRespawnSeconds
|
||||
c.View.Kills++
|
||||
c.WorldKills++
|
||||
c.View.Inventory["herb"]++
|
||||
w.grantXP(c, w.Balance.Progression.MobKillXP)
|
||||
}
|
||||
}
|
||||
c.LastAttack = w.Age()
|
||||
c.View.Skills["combat"] += w.Balance.SkillXpPerAction
|
||||
w.evaluateTitles(c)
|
||||
w.dirty = true
|
||||
return nil
|
||||
}
|
||||
@@ -447,6 +491,7 @@ func (w *World) kill(c *Character, reason string) {
|
||||
died := w.now
|
||||
c.DiedAt = &died
|
||||
c.DeathReason = reason
|
||||
w.evaluateTitles(c)
|
||||
w.dirty = true
|
||||
}
|
||||
|
||||
@@ -464,7 +509,7 @@ func (w *World) Control(op, target, value, reason string) error {
|
||||
if w.Phase == "won" || w.Phase == "lost" {
|
||||
return errors.New("world has already ended")
|
||||
}
|
||||
for _, c := range w.Characters {
|
||||
for _, c := range w.orderedCharacters() {
|
||||
w.kill(c, "World ended by an operator: "+reason)
|
||||
}
|
||||
w.Phase = "lost"
|
||||
@@ -508,7 +553,8 @@ func (w *World) Advance(now time.Time, dt float64) {
|
||||
w.dirty = true
|
||||
}
|
||||
active := map[string]bool{}
|
||||
for _, c := range w.Characters {
|
||||
characters := w.orderedCharacters()
|
||||
for _, c := range characters {
|
||||
if c.View.Entity.State != "alive" {
|
||||
continue
|
||||
}
|
||||
@@ -541,7 +587,8 @@ func (w *World) Advance(now time.Time, dt float64) {
|
||||
c.MoveZ = 0
|
||||
}
|
||||
pos := c.View.Entity.Position
|
||||
nx, nz := pos.X+c.MoveX*w.Balance.PlayerSpeed*dt, pos.Z+c.MoveZ*w.Balance.PlayerSpeed*dt
|
||||
speed := w.playerSpeed(c)
|
||||
nx, nz := pos.X+c.MoveX*speed*dt, pos.Z+c.MoveZ*speed*dt
|
||||
if math.Hypot(nx, nz) < w.Balance.WorldRadius {
|
||||
c.View.Entity.Position = w.terrain.Position(nx, nz)
|
||||
}
|
||||
@@ -561,7 +608,7 @@ func (w *World) Advance(now time.Time, dt float64) {
|
||||
w.updateMobs(active, dt)
|
||||
if w.Phase == "cataclysm" {
|
||||
if w.Age()-w.BossLastAttack >= w.Balance.BossCooldown {
|
||||
for _, c := range w.Characters {
|
||||
for _, c := range characters {
|
||||
if c.Online && !c.Sheltered && c.View.Entity.State == "alive" && distance(c.View.Entity.Position, w.terrain.Position(0, 0)) <= w.Balance.BossRange {
|
||||
c.View.Entity.HP -= w.Balance.BossDamage
|
||||
w.dirty = true
|
||||
@@ -579,7 +626,7 @@ func (w *World) Advance(now time.Time, dt float64) {
|
||||
}
|
||||
}
|
||||
if w.SafeRadius() <= 0 || (len(w.Characters) > 0 && alive == 0) {
|
||||
for _, c := range w.Characters {
|
||||
for _, c := range characters {
|
||||
w.kill(c, "The world has been destroyed.")
|
||||
}
|
||||
w.Phase = "lost"
|
||||
@@ -613,7 +660,14 @@ func (w *World) ensureMob(ch p.Chunk) {
|
||||
w.Mobs[id] = &Mob{Entity: p.Entity{ID: id, Kind: "sentinel", Name: "Ash sentinel", Position: w.terrain.Position(x, z), HP: hp, MaxHP: hp, State: "alive"}, HomeX: int(ch.X), HomeZ: int(ch.Z)}
|
||||
}
|
||||
func (w *World) updateMobs(active map[string]bool, dt float64) {
|
||||
for id, m := range w.Mobs {
|
||||
mobIDs := make([]string, 0, len(w.Mobs))
|
||||
for id := range w.Mobs {
|
||||
mobIDs = append(mobIDs, id)
|
||||
}
|
||||
sort.Strings(mobIDs)
|
||||
characters := w.orderedCharacters()
|
||||
for _, id := range mobIDs {
|
||||
m := w.Mobs[id]
|
||||
key := Key(m.HomeX, m.HomeZ)
|
||||
if !active[key] {
|
||||
if m.Entity.HP == m.Entity.MaxHP || (m.Entity.HP <= 0 && w.Age() >= m.RespawnAt) {
|
||||
@@ -631,7 +685,7 @@ func (w *World) updateMobs(active map[string]bool, dt float64) {
|
||||
}
|
||||
var target *Character
|
||||
nearest := w.Balance.MobAggroRange
|
||||
for _, c := range w.Characters {
|
||||
for _, c := range characters {
|
||||
if !c.Online || c.View.Entity.State != "alive" || c.Sheltered {
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -55,14 +55,34 @@ type Vec3 struct {
|
||||
}
|
||||
|
||||
type Character struct {
|
||||
ACK int64 `json:"ack"`
|
||||
Entity Entity `json:"entity"`
|
||||
HasKeystone bool `json:"hasKeystone"`
|
||||
Inventory map[string]int64 `json:"inventory"`
|
||||
Kills int64 `json:"kills"`
|
||||
PlayedSeconds float64 `json:"playedSeconds"`
|
||||
RemainingSeconds float64 `json:"remainingSeconds"`
|
||||
Skills map[string]int64 `json:"skills"`
|
||||
ACK int64 `json:"ack"`
|
||||
Entity Entity `json:"entity"`
|
||||
Experience int64 `json:"experience"`
|
||||
ExperienceToNextLevel int64 `json:"experienceToNextLevel"`
|
||||
HasKeystone bool `json:"hasKeystone"`
|
||||
Inventory map[string]int64 `json:"inventory"`
|
||||
Kills int64 `json:"kills"`
|
||||
Level int64 `json:"level"`
|
||||
PlayedSeconds float64 `json:"playedSeconds"`
|
||||
RemainingSeconds float64 `json:"remainingSeconds"`
|
||||
Skills map[string]int64 `json:"skills"`
|
||||
StatPoints int64 `json:"statPoints"`
|
||||
Titles []TitleAward `json:"titles"`
|
||||
}
|
||||
|
||||
type TitleAward struct {
|
||||
Description string `json:"description"`
|
||||
EarnedAt string `json:"earnedAt"`
|
||||
Effects TitleEffects `json:"effects"`
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Scope string `json:"scope"`
|
||||
WorldID string `json:"worldId"`
|
||||
}
|
||||
|
||||
type TitleEffects struct {
|
||||
Damage float64 `json:"damage"`
|
||||
MoveSpeed float64 `json:"moveSpeed"`
|
||||
}
|
||||
|
||||
type WorldInfo struct {
|
||||
|
||||
@@ -64,6 +64,7 @@ func (d *DB) migrate(ctx context.Context) error {
|
||||
}
|
||||
for _, stmt := range []string{
|
||||
`CREATE TABLE IF NOT EXISTS schema_migrations(version INTEGER PRIMARY KEY)`,
|
||||
`CREATE TABLE IF NOT EXISTS title_awards(account_id TEXT NOT NULL, title_id TEXT NOT NULL, scope TEXT NOT NULL, scope_key TEXT NOT NULL, character_id TEXT NOT NULL, award TEXT NOT NULL, PRIMARY KEY(account_id,title_id), UNIQUE(scope,scope_key,title_id))`,
|
||||
`CREATE TABLE IF NOT EXISTS character_records(character_id TEXT PRIMARY KEY, account_id TEXT NOT NULL, world_id TEXT NOT NULL, name TEXT NOT NULL, state TEXT NOT NULL, character TEXT NOT NULL)`,
|
||||
`CREATE UNIQUE INDEX IF NOT EXISTS one_living_character ON character_records(account_id) WHERE state IN ('alive','eligible')`,
|
||||
`CREATE INDEX IF NOT EXISTS characters_world ON character_records(world_id)`,
|
||||
|
||||
@@ -135,6 +135,8 @@ 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 {
|
||||
live := w
|
||||
w = stageTitleWorld(w)
|
||||
data, err := json.Marshal(w)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -167,20 +169,26 @@ func (l *Lease) SaveCommand(ctx context.Context, w *game.World, claimID string,
|
||||
return errors.New("passage already redeemed or unavailable")
|
||||
}
|
||||
}
|
||||
if w.Phase == "won" {
|
||||
for _, c := range w.Characters {
|
||||
if c.View.Entity.State != "eligible" {
|
||||
continue
|
||||
}
|
||||
encoded, err := json.Marshal(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = tx.ExecContext(ctx, d.q(`INSERT INTO passages(character_id,account_id,source_world,character) VALUES(?,?,?,?) ON CONFLICT(character_id) DO UPDATE SET source_world=excluded.source_world,character=excluded.character,claimed_world=NULL WHERE passages.claimed_world=excluded.source_world`), c.View.Entity.ID, c.Account, w.ID, string(encoded))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err = d.syncPassages(ctx, tx, w); err != nil {
|
||||
return err
|
||||
}
|
||||
if err = d.syncCharacters(ctx, tx, w, claimID); err != nil {
|
||||
return err
|
||||
}
|
||||
if err = d.syncTitles(ctx, tx, w); err != nil {
|
||||
return err
|
||||
}
|
||||
// Rewrite the final payloads after the immutable award claims have resolved.
|
||||
// The transaction already holds the owner, passage and character row locks.
|
||||
data, err = json.Marshal(w)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err = tx.ExecContext(ctx, d.q(`UPDATE worlds SET snapshot=? WHERE id=? AND owner=?`), string(data), l.WorldID, l.Owner); err != nil {
|
||||
return err
|
||||
}
|
||||
if err = d.syncPassages(ctx, tx, w); err != nil {
|
||||
return err
|
||||
}
|
||||
if err = d.syncCharacters(ctx, tx, w, claimID); err != nil {
|
||||
return err
|
||||
@@ -208,7 +216,11 @@ func (l *Lease) SaveCommand(ctx context.Context, w *game.World, claimID string,
|
||||
return err
|
||||
}
|
||||
l.Revision++
|
||||
w.Saved()
|
||||
for id, c := range w.Characters {
|
||||
live.Characters[id].View.Titles = c.View.Titles
|
||||
}
|
||||
live.PendingTitles = nil
|
||||
live.Saved()
|
||||
return nil
|
||||
}
|
||||
func (l *Lease) Release(ctx context.Context) error {
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"sort"
|
||||
|
||||
"aeternalis/server/internal/game"
|
||||
p "aeternalis/server/internal/protocol"
|
||||
)
|
||||
|
||||
// Only title slices change in this staged view. The live simulation is untouched
|
||||
// until its snapshot, claim ledger, character records and passages all commit.
|
||||
func stageTitleWorld(w *game.World) *game.World {
|
||||
staged := *w
|
||||
staged.Characters = make(map[string]*game.Character, len(w.Characters))
|
||||
for id, c := range w.Characters {
|
||||
copy := *c
|
||||
copy.View.Titles = append([]p.TitleAward{}, c.View.Titles...)
|
||||
staged.Characters[id] = ©
|
||||
}
|
||||
return &staged
|
||||
}
|
||||
|
||||
func (d *DB) syncTitles(ctx context.Context, tx *sql.Tx, w *game.World) error {
|
||||
// syncCharacters has already locked these rows. A stale source world may
|
||||
// checkpoint itself, but it cannot grant titles for a transferred character.
|
||||
owned := make(map[string]bool, len(w.Characters))
|
||||
for id, c := range w.Characters {
|
||||
var account, world string
|
||||
err := tx.QueryRowContext(ctx, d.q(`SELECT account_id,world_id FROM character_records WHERE character_id=?`), id).Scan(&account, &world)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
owned[id] = account == c.Account && world == w.ID
|
||||
}
|
||||
candidates := append([]game.TitleCandidate{}, w.PendingTitles...)
|
||||
// All owners lock title IDs in the same order, even with different catalogs.
|
||||
// Stable ordering preserves simulation event order for contenders for one ID.
|
||||
sort.SliceStable(candidates, func(i, j int) bool { return candidates[i].Award.ID < candidates[j].Award.ID })
|
||||
granted := map[string]map[string]bool{}
|
||||
for _, candidate := range candidates {
|
||||
c := w.Characters[candidate.CharacterID]
|
||||
if c == nil || !owned[candidate.CharacterID] {
|
||||
continue
|
||||
}
|
||||
award := candidate.Award
|
||||
if award.ID == "" || award.WorldID != w.ID {
|
||||
return errors.New("invalid title candidate identity")
|
||||
}
|
||||
key := ""
|
||||
switch award.Scope {
|
||||
case "personal":
|
||||
key = c.Account
|
||||
case "world":
|
||||
key = w.ID
|
||||
case "global":
|
||||
key = "global"
|
||||
default:
|
||||
return errors.New("invalid title candidate scope")
|
||||
}
|
||||
raw, err := json.Marshal(award)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
result, err := tx.ExecContext(ctx, d.q(`INSERT INTO title_awards(account_id,title_id,scope,scope_key,character_id,award) VALUES(?,?,?,?,?,?) ON CONFLICT DO NOTHING`), c.Account, award.ID, award.Scope, key, candidate.CharacterID, string(raw))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
count, err := result.RowsAffected()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if count == 1 {
|
||||
if granted[candidate.CharacterID] == nil {
|
||||
granted[candidate.CharacterID] = map[string]bool{}
|
||||
}
|
||||
granted[candidate.CharacterID][award.ID] = true
|
||||
}
|
||||
}
|
||||
byAccount := map[string][]p.TitleAward{}
|
||||
for id, c := range w.Characters {
|
||||
if !owned[id] {
|
||||
continue
|
||||
}
|
||||
awards, loaded := byAccount[c.Account]
|
||||
if !loaded {
|
||||
var err error
|
||||
awards, err = d.accountTitles(ctx, tx, c.Account)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
byAccount[c.Account] = awards
|
||||
}
|
||||
if c.View.Entity.State != "dead" {
|
||||
c.View.Titles = append([]p.TitleAward{}, awards...)
|
||||
continue
|
||||
}
|
||||
// A historical dead life keeps its own record. Only awards from its death
|
||||
// transaction are appended; titles from later lives do not rewrite history.
|
||||
keep := map[string]bool{}
|
||||
for _, award := range c.View.Titles {
|
||||
keep[award.ID] = true
|
||||
}
|
||||
for title := range granted[id] {
|
||||
keep[title] = true
|
||||
}
|
||||
c.View.Titles = []p.TitleAward{}
|
||||
for _, award := range awards {
|
||||
if keep[award.ID] {
|
||||
c.View.Titles = append(c.View.Titles, award)
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *DB) accountTitles(ctx context.Context, tx *sql.Tx, account string) ([]p.TitleAward, error) {
|
||||
rows, err := tx.QueryContext(ctx, d.q(`SELECT award FROM title_awards WHERE account_id=? ORDER BY title_id`), account)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
awards := []p.TitleAward{}
|
||||
for rows.Next() {
|
||||
var raw string
|
||||
var award p.TitleAward
|
||||
if err = rows.Scan(&raw); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err = json.Unmarshal([]byte(raw), &award); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
awards = append(awards, award)
|
||||
}
|
||||
return awards, rows.Err()
|
||||
}
|
||||
|
||||
func (d *DB) syncPassages(ctx context.Context, tx *sql.Tx, w *game.World) error {
|
||||
if w.Phase != "won" {
|
||||
return nil
|
||||
}
|
||||
// Stable row order also prevents competing owners from acquiring survivor
|
||||
// passage locks in opposite map iteration order.
|
||||
ids := make([]string, 0, len(w.Characters))
|
||||
for id := range w.Characters {
|
||||
ids = append(ids, id)
|
||||
}
|
||||
sort.Strings(ids)
|
||||
for _, id := range ids {
|
||||
c := w.Characters[id]
|
||||
if c.View.Entity.State != "eligible" {
|
||||
continue
|
||||
}
|
||||
encoded, err := json.Marshal(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = tx.ExecContext(ctx, d.q(`INSERT INTO passages(character_id,account_id,source_world,character) VALUES(?,?,?,?) ON CONFLICT(character_id) DO UPDATE SET source_world=excluded.source_world,character=excluded.character,claimed_world=NULL WHERE passages.claimed_world=excluded.source_world OR (passages.source_world=excluded.source_world AND passages.claimed_world IS NULL)`), c.View.Entity.ID, c.Account, w.ID, string(encoded))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,292 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"aeternalis/server/content"
|
||||
"aeternalis/server/internal/game"
|
||||
p "aeternalis/server/internal/protocol"
|
||||
)
|
||||
|
||||
func titleCandidate(w *game.World, c *game.Character, id, scope string) game.TitleCandidate {
|
||||
return game.TitleCandidate{CharacterID: c.View.Entity.ID, Award: p.TitleAward{ID: id, Name: id, Description: "A permanent test title", Scope: scope, WorldID: w.ID, EarnedAt: time.Now().UTC().Format(time.RFC3339Nano), Effects: p.TitleEffects{Damage: 2, MoveSpeed: -.5}}}
|
||||
}
|
||||
|
||||
func TestTitlePersistence(t *testing.T) {
|
||||
runTitleTests(t, "file:"+filepath.ToSlash(filepath.Join(t.TempDir(), "titles.db")))
|
||||
}
|
||||
func TestPostgresTitlePersistence(t *testing.T) {
|
||||
dsn := os.Getenv("TEST_DATABASE_URL")
|
||||
if dsn == "" {
|
||||
t.Skip("TEST_DATABASE_URL not configured")
|
||||
}
|
||||
runTitleTests(t, dsn)
|
||||
}
|
||||
func runTitleTests(t *testing.T, dsn string) {
|
||||
ctx := context.Background()
|
||||
db, err := Open(ctx, dsn)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Close()
|
||||
b, err := content.Load()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
prefix := game.ID()
|
||||
makeWorld := func(suffix string) (*game.World, *Lease, *game.Character) {
|
||||
t.Helper()
|
||||
w := game.New(prefix+suffix, 1, time.Now().UTC(), b)
|
||||
l, _, err := db.Acquire(ctx, w)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = l.Release(ctx) })
|
||||
c, err := w.Join(prefix+suffix, "Traveler")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return w, l, c
|
||||
}
|
||||
count := func(id string) int {
|
||||
t.Helper()
|
||||
var n int
|
||||
if err := db.sql.QueryRowContext(ctx, db.q(`SELECT count(*) FROM title_awards WHERE title_id=?`), id).Scan(&n); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return n
|
||||
}
|
||||
has := func(c *game.Character, id string) bool {
|
||||
for _, a := range c.View.Titles {
|
||||
if a.ID == id {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
t.Run("permanent inheritance and immutable history", func(t *testing.T) {
|
||||
w, l, c := makeWorld("-life")
|
||||
id := prefix + "-personal"
|
||||
w.PendingTitles = []game.TitleCandidate{titleCandidate(w, c, id, "personal")}
|
||||
if err := l.Save(ctx, w, ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
original := c.View.Titles[0]
|
||||
if count(id) != 1 || len(w.PendingTitles) != 0 {
|
||||
t.Fatal("award not committed")
|
||||
}
|
||||
c.View.Titles[0].Name = "Changed"
|
||||
c.View.Titles[0].Effects.Damage = 999
|
||||
w.PendingTitles = []game.TitleCandidate{titleCandidate(w, c, id, "personal")}
|
||||
if err := l.Save(ctx, w, ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if count(id) != 1 || !reflect.DeepEqual(c.View.Titles, []p.TitleAward{original}) {
|
||||
t.Fatal("retry changed immutable title")
|
||||
}
|
||||
if err := w.Control("retire", c.View.Entity.ID, "", "test"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := l.Save(ctx, w, ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
next, err := w.Join(c.Account, "Replacement")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := l.Save(ctx, w, ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !has(next, id) || !has(c, id) || next.View.Level != 1 || c.View.Entity.State != "dead" {
|
||||
t.Fatal("death lost title or resurrected life")
|
||||
}
|
||||
later := prefix + "-later"
|
||||
w.PendingTitles = []game.TitleCandidate{titleCandidate(w, next, later, "personal")}
|
||||
if err := l.Save(ctx, w, ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if has(c, later) || !has(next, later) {
|
||||
t.Fatal("later life rewrote dead history")
|
||||
}
|
||||
if err := l.Release(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
restoredLease, raw, err := db.Acquire(ctx, w)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer restoredLease.Release(ctx)
|
||||
var restored game.World
|
||||
if err = json.Unmarshal(raw, &restored); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = restored.Restore(time.Now()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !has(restored.Characters[next.View.Entity.ID], id) || restored.Characters[c.View.Entity.ID].View.Entity.State != "dead" {
|
||||
t.Fatal("restart lost titles or death")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("global race and independent world firsts", func(t *testing.T) {
|
||||
a, la, ca := makeWorld("-race-a")
|
||||
z, lz, cz := makeWorld("-race-z")
|
||||
global, world := prefix+"-global", prefix+"-world"
|
||||
a.PendingTitles = []game.TitleCandidate{titleCandidate(a, ca, world, "world"), titleCandidate(a, ca, global, "global")}
|
||||
z.PendingTitles = []game.TitleCandidate{titleCandidate(z, cz, global, "global"), titleCandidate(z, cz, world, "world")}
|
||||
var wg sync.WaitGroup
|
||||
results := make(chan error, 2)
|
||||
for _, pair := range []struct {
|
||||
w *game.World
|
||||
l *Lease
|
||||
}{{a, la}, {z, lz}} {
|
||||
wg.Add(1)
|
||||
go func(w *game.World, l *Lease) { defer wg.Done(); results <- l.Save(ctx, w, "") }(pair.w, pair.l)
|
||||
}
|
||||
wg.Wait()
|
||||
close(results)
|
||||
for err := range results {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
winners := 0
|
||||
for _, c := range []*game.Character{ca, cz} {
|
||||
if has(c, global) {
|
||||
winners++
|
||||
}
|
||||
if !has(c, world) {
|
||||
t.Fatal("first in own world denied")
|
||||
}
|
||||
}
|
||||
if winners != 1 || count(global) != 1 || count(world) != 2 {
|
||||
t.Fatal("global first duplicated or world scopes shared")
|
||||
}
|
||||
other, err := a.Join(prefix+"-contender", "Contender")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
a.PendingTitles = []game.TitleCandidate{titleCandidate(a, other, world, "world"), titleCandidate(a, other, global, "global")}
|
||||
if err = la.Save(ctx, a, ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if has(other, global) || has(other, world) {
|
||||
t.Fatal("late contender stole first")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("event order beats character map order", func(t *testing.T) {
|
||||
w, l, c := makeWorld("-order")
|
||||
other, err := w.Join(prefix+"-order-other", "Other")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
id := prefix + "-order-title"
|
||||
w.PendingTitles = []game.TitleCandidate{titleCandidate(w, other, id, "world"), titleCandidate(w, c, id, "world")}
|
||||
if err = l.Save(ctx, w, ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !has(other, id) || has(c, id) {
|
||||
t.Fatal("first simulation candidate lost")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("late transaction failure rolls back claims and view", func(t *testing.T) {
|
||||
w, l, c := makeWorld("-rollback")
|
||||
id := prefix + "-rollback-title"
|
||||
w.PendingTitles = []game.TitleCandidate{titleCandidate(w, c, id, "global")}
|
||||
before := l.Revision
|
||||
if err := l.SaveCommand(ctx, w, "", &Command{ID: "missing-command"}, ""); err == nil {
|
||||
t.Fatal("missing command committed")
|
||||
}
|
||||
if count(id) != 0 || len(c.View.Titles) != 0 || len(w.PendingTitles) != 1 || l.Revision != before {
|
||||
t.Fatal("failed save leaked title state")
|
||||
}
|
||||
if err := l.Save(ctx, w, ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if count(id) != 1 || !has(c, id) {
|
||||
t.Fatal("retry failed after rollback")
|
||||
}
|
||||
if err := l.Release(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
replacement, _, err := db.Acquire(ctx, w)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer replacement.Release(ctx)
|
||||
stale := prefix + "-stale-title"
|
||||
w.PendingTitles = []game.TitleCandidate{titleCandidate(w, c, stale, "global")}
|
||||
if err = l.Save(ctx, w, ""); err == nil {
|
||||
t.Fatal("stale owner saved")
|
||||
}
|
||||
if count(stale) != 0 || has(c, stale) {
|
||||
t.Fatal("stale owner claimed title")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("victory transfer and stale source", func(t *testing.T) {
|
||||
source, ls, c := makeWorld("-source")
|
||||
id := prefix + "-survivor"
|
||||
source.PendingTitles = []game.TitleCandidate{titleCandidate(source, c, id, "global")}
|
||||
c.View.Level = 2
|
||||
c.View.Experience = 20
|
||||
c.View.ExperienceToNextLevel = 150
|
||||
c.View.StatPoints = 5
|
||||
c.DailySeconds = 123
|
||||
c.View.Entity.State = "eligible"
|
||||
source.Phase = "won"
|
||||
if err := ls.Save(ctx, source, ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
survivor, err := db.ReadPassage(ctx, c.View.Entity.ID, c.Account)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !has(survivor, id) {
|
||||
t.Fatal("victory passage missed same-transaction title")
|
||||
}
|
||||
target := game.New(prefix+"-destination", 2, time.Now().UTC(), b)
|
||||
lt, _, err := db.Acquire(ctx, target)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer lt.Release(ctx)
|
||||
if err = target.Import(survivor); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = lt.Save(ctx, target, c.View.Entity.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !has(survivor, id) || survivor.View.StatPoints != 5 || survivor.View.Experience != 20 || survivor.DailySeconds != 123 {
|
||||
t.Fatal("passage lost progression")
|
||||
}
|
||||
forbidden := prefix + "-source-forbidden"
|
||||
source.PendingTitles = []game.TitleCandidate{titleCandidate(source, c, forbidden, "global")}
|
||||
if err = ls.Save(ctx, source, ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if count(forbidden) != 0 || has(c, forbidden) {
|
||||
t.Fatal("old source granted new title")
|
||||
}
|
||||
active, err := db.ActiveCharacter(ctx, c.Account)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if active.WorldID != target.ID || !has(active.Character, id) {
|
||||
t.Fatal("source overwrote destination")
|
||||
}
|
||||
if _, err = db.ReadPassage(ctx, c.View.Entity.ID, c.Account); err == nil {
|
||||
t.Fatal("source reopened spent passage")
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -22,7 +22,7 @@ func (h *HTTP) admin(w http.ResponseWriter, r *http.Request) (string, bool) {
|
||||
return "", false
|
||||
}
|
||||
if !h.auth.isAdmin(r) {
|
||||
fail(w, 403, "Administrator access required. Sign in again with the configured Keycloak role.")
|
||||
fail(w, 403, "Administrator access required. Your Keycloak ID token must include the role \""+h.auth.AdminRole+"\". Sign in again after assigning it.")
|
||||
return "", false
|
||||
}
|
||||
return account, true
|
||||
|
||||
@@ -115,3 +115,28 @@ func TestKeycloakRolesAndReturnURL(t *testing.T) {
|
||||
t.Fatal("game return lost or untrusted query retained")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdminRoleClaimsMatchExactlyAndOnlyOwnClient(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name, raw string
|
||||
want bool
|
||||
}{
|
||||
{"realm role", `{"realm_access":{"roles":["aeternalis-admin"]}}`, true},
|
||||
{"client role", `{"resource_access":{"game":{"roles":["aeternalis-admin"]}}}`, true},
|
||||
{"other client", `{"resource_access":{"other":{"roles":["aeternalis-admin"]}}}`, false},
|
||||
{"player", `{"realm_access":{"roles":["player"]}}`, false},
|
||||
{"case mismatch", `{"realm_access":{"roles":["Aeternalis-admin"]}}`, false},
|
||||
{"substring", `{"realm_access":{"roles":["not-aeternalis-admin"]}}`, false},
|
||||
{"missing", `{}`, false},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
var claims roleClaims
|
||||
if err := json.Unmarshal([]byte(tc.raw), &claims); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if claims.admin("aeternalis-admin", "game") != tc.want {
|
||||
t.Fatal("incorrect role access")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -177,6 +177,7 @@ func (s *Service) join(ctx context.Context, account, name, claim string) (p.Char
|
||||
view := c.View
|
||||
view.Inventory = maps.Clone(view.Inventory)
|
||||
view.Skills = maps.Clone(view.Skills)
|
||||
view.Titles = append([]p.TitleAward{}, view.Titles...)
|
||||
return view, nil
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user