Files
aeternalis/server/internal/game/world.go
T
dingoandClaude Sonnet 5 5df2f1b681 Merge control portal work from RPGTheory/aeternalis-portal
RPGTheory/aeternalis-portal had diverged from this repo (the git/CI/CD
copy) with an in-progress control portal feature that was never synced
back here, so none of it had gone through CI or been deployed:

- New site/game/control routing split: index.html becomes a world
  directory landing page (site.ts), game.html is the renamed former
  index.html (main.ts), control.html is a new admin panel
  (control.ts, portal-shared.ts, portal.css).
- Server: new internal/store/portal.go (character/world registry,
  command queue, admin grants) and internal/transport/control.go
  (portal API routes), plus a new internal/gitops package that lets
  the portal provision new worlds via a GitOps repo commit.
- game.World gains BornAt/DiedAt/DeathReason and an operator Control()
  path (close/open admissions, awaken boss, end world, per-character
  rename/heal/unstuck/retire); death no longer reuses the same
  character id on rejoin, matching the "new life" permadeath model in
  Plan.md rather than the old bypass-prevention test's expectations.
- deploy/: new control-egress network policy and portal/control
  values (admin role, GitOps repo/branch/values file/CIDRs).
- New e2e coverage: tests/portal.spec.ts, tools/capture-world.mjs.

Verified this repo's own independent commits (800ms movement-staleness
window, 20s boss-attack poll, SRS/TLS deploy values, ubuntu-22.04
runner pin, DOCKER_HOST fix) were already present in the portal copy
before merging, so nothing here regresses them. `tsc --noEmit`, the
vite client build, and the protocol contract check all pass; no go.mod
changes. Could not run `go build`/`go test` locally (no Go toolchain
on PATH, Docker daemon not running) — every new/changed Go symbol was
manually cross-referenced and resolves, but this should still be built
and tested in CI before merging to master.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-06 11:08:44 -04:00

715 lines
22 KiB
Go

package game
import (
"crypto/rand"
"encoding/hex"
"errors"
"fmt"
"math"
"sort"
"time"
"aeternalis/server/content"
p "aeternalis/server/internal/protocol"
)
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"`
}
type Corpse struct {
Entity p.Entity `json:"entity"`
Inventory map[string]int64 `json:"inventory"`
}
type Mob struct {
Entity p.Entity `json:"entity"`
HomeX int `json:"homeX"`
HomeZ int `json:"homeZ"`
LastAttack float64 `json:"lastAttack"`
RespawnAt float64 `json:"respawnAt"`
}
type World struct {
Version int `json:"version"`
ID string `json:"id"`
Seed int64 `json:"seed"`
CreatedAt time.Time `json:"createdAt"`
EndedAt *time.Time `json:"endedAt,omitempty"`
Phase string `json:"phase"`
AdmissionsClosed bool `json:"admissionsClosed"`
Tick int64 `json:"tick"`
BossHP float64 `json:"bossHp"`
BossLastAttack float64 `json:"bossLastAttack"`
Characters map[string]*Character `json:"characters"`
Corpses map[string]*Corpse `json:"corpses"`
Depleted map[string]float64 `json:"depleted"`
Mobs map[string]*Mob `json:"mobs"`
Balance content.Balance `json:"balance"`
terrain *Terrain
chunks map[string]p.Chunk
now time.Time
dirty bool
}
func ID() string {
var b [16]byte
if _, err := rand.Read(b[:]); err != nil {
panic(err)
}
return hex.EncodeToString(b[:])
}
func New(id string, seed int64, now time.Time, b content.Balance) *World {
w := &World{Version: GeneratorVersion, ID: id, Seed: seed, CreatedAt: now, Phase: "gathering", BossHP: b.BossHp, Characters: map[string]*Character{}, Corpses: map[string]*Corpse{}, Depleted: map[string]float64{}, Mobs: map[string]*Mob{}, Balance: b}
_ = w.Restore(now)
return w
}
func (w *World) Restore(now time.Time) error {
if w.Version != GeneratorVersion {
return errors.New("unsupported persisted generator version")
}
if err := w.Balance.Validate(); err != nil {
return err
}
if w.Characters == nil || w.Mobs == nil || w.Corpses == nil || w.Depleted == nil {
return errors.New("invalid world snapshot")
}
w.terrain = NewTerrain(w.Seed, w.Balance)
w.chunks = map[string]p.Chunk{}
w.now = now
for _, c := range w.Characters {
c.Online = false
c.MoveX = 0
c.MoveZ = 0
c.View.ACK = 0
}
return nil
}
func (w *World) Age() float64 {
now := w.now
if w.EndedAt != nil {
now = *w.EndedAt
}
return math.Max(0, now.Sub(w.CreatedAt).Seconds())
}
func (w *World) Dirty() bool { return w.dirty }
func (w *World) Saved() { w.dirty = false }
func (w *World) SafeRadius() float64 {
if w.Phase == "gathering" {
return w.Balance.WorldRadius
}
if w.Phase == "lost" {
return 0
}
return math.Max(0, w.Balance.WorldRadius*(1-(w.Age()-w.Balance.SeasonSeconds)/w.Balance.CollapseSeconds))
}
func (w *World) Info() p.WorldInfo {
online := int64(0)
for _, c := range w.Characters {
if c.Online {
online++
}
}
return p.WorldInfo{ID: w.ID, Seed: w.Seed, Phase: w.Phase, AgeSeconds: w.Age(), BossInSeconds: math.Max(0, w.Balance.SeasonSeconds-w.Age()), CollapseInSeconds: math.Max(0, w.Balance.SeasonSeconds+w.Balance.CollapseSeconds-w.Age()), SafeRadius: w.SafeRadius(), Radius: w.Balance.WorldRadius, Online: online, Capacity: int64(w.Balance.MaxPlayers), BossHP: w.BossHP, BossMaxHP: w.Balance.BossHp}
}
func (w *World) ForAccount(account string) *Character {
for _, c := range w.Characters {
if c.Account == account && c.View.Entity.State != "dead" {
return c
}
}
return nil
}
func (w *World) LivingCount() int {
n := 0
for _, c := range w.Characters {
if c.View.Entity.State != "dead" {
n++
}
}
return n
}
func (w *World) spawn(exclude string) (p.Vec3, error) {
for i := 0; i < 4096; i++ {
radius := math.Sqrt(float64(i)) * w.Balance.SpawnSeparation * 0.6
angle := float64(i) * 2.399963229728653
pos := w.terrain.Position(math.Cos(angle)*radius, math.Sin(angle)*radius)
if radius > math.Max(0, math.Min(w.Balance.WorldRadius-32, w.SafeRadius()-8)) {
break
}
clear := true
for id, c := range w.Characters {
if id != exclude && c.View.Entity.State != "dead" && distance(pos, c.View.Entity.Position) < w.Balance.SpawnSeparation {
clear = false
break
}
}
if clear {
return pos, nil
}
}
return p.Vec3{}, errors.New("no separated spawn available")
}
func (w *World) Join(account, name string) (*Character, error) {
if c := w.ForAccount(account); c != nil {
return c, nil
}
if (w.Phase != "gathering" && w.Phase != "cataclysm") || w.AdmissionsClosed {
return nil, errors.New("this world is closed to new arrivals")
}
if w.LivingCount() >= w.Balance.MaxPlayers {
return nil, errors.New("world capacity reached")
}
pos, err := w.spawn("")
if err != nil {
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}}
for k, v := range w.Balance.StartingKit {
c.View.Inventory[k] = v
}
w.Characters[c.View.Entity.ID] = c
c.BornAt = w.now
w.dirty = true
return c, nil
}
func (w *World) Import(c *Character) error {
if w.Phase != "gathering" || w.AdmissionsClosed || w.ForAccount(c.Account) != nil || w.Characters[c.View.Entity.ID] != nil || w.LivingCount() >= w.Balance.MaxPlayers {
return errors.New("destination cannot accept character")
}
if c.View.Entity.State != "eligible" || c.View.Entity.HP <= 0 {
return errors.New("character is not a living survivor")
}
pos, err := w.spawn("")
if err != nil {
return err
}
c.View.Entity.Position = pos
c.View.Entity.State = "alive"
c.Online = false
c.MoveX = 0
c.MoveZ = 0
c.View.ACK = 0
c.LastAttack = 0
c.LastGather = 0
c.ReturnPosition = nil
c.Sheltered = false
c.View.HasKeystone = false
w.resetDay(c)
w.Characters[c.View.Entity.ID] = c
w.dirty = true
return nil
}
func (w *World) resetDay(c *Character) {
day := w.now.UTC().Format(time.DateOnly)
if c.Day != day {
c.Day = day
c.DailySeconds = 0
w.dirty = true
}
c.View.RemainingSeconds = math.Max(0, w.Balance.DailyPlaySeconds-c.DailySeconds)
}
func (w *World) Connect(id string) error {
c := w.Characters[id]
if c == nil {
return errors.New("character not found")
}
w.resetDay(c)
if c.View.Entity.State == "dead" {
return errors.New("this character has died permanently")
}
if c.View.RemainingSeconds <= 0 {
return errors.New("daily play limit reached; resets at 00:00 UTC")
}
if c.Online {
return errors.New("character already connected")
}
c.Online = true
c.View.ACK = 0
c.MoveX = 0
c.MoveZ = 0
return nil
}
func (w *World) Disconnect(id string) {
if c := w.Characters[id]; c != nil {
c.Online = false
c.MoveX = 0
c.MoveZ = 0
}
}
func distance(a, b p.Vec3) float64 { return math.Hypot(a.X-b.X, a.Z-b.Z) }
func (w *World) chunk(x, z int) p.Chunk {
key := Key(x, z)
if c, ok := w.chunks[key]; ok {
return c
}
c := w.terrain.Chunk(x, z)
w.chunks[key] = c
return c
}
func (w *World) neighbors(pos p.Vec3) []p.Chunk {
x, z := ChunkCoord(pos.X, w.Balance.ChunkSize), ChunkCoord(pos.Z, w.Balance.ChunkSize)
chunks := make([]p.Chunk, 0, 9)
for dz := -1; dz <= 1; dz++ {
for dx := -1; dx <= 1; dx++ {
chunks = append(chunks, w.chunk(x+dx, z+dz))
}
}
return chunks
}
func (w *World) Intent(id string, i p.Intent) error {
c := w.Characters[id]
if c == nil || !c.Online || c.View.Entity.State != "alive" || w.Phase == "won" || w.Phase == "lost" {
return errors.New("character cannot act")
}
if i.Seq <= c.View.ACK || i.Seq > c.View.ACK+10000 {
return errors.New("invalid input sequence")
}
if math.IsNaN(i.X) || math.IsNaN(i.Z) || math.IsInf(i.X, 0) || math.IsInf(i.Z, 0) || math.Abs(i.X) > 1 || math.Abs(i.Z) > 1 || len(i.Target) > 100 {
return errors.New("invalid intent")
}
c.View.ACK = i.Seq
if c.Sheltered && ((i.Op == "move" && (i.X != 0 || i.Z != 0)) || (i.Op != "move" && i.Op != "heal")) {
c.Sheltered = false
w.dirty = true
}
switch i.Op {
case "move":
n := math.Max(1, math.Hypot(i.X, i.Z))
c.MoveX = i.X / n
c.MoveZ = i.Z / n
c.LastMove = w.now
return nil
case "gather":
return w.gather(c, i.Target)
case "craft":
return w.craft(c, i.Target)
case "attack":
return w.attack(c, i.Target)
case "heal":
if c.View.Inventory["bandage"] < 1 || c.View.Entity.HP >= c.View.Entity.MaxHP {
return errors.New("no bandage needed or available")
}
c.View.Inventory["bandage"]--
c.View.Entity.HP = math.Min(c.View.Entity.MaxHP, c.View.Entity.HP+w.Balance.BandageHealing)
w.dirty = true
case "return":
if c.ReturnPosition == nil {
return errors.New("no keystone destination")
}
if math.Hypot(c.ReturnPosition.X, c.ReturnPosition.Z) > w.SafeRadius() {
return errors.New("keystone destination has been destroyed")
}
c.View.Entity.Position = *c.ReturnPosition
c.ReturnPosition = nil
c.View.HasKeystone = false
w.dirty = true
case "loot":
corpse := w.Corpses[i.Target]
if corpse == nil || distance(c.View.Entity.Position, corpse.Entity.Position) > w.Balance.GatherRange {
return errors.New("corpse out of reach")
}
for k, v := range corpse.Inventory {
c.View.Inventory[k] += v
}
delete(w.Corpses, i.Target)
w.dirty = true
default:
return errors.New("unknown intent")
}
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]++
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
return nil
}
}
return errors.New("unknown resource")
}
func (w *World) craft(c *Character, name string) error {
r, ok := w.Balance.Recipes[name]
if !ok {
return errors.New("unknown recipe")
}
for k, v := range r.Inputs {
if c.View.Inventory[k] < v {
return errors.New("missing crafting materials")
}
}
for k, v := range r.Inputs {
c.View.Inventory[k] -= v
}
for k, v := range r.Outputs {
c.View.Inventory[k] += v
}
c.View.Skills["crafting"] += w.Balance.SkillXpPerAction
c.Message = "Crafted " + name
w.dirty = true
return nil
}
func (w *World) attack(c *Character, target string) error {
if w.Age()-c.LastAttack < w.Balance.AttackCooldown {
return errors.New("attack cooldown")
}
damage := w.Balance.PlayerDamage
if c.View.Inventory["spear"] > 0 {
damage = w.Balance.SpearDamage
}
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 {
w.Phase = "won"
ended := w.now
w.EndedAt = &ended
for _, survivor := range w.Characters {
if survivor.View.Entity.State == "alive" {
survivor.View.Entity.State = "eligible"
survivor.MoveX = 0
survivor.MoveZ = 0
survivor.Message = "The world is saved. Passage is open."
}
}
}
} else {
m := w.Mobs[target]
if m == nil || m.Entity.HP <= 0 || distance(c.View.Entity.Position, m.Entity.Position) > w.Balance.AttackRange {
return errors.New("target out of reach")
}
m.Entity.HP = math.Max(0, m.Entity.HP-damage)
if m.Entity.HP == 0 {
m.Entity.State = "dead"
m.RespawnAt = w.Age() + w.Balance.MobRespawnSeconds
c.View.Kills++
c.View.Inventory["herb"]++
}
}
c.LastAttack = w.Age()
c.View.Skills["combat"] += w.Balance.SkillXpPerAction
w.dirty = true
return nil
}
func (w *World) kill(c *Character, reason string) {
if c.View.Entity.State != "alive" {
return
}
e := c.View.Entity
e.ID = "corpse:" + e.ID
e.Kind = "corpse"
e.State = "dead"
e.HP = 0
w.Corpses[e.ID] = &Corpse{Entity: e, Inventory: c.View.Inventory}
c.View.Inventory = map[string]int64{}
c.View.Entity.HP = 0
c.View.Entity.State = "dead"
c.MoveX = 0
c.MoveZ = 0
c.ReturnPosition = nil
c.View.HasKeystone = false
c.Message = reason
died := w.now
c.DiedAt = &died
c.DeathReason = reason
w.dirty = true
}
// Operator changes use the same simulation and persistence path as gameplay.
func (w *World) Control(op, target, value, reason string) error {
switch op {
case "close-admissions", "open-admissions":
if w.Phase == "won" || w.Phase == "lost" {
return errors.New("world has ended")
}
w.AdmissionsClosed = op == "close-admissions"
case "awaken-boss":
return w.TriggerBoss()
case "end-world":
if w.Phase == "won" || w.Phase == "lost" {
return errors.New("world has already ended")
}
for _, c := range w.Characters {
w.kill(c, "World ended by an operator: "+reason)
}
w.Phase = "lost"
ended := w.now
w.EndedAt = &ended
default:
c := w.Characters[target]
if c == nil {
return errors.New("character not found")
}
if c.View.Entity.State != "alive" {
return errors.New("only living characters in an active world may be changed")
}
switch op {
case "rename":
c.View.Entity.Name = value
case "heal":
c.View.Entity.HP = c.View.Entity.MaxHP
case "unstuck":
c.View.Entity.Position = w.terrain.Position(0, 0)
c.MoveX, c.MoveZ = 0, 0
case "retire":
w.kill(c, "Character retired by an operator: "+reason)
default:
return errors.New("unknown control operation")
}
}
w.dirty = true
return nil
}
func (w *World) Advance(now time.Time, dt float64) {
playedDT := math.Max(0, dt)
w.now = now
w.Tick++
dt = math.Max(0, math.Min(dt, 0.25))
if w.Phase == "won" || w.Phase == "lost" {
return
}
if w.Phase == "gathering" && w.Age() >= w.Balance.SeasonSeconds {
w.Phase = "cataclysm"
w.dirty = true
}
active := map[string]bool{}
for _, c := range w.Characters {
if c.View.Entity.State != "alive" {
continue
}
w.resetDay(c)
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())
c.View.PlayedSeconds += playedDT
c.View.RemainingSeconds = math.Max(0, w.Balance.DailyPlaySeconds-c.DailySeconds)
if c.View.RemainingSeconds <= 0 {
pos := c.View.Entity.Position
c.ReturnPosition = &pos
c.Sheltered = true
c.View.HasKeystone = true
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
c.MoveX = 0
c.MoveZ = 0
c.Message = "Daily limit reached. Your keystone is ready for tomorrow."
w.dirty = true
}
}
if c.Online {
// A generous window: the client resends its move intent well under this on every
// rendered frame, but a slow/throttled frame (e.g. software-rendered CI) shouldn't
// zero out in-flight movement and strand a walk-to-target action mid-course.
if now.Sub(c.LastMove) > 800*time.Millisecond {
c.MoveX = 0
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
if math.Hypot(nx, nz) < w.Balance.WorldRadius {
c.View.Entity.Position = w.terrain.Position(nx, nz)
}
for _, ch := range w.neighbors(c.View.Entity.Position) {
active[ch.Key] = true
w.ensureMob(ch)
}
}
if w.Phase == "cataclysm" && math.Hypot(c.View.Entity.Position.X, c.View.Entity.Position.Z) > w.SafeRadius() {
c.View.Entity.HP -= w.Balance.StormDamagePerSecond * dt
w.dirty = true
}
if c.View.Entity.HP <= 0 {
w.kill(c, "The encroaching ruin claimed this character.")
}
}
w.updateMobs(active, dt)
if w.Phase == "cataclysm" {
if w.Age()-w.BossLastAttack >= w.Balance.BossCooldown {
for _, c := range w.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
if c.View.Entity.HP <= 0 {
w.kill(c, "The Harbinger ended this character's journey.")
}
}
}
w.BossLastAttack = w.Age()
}
alive := 0
for _, c := range w.Characters {
if c.View.Entity.State == "alive" {
alive++
}
}
if w.SafeRadius() <= 0 || (len(w.Characters) > 0 && alive == 0) {
for _, c := range w.Characters {
w.kill(c, "The world has been destroyed.")
}
w.Phase = "lost"
ended := w.now
w.EndedAt = &ended
w.dirty = true
}
}
// Keep CPU/GPU working sets bounded to subscribed chunks. Persistent deltas survive eviction.
for key := range w.chunks {
if !active[key] {
delete(w.chunks, key)
}
}
for key, until := range w.Depleted {
if until <= w.Age() {
delete(w.Depleted, key)
}
}
}
func (w *World) ensureMob(ch p.Chunk) {
id := "m:" + ch.Key
if _, ok := w.Mobs[id]; ok {
return
}
x, z := (float64(ch.X)+0.55)*ch.Size, (float64(ch.Z)+0.55)*ch.Size
if math.Hypot(x, z) > w.Balance.WorldRadius {
return
}
hp := w.Balance.MobHp * (1 + w.Age()/86400*w.Balance.MobScalePerDay)
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 {
key := Key(m.HomeX, m.HomeZ)
if !active[key] {
if m.Entity.HP == m.Entity.MaxHP || (m.Entity.HP <= 0 && w.Age() >= m.RespawnAt) {
delete(w.Mobs, id)
}
continue
}
if m.Entity.HP <= 0 {
if w.Age() >= m.RespawnAt {
m.Entity.HP = w.Balance.MobHp * (1 + w.Age()/86400*w.Balance.MobScalePerDay)
m.Entity.MaxHP = m.Entity.HP
m.Entity.State = "alive"
}
continue
}
var target *Character
nearest := w.Balance.MobAggroRange
for _, c := range w.Characters {
if !c.Online || c.View.Entity.State != "alive" || c.Sheltered {
continue
}
d := distance(c.View.Entity.Position, m.Entity.Position)
if d < nearest {
nearest = d
target = c
}
}
if target == nil {
continue
}
if nearest <= w.Balance.MobAttackRange {
if w.Age()-m.LastAttack >= w.Balance.MobCooldown {
target.View.Entity.HP -= w.Balance.MobDamage * (1 + w.Age()/86400*w.Balance.MobScalePerDay)
m.LastAttack = w.Age()
w.dirty = true
if target.View.Entity.HP <= 0 {
w.kill(target, "An ash sentinel ended this character's journey.")
}
}
} else {
pos, to := m.Entity.Position, target.View.Entity.Position
step := math.Min(nearest, w.Balance.MobSpeed*dt)
x, z := pos.X+(to.X-pos.X)/nearest*step, pos.Z+(to.Z-pos.Z)/nearest*step
if ChunkCoord(x, w.Balance.ChunkSize) == m.HomeX && ChunkCoord(z, w.Balance.ChunkSize) == m.HomeZ {
m.Entity.Position = w.terrain.Position(x, z)
}
}
}
}
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{}}
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] {
s.Chunks = append(s.Chunks, ch)
}
for _, r := range ch.Resources {
if w.Depleted[r.ID] > w.Age() {
s.UnavailableResources = append(s.UnavailableResources, r.ID)
}
}
}
visible := func(pos p.Vec3) bool {
return allowed[Key(ChunkCoord(pos.X, w.Balance.ChunkSize), ChunkCoord(pos.Z, w.Balance.ChunkSize))]
}
for _, other := range w.Characters {
if 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)
}
}
for _, m := range w.Mobs {
if m.Entity.HP > 0 && visible(m.Entity.Position) {
s.Entities = append(s.Entities, m.Entity)
}
}
for _, corpse := range w.Corpses {
if visible(corpse.Entity.Position) {
s.Entities = append(s.Entities, corpse.Entity)
}
}
if w.Phase == "cataclysm" && visible(w.terrain.Position(0, 0)) {
s.Entities = append(s.Entities, p.Entity{ID: "boss", Kind: "boss", Name: "The Harbinger", HP: w.BossHP, MaxHP: w.Balance.BossHp, Position: w.terrain.Position(0, 0), State: "alive"})
}
sort.Slice(s.Entities, func(i, j int) bool { return s.Entities[i].ID < s.Entities[j].ID })
return s
}
func (w *World) TriggerBoss() error {
if w.Phase != "gathering" {
return fmt.Errorf("boss event already started")
}
w.CreatedAt = w.now.Add(-time.Duration(w.Balance.SeasonSeconds * float64(time.Second)))
w.Phase = "cataclysm"
w.dirty = true
return nil
}