Add terrain biomes jumping and extensible gathering professions

This commit is contained in:
dingo
2026-09-08 21:54:23 -04:00
parent 141cb9e6b2
commit df7b245ca7
34 changed files with 1895 additions and 184 deletions
+12
View File
@@ -30,6 +30,18 @@ func (w *World) AdminItems(c *Character, op, value string) error {
}
if op == "grant-item" {
known := false
if w.Balance.Gathering != nil {
for _, r := range w.Balance.Gathering.Resources {
if r.Output == "self" && r.ID == id {
known = true
}
}
for _, v := range w.Balance.Gathering.Consumables {
if v.ID == id {
known = true
}
}
}
for _, key := range []string{"axe", "flint_and_steel", "fishing_pole", "wood", "ore", "herb", "bandage"} {
if key == id {
known = true
+84
View File
@@ -0,0 +1,84 @@
package game
import (
"aeternalis/server/content"
p "aeternalis/server/internal/protocol"
"fmt"
"hash/fnv"
"math"
"math/rand/v2"
"slices"
)
// Read-only arrival preview uses the world's generator and any explored layout.
func (w *World) PreviewChunk(x, z int) p.Chunk {
c := w.terrain.Chunk(x, z)
if layout, ok := w.ResourceLayouts[c.Key]; ok {
c.Biome, c.Color, c.Resources = layout.Biome, layout.Color, layout.Resources
}
return c
}
func (t *Terrain) biome(x, z int) content.BiomeDefinition {
list := t.B.Gathering.Biomes
total := int64(0)
for _, b := range list {
total += b.Weight
}
// Low-frequency noise creates contiguous biome regions; no per-frame randomness.
n := (t.noise.Eval2((float64(x)+0.5)/3, (float64(z)+0.5)/3) + 1) / 2
choice := int64(n * float64(total))
for _, b := range list {
choice -= b.Weight
if choice < 0 {
return b
}
}
return list[len(list)-1]
}
func (t *Terrain) Chunk(x, z int) p.Chunk {
c := t.legacyChunk(x, z)
if t.B.Gathering == nil {
return c
}
biome := t.biome(x, z)
c.Biome = biome.Name
c.Color = &biome.Color
if t.Version == 1 {
for i := range c.Resources {
e := &c.Resources[i]
e.ResourceID = stringPtr(e.Kind)
}
return c // Legacy coordinates and depleted IDs are never regenerated under new rules.
}
c.Resources = []p.Entity{}
for _, r := range t.B.Gathering.Resources {
if !slices.Contains(r.Biomes, biome.ID) {
continue
}
hash := fnv.New64a()
fmt.Fprintf(hash, "%d:%d:%d:%s", t.Seed, x, z, r.ID)
rng := rand.New(rand.NewPCG(hash.Sum64(), uint64(t.Seed)))
count := r.Density
if biome.ID == "forest" && r.Model == "tree" {
count = min(int64(32), count*2)
}
for i := int64(0); i < count && len(c.Resources) < 128; i++ {
px, pz := (float64(x)+.08+rng.Float64()*.84)*c.Size, (float64(z)+.08+rng.Float64()*.84)*c.Size
if math.Hypot(px, pz) > t.B.WorldRadius || math.Hypot(px, pz) < 25 {
continue
}
c.Resources = append(c.Resources, p.Entity{ID: fmt.Sprintf("r:%d:%d:%s:%d", x, z, r.ID, i), Kind: r.Model, Name: r.Name, ResourceID: stringPtr(r.ID), SkillID: stringPtr(r.SkillID), RequiredLevel: &r.RequiredLevel, Position: t.Position(px, pz), HP: 1, MaxHP: 1, State: "available"})
}
}
if x == 0 && z == 0 {
for i, id := range []string{"tree", "ore", "herb"} {
for _, r := range t.B.Gathering.Resources {
if r.ID == id {
c.Resources = append(c.Resources, p.Entity{ID: "arrival:" + id, Kind: r.Model, Name: r.Name, ResourceID: stringPtr(id), SkillID: stringPtr(r.SkillID), RequiredLevel: &r.RequiredLevel, Position: t.Position(12+float64(i)*5, 12), HP: 1, MaxHP: 1, State: "available"})
}
}
}
}
return c
}
+1 -1
View File
@@ -62,7 +62,7 @@ func (w *World) addInventoryItems(inventory *map[string]int64, items *[]p.ItemIn
item.Requirements.Stats[stat] = value
}
for _, modifier := range definition.Modifiers {
item.Modifiers = append(item.Modifiers, p.StatModifier{Stat: modifier.Stat, Flat: modifier.Flat, Percent: modifier.Percent})
item.Modifiers = append(item.Modifiers, p.StatModifier{Skill: stringPtr(modifier.Skill), Stat: modifier.Stat, Flat: modifier.Flat, Percent: modifier.Percent})
}
created = append(created, item)
}
+298
View File
@@ -0,0 +1,298 @@
package game
import (
"aeternalis/server/content"
p "aeternalis/server/internal/protocol"
"errors"
"fmt"
"math"
"slices"
)
func stringPtr(s string) *string {
if s == "" {
return nil
}
return &s
}
func stringValue(s *string) string {
if s == nil {
return ""
}
return *s
}
func (w *World) restoreGathering(c *Character) error {
for _, xp := range c.View.Skills {
if xp < 0 || xp > 1000000000000 {
return errors.New("invalid persisted skill XP")
}
}
if math.IsNaN(c.JumpVelocity) || math.IsInf(c.JumpVelocity, 0) || math.IsNaN(c.GatherReadyAt) || math.IsInf(c.GatherReadyAt, 0) || c.GatherReadyAt < 0 || len(c.View.GatheringEffects) > 128 {
return errors.New("invalid persisted gathering/movement state")
}
seen := map[string]bool{}
live := []p.TimedGatheringEffect{}
for _, e := range c.View.GatheringEffects {
if e.Source == "" || len(e.Source) > 100 || seen[e.Source] || len(e.Name) > 160 || math.IsNaN(e.ExpiresAt) || math.IsInf(e.ExpiresAt, 0) || e.ExpiresAt < 0 {
return errors.New("invalid persisted gathering effect")
}
seen[e.Source] = true
mods := []content.StatModifier{}
for _, m := range e.Modifiers {
if !content.GatheringStat(m.Stat) {
return errors.New("unsupported timed gathering modifier")
}
mods = append(mods, content.StatModifier{Stat: m.Stat, Skill: stringValue(m.Skill), Flat: m.Flat, Percent: m.Percent})
}
if err := content.ValidateModifiers(mods); err != nil {
return err
}
if e.ExpiresAt > float64(w.now.UnixMilli())/1000 {
live = append(live, e)
}
}
if len(live) != len(c.View.GatheringEffects) {
w.dirty = true
}
c.View.GatheringEffects = live
return nil
}
func (w *World) gatheringModifiers(c *Character) []p.StatModifier {
mods := []p.StatModifier{}
seen := map[string]bool{}
for _, t := range c.View.Titles {
if !seen[t.ID] {
mods = append(mods, t.Effects.Modifiers...)
seen[t.ID] = true
}
}
equipped := map[string]bool{}
for _, id := range c.View.Equipment {
equipped[id] = true
}
for _, i := range c.View.Items {
if equipped[i.ID] {
mods = append(mods, i.Modifiers...)
}
}
now := float64(w.now.UnixMilli()) / 1000
for _, e := range c.View.GatheringEffects {
if e.ExpiresAt > now {
mods = append(mods, e.Modifiers...)
}
}
return mods
}
func (w *World) refreshGathering(c *Character) {
if w.Balance.Gathering == nil {
return
}
if c.View.Skills == nil {
c.View.Skills = map[string]int64{}
}
c.View.Gathering = map[string]p.SkillProgress{}
mods := w.gatheringModifiers(c)
value := func(skill, key string, base, min, max float64) p.StatValue {
v := p.StatValue{Base: base}
for _, m := range mods {
if m.Stat == key && (stringValue(m.Skill) == "" || stringValue(m.Skill) == skill) {
v.Flat += m.Flat
v.Percent += m.Percent
}
}
v.Final = math.Max(min, math.Min(max, (v.Base+v.Flat)*math.Max(0, 1+v.Percent/100)))
return v
}
for _, s := range w.Balance.Gathering.Skills {
xp := max(0, c.View.Skills[s.ID])
remaining := xp
level := int64(1)
for level < s.MaxLevel {
cost := s.BaseXP + (level-1)*s.XPPerLevel
if remaining < cost {
break
}
remaining -= cost
level++
}
next := s.BaseXP + (level-1)*s.XPPerLevel - remaining
if level == s.MaxLevel {
next = 0
}
lv := value(s.ID, "gatheringLevel", float64(level), 1, 10000)
c.View.Gathering[s.ID] = p.SkillProgress{Name: s.Name, XP: xp, Level: level, XPToNextLevel: next, EffectiveLevel: int64(math.Floor(lv.Final)), LevelValue: lv, Yield: value(s.ID, "gatheringYield", c.View.Stats["gatherRate"].Final, 0, 100000), Speed: value(s.ID, "gatheringSpeed", 100, 10, 1000), Experience: value(s.ID, "gatheringXP", c.View.Stats["xpGain"].Final, 0, 100000)}
}
c.View.StackNames = map[string]string{}
for _, r := range w.Balance.Gathering.Resources {
if r.Output == "self" && c.View.Inventory[r.ID] > 0 {
c.View.StackNames[r.ID] = r.Name
}
}
c.View.Consumables = []p.GatheringConsumable{}
for _, v := range w.Balance.Gathering.Consumables {
if c.View.Inventory[v.ID] > 0 {
c.View.StackNames[v.ID] = v.Name
c.View.Consumables = append(c.View.Consumables, p.GatheringConsumable{ID: v.ID, Name: v.Name, Description: v.Description, Seconds: v.Seconds, Modifiers: protocolModifiers(v.Modifiers)})
}
}
}
func (w *World) resource(id string) *content.ResourceDefinition {
for i := range w.Balance.Gathering.Resources {
if w.Balance.Gathering.Resources[i].ID == id {
return &w.Balance.Gathering.Resources[i]
}
}
return nil
}
func (w *World) gatherRisk(c *Character, r content.ResourceDefinition) p.GatheringRisk {
s := c.View.Gathering[r.SkillID]
gap := max(int64(0), r.RequiredLevel-s.EffectiveLevel)
rules := w.Balance.GatheringRules
risk := p.GatheringRisk{Allowed: gap <= 20, Seconds: r.Seconds * 100 / math.Max(10, s.Speed.Final)}
if gap > 0 {
risk.Failure = math.Min(rules.FailureMax, rules.FailureBase+float64(gap)*rules.FailurePerLevel)
risk.Destruction = math.Min(100, rules.DestroyBase+float64(gap)*rules.DestroyPerLevel)
risk.Negative = rules.NegativeChance
risk.Damage = float64(gap) * rules.DamagePerLevel
}
return risk
}
func (w *World) gather(c *Character, target string) error {
if until := w.Depleted[target]; until > w.Age() {
return errors.New("resource depleted")
}
w.refreshGathering(c)
for _, ch := range w.neighbors(c.View.Entity.Position) {
for _, e := range ch.Resources {
if e.ID != target {
continue
}
if distance(c.View.Entity.Position, e.Position) > w.Balance.GatherRange || math.Abs(c.View.Entity.Position.Y-e.Position.Y) > w.Balance.GatherRange {
return errors.New("resource out of reach")
}
id := stringValue(e.ResourceID)
if id == "" {
id = e.Kind
}
r := w.resource(id)
if r == nil {
return errors.New("not gatherable")
}
risk := w.gatherRisk(c, *r)
if !risk.Allowed {
return errors.New("resource requires more than 20 levels above your effective gathering level")
}
if w.Age() < c.GatherReadyAt || w.Age()-c.LastGather < risk.Seconds {
return errors.New("gathering cooldown")
}
c.LastGather = w.Age()
c.GatherReadyAt = w.Age() + risk.Seconds
c.View.GatherAttempt++
w.dirty = true
if w.roll(risk.Failure) {
destroyed := w.roll(risk.Destruction)
if destroyed {
w.Depleted[target] = w.Age() + r.RespawnSeconds
}
negative := w.roll(risk.Negative)
if negative {
c.View.Entity.HP = math.Max(0, c.View.Entity.HP-risk.Damage)
w.applyGatheringEffect(c, p.TimedGatheringEffect{Source: "fatigue:" + r.SkillID, Name: "Gathering fatigue: " + c.View.Gathering[r.SkillID].Name, ExpiresAt: float64(w.now.UnixMilli())/1000 + w.Balance.GatheringRules.FatigueSeconds, Modifiers: []p.StatModifier{{Stat: "gatheringSpeed", Skill: stringPtr(r.SkillID), Percent: -w.Balance.GatheringRules.FatiguePercent}}})
}
c.Message = "Gathering failed"
if destroyed {
c.Message += "; resource destroyed until respawn"
}
if negative {
c.Message += fmt.Sprintf("; %.0f damage and gathering fatigue", risk.Damage)
}
if c.View.Entity.HP <= 0 {
w.kill(c, "A dangerous gathering attempt ended this character's journey.")
}
w.RefreshStats(c)
return nil
}
output := r.Output
if output == "self" {
output = r.ID
}
n := w.yieldAmount(float64(r.Amount) * c.View.Gathering[r.SkillID].Yield.Final)
if n > 0 {
if err := w.addInventoryItems(&c.View.Inventory, &c.View.Items, output, n); err != nil {
return err
}
}
xp := int64(math.Min(1000000000, float64(r.XP)*c.View.Gathering[r.SkillID].Experience.Final/100))
c.View.Skills[r.SkillID] = min(int64(1000000000000), c.View.Skills[r.SkillID]+xp)
// Keep the legacy aggregate for existing title predicates, never as a level.
c.View.Skills["gathering"] = min(int64(1000000000000), c.View.Skills["gathering"]+w.Balance.SkillXpPerAction)
w.Depleted[target] = w.Age() + r.RespawnSeconds
label := output
if r.Output == "self" {
label = r.Name
}
c.Message = fmt.Sprintf("Gathered %d %s; +%d %s XP", n, label, xp, c.View.Gathering[r.SkillID].Name)
w.RefreshStats(c)
w.grantXP(c, w.Balance.Progression.GatherXP)
w.evaluateTitles(c)
return nil
}
}
return errors.New("unknown resource")
}
func (w *World) applyGatheringEffect(c *Character, e p.TimedGatheringEffect) {
c.View.GatheringEffects = slices.DeleteFunc(c.View.GatheringEffects, func(v p.TimedGatheringEffect) bool {
return v.Source == e.Source || v.ExpiresAt <= float64(w.now.UnixMilli())/1000
})
c.View.GatheringEffects = append(c.View.GatheringEffects, e)
}
func (w *World) consumeGathering(c *Character, id string) error {
if c.View.Inventory[id] < 1 {
return errors.New("consumable not in inventory")
}
for _, v := range w.Balance.Gathering.Consumables {
if v.ID == id {
if len(c.View.GatheringEffects) >= 64 && !slices.ContainsFunc(c.View.GatheringEffects, func(e p.TimedGatheringEffect) bool { return e.Source == id }) {
return errors.New("too many active gathering effects")
}
c.View.Inventory[id]--
w.applyGatheringEffect(c, p.TimedGatheringEffect{Source: id, Name: v.Name, ExpiresAt: float64(w.now.UnixMilli())/1000 + v.Seconds, Modifiers: protocolModifiers(v.Modifiers)})
w.RefreshStats(c)
c.Message = "Used " + v.Name
w.dirty = true
return nil
}
}
return errors.New("unknown gathering consumable")
}
func (w *World) jump(c *Character) error {
ground := w.terrain.Height(c.View.Entity.Position.X, c.View.Entity.Position.Z)
if c.JumpVelocity != 0 || c.View.Entity.Position.Y > ground+0.05 {
return errors.New("already airborne")
}
c.JumpVelocity = w.Balance.GatheringRules.JumpSpeed
w.dirty = true
return nil
}
func (w *World) moveCharacter(c *Character, dt float64) {
pos := c.View.Entity.Position
speed := w.playerSpeed(c)
x, z := pos.X+c.MoveX*speed*dt, pos.Z+c.MoveZ*speed*dt
if math.Hypot(x, z) >= w.Balance.WorldRadius {
x, z = pos.X, pos.Z
}
ground := w.terrain.Height(x, z)
if c.JumpVelocity != 0 || pos.Y > w.terrain.Height(pos.X, pos.Z)+0.05 {
y := pos.Y + c.JumpVelocity*dt - w.Balance.GatheringRules.Gravity*dt*dt/2
c.JumpVelocity -= w.Balance.GatheringRules.Gravity * dt
if y <= ground {
y = ground
c.JumpVelocity = 0
}
c.View.Entity.Position = p.Vec3{X: x, Y: y, Z: z}
} else {
c.View.Entity.Position = w.terrain.Position(x, z)
}
}
+211
View File
@@ -0,0 +1,211 @@
package game
import (
"aeternalis/server/content"
p "aeternalis/server/internal/protocol"
"encoding/json"
"math"
"reflect"
"testing"
"time"
)
func gatheringArrival(t *testing.T, w *World, c *Character) {
t.Helper()
w.now = w.CreatedAt.Add(time.Minute)
c.View.Entity.Position = w.terrain.Position(12, 12)
}
func TestGatheringSkillsModifiersAndConsumables(t *testing.T) {
w, c := fixture(t)
gatheringArrival(t, w, c)
// A scoped item changes effective level, yield, speed and XP through one path.
mods := []p.StatModifier{{Stat: "gatheringLevel", Skill: stringPtr("lumberjack"), Flat: 5}, {Stat: "gatheringYield", Skill: stringPtr("lumberjack"), Percent: 100}, {Stat: "gatheringSpeed", Skill: stringPtr("lumberjack"), Percent: 100}, {Stat: "gatheringXP", Skill: stringPtr("lumberjack"), Percent: 100}}
c.View.Items = append(c.View.Items, p.ItemInstance{ID: "test-ring", DefinitionID: "test-ring", Name: "Test ring", Slot: "ring", Requirements: p.ItemRequirements{Level: 1}, Modifiers: mods})
c.View.Equipment["ring1"] = "test-ring"
w.RefreshStats(c)
if c.View.Gathering["lumberjack"].Level != 1 || c.View.Gathering["lumberjack"].EffectiveLevel != 6 || c.View.Gathering["miner"].EffectiveLevel != 1 {
t.Fatal("level bonus leaked or granted earned levels")
}
if err := w.gather(c, "arrival:tree"); err != nil {
t.Fatal(err)
}
if c.View.Inventory["wood"] != 2 || c.View.Skills["lumberjack"] != 4 || c.View.Skills["miner"] != 0 {
t.Fatal("wrong scoped yield or XP", c.View.Inventory, c.View.Skills)
}
if err := w.gather(c, "arrival:tree"); err == nil {
t.Fatal("depleted node rewarded twice")
}
delete(w.Depleted, "arrival:tree")
w.now = w.now.Add(200 * time.Millisecond)
if err := w.gather(c, "arrival:tree"); err == nil {
t.Fatal("gather speed bypassed cooldown")
}
w.now = w.now.Add(200 * time.Millisecond)
if err := w.gather(c, "arrival:tree"); err != nil {
t.Fatal(err)
}
if err := w.unequip(c, "ring1"); err != nil {
t.Fatal(err)
}
if c.View.Gathering["lumberjack"].EffectiveLevel != 1 || c.View.Skills["lumberjack"] != 8 {
t.Fatal("unequip changed earned XP")
}
c.View.Inventory["gathering_tonic"] = 2
if err := w.consumeGathering(c, "gathering_tonic"); err != nil {
t.Fatal(err)
}
first := c.View.GatheringEffects[0].ExpiresAt
w.now = w.now.Add(time.Second)
if err := w.consumeGathering(c, "gathering_tonic"); err != nil {
t.Fatal(err)
}
if len(c.View.GatheringEffects) != 1 || c.View.GatheringEffects[0].ExpiresAt <= first || c.View.Gathering["miner"].EffectiveLevel != 6 || c.View.Inventory["gathering_tonic"] != 0 {
t.Fatal("consumption did not refresh one source")
}
if err := w.consumeGathering(c, "gathering_tonic"); err == nil {
t.Fatal("used missing consumable")
}
raw, _ := json.Marshal(w)
var restored World
if err := json.Unmarshal(raw, &restored); err != nil {
t.Fatal(err)
}
if err := restored.Restore(w.now.Add(121 * time.Second)); err != nil {
t.Fatal(err)
}
rc := restored.Characters[c.View.Entity.ID]
if rc.View.Gathering["miner"].EffectiveLevel != 1 || rc.View.Skills["lumberjack"] != 8 {
t.Fatal("restart renewed expired bonus or lost progression")
}
}
func TestGatheringRiskCeilingFailureDeathAndReplacement(t *testing.T) {
w, c := fixture(t)
gatheringArrival(t, w, c)
r := w.resource("tree")
r.RequiredLevel = 22
before := c.View.GatherAttempt
if err := w.gather(c, "arrival:tree"); err == nil || c.View.GatherAttempt != before || len(w.Depleted) != 0 {
t.Fatal("accepted +21 or mutated rejection")
}
r.RequiredLevel = 21
risk := w.gatherRisk(c, *r)
if !risk.Allowed || risk.Failure < 95 || risk.Destruction < 90 || risk.Negative == 0 {
t.Fatal("+20 should be allowed but extremely risky", risk)
}
// Force each probabilistic outcome independently for deterministic lifecycle coverage.
rules := w.Balance.GatheringRules
rules.FailureBase = 100
rules.FailureMax = 100
rules.DestroyBase = 100
rules.NegativeChance = 100
if err := w.gather(c, "arrival:tree"); err != nil {
t.Fatal(err)
}
if c.View.Skills["lumberjack"] != 0 || c.View.Inventory["wood"] != 0 || w.Depleted["arrival:tree"] <= w.Age() || len(c.View.GatheringEffects) != 1 || c.View.Entity.HP >= c.View.Entity.MaxHP {
t.Fatal("failure gave rewards or omitted consequences")
}
c.View.Entity.HP = 1
delete(w.Depleted, "arrival:tree")
w.now = w.now.Add(time.Minute)
if err := w.gather(c, "arrival:tree"); err != nil {
t.Fatal(err)
}
if c.View.Entity.State != "dead" || len(w.Corpses) != 1 {
t.Fatal("lethal failure did not use permanent-death path")
}
if err := w.Intent(c.View.Entity.ID, p.Intent{Op: "gather", Seq: 1, Target: "arrival:tree"}); err == nil {
t.Fatal("dead character gathered")
}
replacement, err := w.Join(c.Account, "Replacement")
if err != nil {
t.Fatal(err)
}
if replacement.View.Gathering["lumberjack"].Level != 1 || len(replacement.View.GatheringEffects) != 0 {
t.Fatal("replacement inherited progress or effects")
}
}
func TestGatheringProgressAndEffectsTravel(t *testing.T) {
w, c := fixture(t)
c.View.Skills["miner"] = 90
c.View.Inventory["gathering_tonic"] = 1
if err := w.consumeGathering(c, "gathering_tonic"); err != nil {
t.Fatal(err)
}
c.DailySeconds = 123
c.View.Entity.State = "eligible"
expiry := c.View.GatheringEffects[0].ExpiresAt
b, _ := content.Load()
dest := New("next", 42, w.now, b)
if err := dest.Import(c); err != nil {
t.Fatal(err)
}
if c.View.Skills["miner"] != 90 || c.View.Gathering["miner"].Level != 4 || c.View.Gathering["miner"].EffectiveLevel != 9 || c.DailySeconds != 123 || c.View.GatheringEffects[0].ExpiresAt != expiry {
t.Fatal("travel reset XP, usage, or renewed effects")
}
if err := dest.Connect(c.View.Entity.ID); err != nil {
t.Fatal(err)
}
c.DailySeconds = b.DailyPlaySeconds
dest.Advance(w.now.Add(time.Second), 1)
if c.Online || !c.Sheltered {
t.Fatal("daily cap bypassed")
}
if err := dest.Intent(c.View.Entity.ID, p.Intent{Op: "jump", Seq: 1}); err == nil {
t.Fatal("capped player acted")
}
}
func TestJumpAndPersistedResourceLayouts(t *testing.T) {
w, c := fixture(t)
ground := c.View.Entity.Position.Y
if err := w.Intent(c.View.Entity.ID, p.Intent{Op: "jump", Seq: 1}); err != nil {
t.Fatal(err)
}
w.Advance(w.now.Add(100*time.Millisecond), .1)
if c.View.Entity.Position.Y <= ground {
t.Fatal("jump did not rise")
}
if err := w.Intent(c.View.Entity.ID, p.Intent{Op: "jump", Seq: 2}); err == nil {
t.Fatal("air jump accepted")
}
for i := 0; i < 30; i++ {
w.Advance(w.now.Add(50*time.Millisecond), .05)
}
if math.Abs(c.View.Entity.Position.Y-ground) > 1e-8 || c.JumpVelocity != 0 {
t.Fatal("jump did not land on authoritative terrain")
}
ch := w.chunk(0, 0)
depleted := ch.Resources[0].ID
w.Depleted[depleted] = w.Age() + 100
w.Balance.Gathering.Resources = append(w.Balance.Gathering.Resources, content.ResourceDefinition{ID: "added", Name: "Added", SkillID: "miner", Model: "ore", Output: "ore", RequiredLevel: 1, Amount: 1, Seconds: 1, RespawnSeconds: 60, Density: 32, Biomes: []string{"forest", "meadow", "highlands"}})
raw, _ := json.Marshal(w)
var restored World
_ = json.Unmarshal(raw, &restored)
if err := restored.Restore(w.now); err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(ch, restored.chunk(0, 0)) || restored.Depleted[depleted] != w.Depleted[depleted] {
t.Fatal("catalog/restart rerolled explored nodes or depletion")
}
found := false
for _, r := range restored.chunk(5, 0).Resources {
if stringValue(r.ResourceID) == "added" {
found = true
}
}
if !found {
t.Fatal("new resource missing from unexplored chunk")
}
old := NewTerrain(w.Seed, w.Balance)
old.Version = 1
restored.Version = 1
restored.ResourceLayouts = nil
if err := restored.Restore(w.now); err != nil {
t.Fatal(err)
}
if restored.terrain.Height(130, 75) != old.Height(130, 75) {
t.Fatal("legacy terrain changed")
}
if math.Abs(old.Height(130, 75)-w.terrain.Height(130, 75)) < .01 {
t.Fatal("new terrain is not deeper")
}
}
+6 -1
View File
@@ -15,7 +15,7 @@ import (
func protocolModifiers(in []content.StatModifier) []p.StatModifier {
out := make([]p.StatModifier, 0, len(in))
for _, m := range in {
out = append(out, p.StatModifier{Stat: m.Stat, Flat: m.Flat, Percent: m.Percent})
out = append(out, p.StatModifier{Skill: stringPtr(m.Skill), Stat: m.Stat, Flat: m.Flat, Percent: m.Percent})
}
return out
}
@@ -88,6 +88,7 @@ func (w *World) RefreshStats(c *Character) {
}
w.revalidateEquipment(c)
c.View.Stats = w.statValues(c, true)
w.refreshGathering(c)
c.View.Entity.MaxHP = c.View.Stats["healthPoints"].Final
c.View.Entity.HP = math.Min(c.View.Entity.HP, c.View.Entity.MaxHP)
c.View.Mana = math.Max(0, math.Min(c.View.Mana, c.View.Stats["manaPoints"].Final))
@@ -161,6 +162,10 @@ func (w *World) ApplyCatalog(catalog content.Catalog) error {
if err := catalog.Validate(); err != nil {
return err
}
if catalog.Gathering != nil {
w.Balance.Gathering = catalog.Gathering
w.terrain.B.Gathering = catalog.Gathering
}
w.Balance.Titles = catalog.Titles
w.Balance.Items = catalog.Items
w.Balance.Stats = &catalog.Stats
+10 -6
View File
@@ -10,20 +10,24 @@ import (
"github.com/ojrac/opensimplex-go"
)
const GeneratorVersion = 1
const GeneratorVersion = 2
type Terrain struct {
Seed int64
B content.Balance
noise opensimplex.Noise
Version int
Seed int64
B content.Balance
noise opensimplex.Noise
}
func NewTerrain(seed int64, b content.Balance) *Terrain {
return &Terrain{seed, b, opensimplex.New(seed)}
return &Terrain{Version: GeneratorVersion, Seed: seed, B: b, noise: opensimplex.New(seed)}
}
func (t *Terrain) rawHeight(x, z float64) float64 {
// A low, flat arrival clearing blends into broad hills and fine detail.
d := math.Min(1, math.Hypot(x, z)/55)
if t.Version >= 2 {
return (t.noise.Eval2(x/220, z/220)*t.B.GatheringRules.HillHeight + t.noise.Eval2(x/55, z/55)*t.B.GatheringRules.DetailHeight) * d
}
return (t.noise.Eval2(x/220, z/220)*17 + t.noise.Eval2(x/55, z/55)*3) * d
}
func ChunkCoord(v, size float64) int { return int(math.Floor(v / size)) }
@@ -42,7 +46,7 @@ func (t *Terrain) Height(x, z float64) float64 {
return d + (c-d)*(1-fx) + (b-d)*(1-fz)
}
func (t *Terrain) Position(x, z float64) p.Vec3 { return p.Vec3{X: x, Y: t.Height(x, z), Z: z} }
func (t *Terrain) Chunk(x, z int) p.Chunk {
func (t *Terrain) legacyChunk(x, z int) p.Chunk {
c := p.Chunk{Key: Key(x, z), X: int64(x), Z: int64(z), Size: t.B.ChunkSize, Resolution: int64(t.B.TerrainResolution), Biome: "highlands", Heights: []float64{}, Resources: []p.Entity{}}
for iz := 0; iz <= t.B.TerrainResolution; iz++ {
for ix := 0; ix <= t.B.TerrainResolution; ix++ {
+94 -40
View File
@@ -15,6 +15,9 @@ import (
)
type Character struct {
JumpVelocity float64 `json:"jumpVelocity"`
GatherReadyAt float64 `json:"gatherReadyAt"`
View p.Character `json:"view"`
Account string `json:"account"`
Day string `json:"day"`
@@ -49,7 +52,14 @@ type Mob struct {
LastAttack float64 `json:"lastAttack"`
RespawnAt float64 `json:"respawnAt"`
}
type ResourceLayout struct {
Biome string `json:"biome"`
Color *string `json:"color"`
Resources []p.Entity `json:"resources"`
}
type World struct {
ResourceLayouts map[string]ResourceLayout `json:"resourceLayouts,omitempty"`
Version int `json:"version"`
ID string `json:"id"`
Seed int64 `json:"seed"`
@@ -87,7 +97,7 @@ func New(id string, seed int64, now time.Time, b content.Balance) *World {
return w
}
func (w *World) Restore(now time.Time) error {
if w.Version != GeneratorVersion {
if w.Version != 1 && w.Version != GeneratorVersion {
return errors.New("unsupported persisted generator version")
}
// Snapshots predating progression receive the YAML defaults once. Existing
@@ -133,6 +143,22 @@ func (w *World) Restore(now time.Time) error {
w.Balance.MaxYieldPerAction = defaults.MaxYieldPerAction
w.dirty = true
}
if w.Balance.Gathering == nil || w.Balance.GatheringRules == nil {
b, err := content.Load()
if err != nil {
return err
}
if w.Balance.Gathering == nil {
w.Balance.Gathering = b.Gathering
}
if w.Balance.GatheringRules == nil {
w.Balance.GatheringRules = b.GatheringRules
}
w.dirty = true
}
if w.ResourceLayouts == nil {
w.ResourceLayouts = map[string]ResourceLayout{}
}
if err := w.Balance.Validate(); err != nil {
return err
}
@@ -140,6 +166,7 @@ func (w *World) Restore(now time.Time) error {
return errors.New("invalid world snapshot")
}
w.terrain = NewTerrain(w.Seed, w.Balance)
w.terrain.Version = w.Version
w.chunks = map[string]p.Chunk{}
w.now = now
w.PendingTitles = nil
@@ -150,6 +177,9 @@ func (w *World) Restore(now time.Time) error {
if err := w.restoreEquipment(c); err != nil {
return err
}
if err := w.restoreGathering(c); err != nil {
return err
}
if err := w.initializeStats(c); err != nil {
return err
}
@@ -249,6 +279,9 @@ func (w *World) Join(account, name string) (*Character, error) {
if err := w.restoreEquipment(c); err != nil {
return nil, err
}
if err := w.restoreGathering(c); err != nil {
return nil, err
}
if err := w.initializeStats(c); err != nil {
return nil, err
}
@@ -274,6 +307,9 @@ func (w *World) Import(c *Character) error {
if err := w.checkImportedEquipment(c); err != nil {
return err
}
if err := w.restoreGathering(c); err != nil {
return err
}
if err := w.initializeStats(c); err != nil {
return err
}
@@ -289,6 +325,8 @@ func (w *World) Import(c *Character) error {
c.View.ACK = 0
c.LastAttack = 0
c.LastGather = 0
c.GatherReadyAt = 0
c.JumpVelocity = 0
c.ReturnPosition = nil
c.Sheltered = false
c.View.HasKeystone = false
@@ -342,6 +380,12 @@ func (w *World) chunk(x, z int) p.Chunk {
return c
}
c := w.terrain.Chunk(x, z)
if layout, ok := w.ResourceLayouts[key]; ok {
c.Biome, c.Color, c.Resources = layout.Biome, layout.Color, layout.Resources
} else {
w.ResourceLayouts[key] = ResourceLayout{Biome: c.Biome, Color: c.Color, Resources: c.Resources}
w.dirty = true
}
w.chunks[key] = c
return c
}
@@ -388,6 +432,10 @@ func (w *World) Intent(id string, i p.Intent) error {
c.MoveZ = i.Z / n
c.LastMove = w.now
return nil
case "jump":
return w.jump(c)
case "consume":
return w.consumeGathering(c, i.Target)
case "gather":
return w.gather(c, i.Target)
case "craft":
@@ -409,6 +457,7 @@ func (w *World) Intent(id string, i p.Intent) error {
if math.Hypot(c.ReturnPosition.X, c.ReturnPosition.Z) > w.SafeRadius() {
return errors.New("keystone destination has been destroyed")
}
c.JumpVelocity = 0
c.View.Entity.Position = *c.ReturnPosition
c.ReturnPosition = nil
c.View.HasKeystone = false
@@ -420,39 +469,6 @@ func (w *World) Intent(id string, i p.Intent) error {
}
return nil
}
func (w *World) gather(c *Character, target string) error {
if w.Age()-c.LastGather < w.Balance.GatherCooldown {
return errors.New("gathering cooldown")
}
if until := w.Depleted[target]; until > w.Age() {
return errors.New("resource depleted")
}
for _, chunk := range w.neighbors(c.View.Entity.Position) {
for _, r := range chunk.Resources {
if r.ID != target {
continue
}
if distance(c.View.Entity.Position, r.Position) > w.Balance.GatherRange {
return errors.New("resource out of reach")
}
item := map[string]string{"tree": "wood", "ore": "ore", "herb": "herb"}[r.Kind]
if item == "" {
return errors.New("not gatherable")
}
c.View.Inventory[item] += w.yieldAmount(c.View.Stats["gatherRate"].Final)
c.View.Skills["gathering"] += w.Balance.SkillXpPerAction
c.LastGather = w.Age()
w.Depleted[target] = w.Age() + w.Balance.ResourceRespawnSeconds
w.dirty = true
c.Message = "Gathered " + item
w.RefreshStats(c)
w.grantXP(c, w.Balance.Progression.GatherXP)
w.evaluateTitles(c)
return nil
}
}
return errors.New("unknown resource")
}
func (w *World) craft(c *Character, name string) error {
r, ok := w.Balance.Recipes[name]
if !ok {
@@ -551,6 +567,8 @@ func (w *World) kill(c *Character, reason string) {
return
}
e := c.View.Entity
e.Position = w.terrain.Position(e.Position.X, e.Position.Z)
c.View.Entity.Position = e.Position
e.ID = "corpse:" + e.ID
e.Kind = "corpse"
e.State = "dead"
@@ -561,6 +579,7 @@ func (w *World) kill(c *Character, reason string) {
c.View.Equipment = map[string]string{}
c.View.CarryWeight = 0
c.View.Entity.HP = 0
c.JumpVelocity = 0
c.View.Entity.State = "dead"
c.MoveX = 0
c.MoveZ = 0
@@ -608,6 +627,7 @@ func (w *World) Control(op, target, value, reason string) error {
case "heal":
c.View.Entity.HP = c.View.Entity.MaxHP
case "unstuck":
c.JumpVelocity = 0
c.View.Entity.Position = w.terrain.Position(0, 0)
c.MoveX, c.MoveZ = 0, 0
case "retire":
@@ -638,6 +658,18 @@ func (w *World) Advance(now time.Time, dt float64) {
continue
}
w.resetDay(c)
nowSeconds := float64(w.now.UnixMilli()) / 1000
effects := c.View.GatheringEffects[:0]
for _, e := range c.View.GatheringEffects {
if e.ExpiresAt > nowSeconds {
effects = append(effects, e)
}
}
if len(effects) != len(c.View.GatheringEffects) {
c.View.GatheringEffects = effects
w.RefreshStats(c)
w.dirty = true
}
if c.Online {
midnight := time.Date(now.UTC().Year(), now.UTC().Month(), now.UTC().Day(), 0, 0, 0, 0, time.UTC)
c.DailySeconds += math.Min(playedDT, now.Sub(midnight).Seconds())
@@ -648,6 +680,7 @@ func (w *World) Advance(now time.Time, dt float64) {
c.ReturnPosition = &pos
c.Sheltered = true
c.View.HasKeystone = true
c.JumpVelocity = 0
c.View.Entity.Position = w.terrain.Position(0, 0)
c.View.Entity.HP = math.Min(c.View.Entity.MaxHP, math.Max(50, c.View.Entity.HP))
c.Online = false
@@ -670,12 +703,7 @@ func (w *World) Advance(now time.Time, dt float64) {
c.MoveX = 0
c.MoveZ = 0
}
pos := c.View.Entity.Position
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)
}
w.moveCharacter(c, dt)
for _, ch := range w.neighbors(c.View.Entity.Position) {
active[ch.Key] = true
w.ensureMob(ch)
@@ -804,14 +832,40 @@ func (w *World) updateMobs(active map[string]bool, dt float64) {
func (w *World) Snapshot(id string, known map[string]bool) p.Snapshot {
c := w.Characters[id]
s := p.Snapshot{Type: "snapshot", Version: 1, Tick: w.Tick, World: w.Info(), Self: c.View, Message: c.Message, Entities: []p.Entity{}, Chunks: []p.Chunk{}, ChunkKeys: []string{}, UnavailableResources: []string{}}
s.GatherRisks = map[string]p.GatheringRisk{}
allowed := map[string]bool{}
for _, ch := range w.neighbors(c.View.Entity.Position) {
allowed[ch.Key] = true
s.ChunkKeys = append(s.ChunkKeys, ch.Key)
if !known[ch.Key] {
ch.Resources = append([]p.Entity{}, ch.Resources...)
for index := range ch.Resources {
e := &ch.Resources[index]
id := stringValue(e.ResourceID)
if id == "" {
id = e.Kind
}
if r := w.resource(id); r != nil {
e.ResourceID = stringPtr(r.ID)
e.SkillID = stringPtr(r.SkillID)
e.RequiredLevel = &r.RequiredLevel
e.Name = r.Name
}
}
s.Chunks = append(s.Chunks, ch)
}
for _, r := range ch.Resources {
if w.Depleted[r.ID] <= w.Age() {
id := stringValue(r.ResourceID)
if id == "" {
id = r.Kind
}
if def := w.resource(id); def != nil {
if _, ok := s.GatherRisks[def.ID]; !ok {
s.GatherRisks[def.ID] = w.gatherRisk(c, *def)
}
}
}
if w.Depleted[r.ID] > w.Age() {
s.UnavailableResources = append(s.UnavailableResources, r.ID)
}