space-browser / commits / 2795ea7
feat: server gen
This diff is too big to show in full. The first 1000 lines are below, and every file is listed with its counts.
@@ -0,0 +1,107 @@
1+package main
2+
3+import (
4+ "encoding/json"
5+ "sync/atomic"
6+ "time"
7+
8+ "github.com/gorilla/websocket"
9+)
10+
11+const (
12+ writeWait = 10 * time.Second
13+ pongWait = 40 * time.Second
14+ pingPeriod = 30 * time.Second
15+)
16+
17+// Client is one websocket connection. A client may outlive its player: death
18+// keeps the connection open so the user can respawn.
19+type Client struct {
20+ conn *websocket.Conn
21+ send chan []byte
22+ playerID string
23+ closed atomic.Bool
24+}
25+
26+func newClient(conn *websocket.Conn) *Client {
27+ c := &Client{conn: conn, send: make(chan []byte, 256)}
28+ go c.writeLoop()
29+ go c.readLoop()
30+ return c
31+}
32+
33+func (c *Client) push(v any) {
34+ if c.closed.Load() {
35+ return
36+ }
37+ b, err := json.Marshal(v)
38+ if err != nil {
39+ return
40+ }
41+ select {
42+ case c.send <- b:
43+ default: // slow client: drop frame rather than stall the world
44+ }
45+}
46+
47+func (c *Client) writeLoop() {
48+ ticker := time.NewTicker(pingPeriod)
49+ defer ticker.Stop()
50+ defer c.conn.Close()
51+ for {
52+ select {
53+ case msg, ok := <-c.send:
54+ if !ok {
55+ c.conn.WriteMessage(websocket.CloseMessage, nil)
56+ return
57+ }
58+ c.conn.SetWriteDeadline(time.Now().Add(writeWait))
59+ if err := c.conn.WriteMessage(websocket.TextMessage, msg); err != nil {
60+ return
61+ }
62+ case <-ticker.C:
63+ c.conn.SetWriteDeadline(time.Now().Add(writeWait))
64+ if err := c.conn.WriteMessage(websocket.PingMessage, nil); err != nil {
65+ return
66+ }
67+ }
68+ }
69+}
70+
71+func (c *Client) readLoop() {
72+ defer func() {
73+ c.closed.Store(true)
74+ w.disconnect(c)
75+ }()
76+ c.conn.SetReadLimit(1 << 16)
77+ c.conn.SetReadDeadline(time.Now().Add(pongWait))
78+ c.conn.SetPongHandler(func(string) error {
79+ return c.conn.SetReadDeadline(time.Now().Add(pongWait))
80+ })
81+ for {
82+ _, data, err := c.conn.ReadMessage()
83+ if err != nil {
84+ return
85+ }
86+ var msg InMsg
87+ if err := json.Unmarshal(data, &msg); err != nil {
88+ continue
89+ }
90+ w.enqueue(func() { w.handle(c, &msg) })
91+ }
92+}
93+
94+// InMsg is the union of all client -> server commands.
95+type InMsg struct {
96+ T string `json:"t"`
97+ Callsign string `json:"callsign"`
98+ Shape string `json:"shape"`
99+ X float64 `json:"x"`
100+ Y float64 `json:"y"`
101+ Queue bool `json:"queue"`
102+ Target string `json:"target"`
103+ Name string `json:"name"`
104+ Piece int `json:"piece"`
105+ Slot int `json:"slot"`
106+ Text string `json:"text"`
107+}
@@ -0,0 +1,138 @@
1+package main
2+
3+import "math"
4+
5+// rotate returns v rotated by angle.
6+func rotate(v Vec2, angle float64) Vec2 {
7+ c, s := math.Cos(angle), math.Sin(angle)
8+ return Vec2{v.X*c - v.Y*s, v.X*s + v.Y*c}
9+}
10+
11+func (w *World) isShip(id string) bool {
12+ if _, ok := w.players[id]; ok {
13+ return true
14+ }
15+ _, ok := w.npcs[id]
16+ return ok
17+}
18+
19+// fireShip auto-fires every triangle piece at the current target when in range.
20+func (w *World) fireShip(owner string, ship *Ship, pos Vec2, angle float64, target string, dt float64, cd map[int]float64) {
21+ if target == "" || !w.isShip(target) {
22+ return
23+ }
24+ tpos, _, ok := w.entityPos(target)
25+ if !ok || pos.Dist(tpos) > config.Combat.Range {
26+ return
27+ }
28+ st := ship.Stats()
29+ dir := tpos.Sub(pos).Norm()
30+ fired := false
31+ for _, p := range ship.piecesSlice() {
32+ if p.Shape != "triangle" {
33+ continue
34+ }
35+ cd[p.ID] -= dt
36+ if cd[p.ID] > 0 {
37+ continue
38+ }
39+ cd[p.ID] = config.Combat.Cooldown
40+ origin := pos.Add(rotate(Vec2{p.X, p.Y}, angle))
41+ w.projs[w.nextID("j")] = &Projectile{
42+ Pos: origin,
43+ Vel: dir.Mul(config.Combat.ProjectileSpeed),
44+ Damage: st.Attack,
45+ Owner: owner,
46+ Target: target,
47+ Life: 3,
48+ }
49+ fired = true
50+ }
51+ if fired {
52+ w.tagCombat(owner, target)
53+ }
54+}
55+
56+func (w *World) stepProjectiles(dt float64) {
57+ for id, pr := range w.projs {
58+ pr.Life -= dt
59+ if pr.Life <= 0 {
60+ delete(w.projs, id)
61+ continue
62+ }
63+ if tpos, _, ok := w.entityPos(pr.Target); ok {
64+ pr.Vel = tpos.Sub(pr.Pos).Norm().Mul(config.Combat.ProjectileSpeed)
65+ }
66+ pr.Pos = pr.Pos.Add(pr.Vel.Mul(dt))
67+ if tpos, _, ok := w.entityPos(pr.Target); ok && pr.Pos.Dist(tpos) <= config.Combat.HitRadius {
68+ w.applyDamage(pr.Target, pr.Damage, pr.Owner)
69+ delete(w.projs, id)
70+ }
71+ }
72+}
73+
74+// tagCombat marks both parties as in combat for the configured delay.
75+func (w *World) tagCombat(a, b string) {
76+ until := w.t + config.Combat.Delay
77+ if p, ok := w.players[a]; ok {
78+ p.Combat = until
79+ }
80+ if p, ok := w.players[b]; ok {
81+ p.Combat = until
82+ if p.Target == "" && w.isShip(a) {
83+ p.Target = a // auto-engage the attacker
84+ p.Mode = "attack"
85+ }
86+ }
87+ if n, ok := w.npcs[b]; ok {
88+ n.Combat = until
89+ }
90+ if n, ok := w.npcs[a]; ok {
91+ n.Combat = until
92+ }
93+}
94+
95+// applyDamage applies reduced damage to a random piece of the target ship,
96+// handles piece destruction / graph severing, and books run statistics.
97+func (w *World) applyDamage(targetID string, amount float64, attacker string) {
98+ if ap, ok := w.players[attacker]; ok {
99+ ap.Stats.DamageDone += amount
100+ }
101+ if p, ok := w.players[targetID]; ok {
102+ w.damageShip(p.Ship, p.Pos, amount)
103+ p.Stats.DamageReceived += amount
104+ w.tagCombat(targetID, attacker)
105+ if len(p.Ship.Pieces) == 0 || p.Ship.Pieces[p.Ship.Root] == nil {
106+ w.killPlayer(p, "destroyed in combat")
107+ }
108+ return
109+ }
110+ if n, ok := w.npcs[targetID]; ok {
111+ w.damageShip(n.Ship, n.Pos, amount)
112+ w.tagCombat(targetID, attacker)
113+ if len(n.Ship.Pieces) == 0 || n.Ship.Pieces[n.Ship.Root] == nil {
114+ w.destroyNPC(n)
115+ }
116+ }
117+}
118+
119+// damageShip resolves armor, picks a piece, and severs the graph if needed.
120+func (w *World) damageShip(ship *Ship, pos Vec2, amount float64) {
121+ dmg := math.Max(config.Combat.ArmorFloor, amount-ship.Stats().Defense)
122+ pid := ship.randomPiece(w.rng)
123+ if pid < 0 {
124+ return
125+ }
126+ destroyed := ship.damage(pid, dmg)
127+ if !destroyed {
128+ return
129+ }
130+ wasRoot := pid == ship.Root
131+ ship.remove(pid)
132+ if wasRoot {
133+ return // caller re-checks the root and kills
134+ }
135+ for _, lp := range ship.sever() {
136+ w.dropPiece(pos, lp)
137+ }
138+}
@@ -0,0 +1,113 @@
1+package main
2+
3+import (
4+ _ "embed"
5+ "encoding/json"
6+ "fmt"
7+ "os"
8+)
9+
10+//go:embed config/game.json
11+var defaultConfigJSON []byte
12+
13+// Config is the single shared balancing file consumed by both the server and
14+// the client (the server also serves it verbatim at /config).
15+type Config struct {
16+ TickHz int `json:"tickHz"`
17+ PositionHz int `json:"positionHz"`
18+ DotsHz int `json:"dotsHz"`
19+ ReconnectSeconds float64 `json:"reconnectSeconds"`
20+ Galaxy struct {
21+ SeedFallback uint64 `json:"seedFallback"`
22+ Radius float64 `json:"radius"`
23+ StarCount int `json:"starCount"`
24+ CenterDensityPower float64 `json:"centerDensityPower"`
25+ StarSpacing struct {
26+ Min float64 `json:"min"`
27+ Max float64 `json:"max"`
28+ } `json:"starSpacing"`
29+ DiscoverRange float64 `json:"discoverRange"`
30+ OrbitRange float64 `json:"orbitRange"`
31+ Planets struct {
32+ Chance float64 `json:"chance"`
33+ Max int `json:"max"`
34+ OrbitMin float64 `json:"orbitMin"`
35+ OrbitMax float64 `json:"orbitMax"`
36+ } `json:"planets"`
37+ StarRadius struct {
38+ Min float64 `json:"min"`
39+ Max float64 `json:"max"`
40+ } `json:"starRadius"`
41+ PlanetRadius struct {
42+ Min float64 `json:"min"`
43+ Max float64 `json:"max"`
44+ } `json:"planetRadius"`
45+ Extras struct {
46+ AsteroidChance float64 `json:"asteroidChance"`
47+ CommsChance float64 `json:"commsChance"`
48+ ShipyardChance float64 `json:"shipyardChance"`
49+ WreckChance float64 `json:"wreckChance"`
50+ FleetChance float64 `json:"fleetChance"`
51+ EdgeFade float64 `json:"edgeFade"`
52+ } `json:"extras"`
53+ } `json:"galaxy"`
54+ Ship struct {
55+ PieceBaseHP float64 `json:"pieceBaseHP"`
56+ PieceBaseStat float64 `json:"pieceBaseStat"`
57+ ShapeBonus float64 `json:"shapeBonus"`
58+ QualityMult []float64 `json:"qualityMult"`
59+ SpeedPerPoint float64 `json:"speedPerPoint"`
60+ FuelPerPoint float64 `json:"fuelPerPoint"`
61+ MinSeparation float64 `json:"minSeparation"`
62+ AttachMax float64 `json:"attachMax"`
63+ MaxPieces int `json:"maxPieces"`
64+ } `json:"ship"`
65+ Combat struct {
66+ Range float64 `json:"range"`
67+ Cooldown float64 `json:"cooldown"`
68+ Delay float64 `json:"delay"`
69+ ProjectileSpeed float64 `json:"projectileSpeed"`
70+ HitRadius float64 `json:"hitRadius"`
71+ ArmorFloor float64 `json:"armorFloor"`
72+ } `json:"combat"`
73+ Fuel struct {
74+ PerDistance float64 `json:"perDistance"`
75+ ShareAmount float64 `json:"shareAmount"`
76+ ShareRange float64 `json:"shareRange"`
77+ } `json:"fuel"`
78+ Radio struct {
79+ LocalRange float64 `json:"localRange"`
80+ } `json:"radio"`
81+ Cargo struct {
82+ PickupRange float64 `json:"pickupRange"`
83+ EjectSpeed float64 `json:"ejectSpeed"`
84+ RePickDelay float64 `json:"rePickDelay"`
85+ CraftCost int `json:"craftCost"`
86+ UpgradeCostPerLevel int `json:"upgradeCostPerLevel"`
87+ RepairCost int `json:"repairCost"`
88+ FieldOre int `json:"fieldOre"`
89+ WreckPieces int `json:"wreckPieces"`
90+ } `json:"cargo"`
91+ NPC struct {
92+ EngageRange float64 `json:"engageRange"`
93+ HailRange float64 `json:"hailRange"`
94+ MinFleetSize int `json:"minFleetSize"`
95+ MaxFleetSize int `json:"maxFleetSize"`
96+ } `json:"npc"`
97+}
98+
99+func loadConfig(path string) (Config, []byte, error) {
100+ raw := defaultConfigJSON
101+ if path != "" {
102+ b, err := os.ReadFile(path)
103+ if err != nil {
104+ return Config{}, nil, err
105+ }
106+ raw = b
107+ }
108+ var c Config
109+ if err := json.Unmarshal(raw, &c); err != nil {
110+ return Config{}, nil, fmt.Errorf("parse config: %w", err)
111+ }
112+ return c, raw, nil
113+}
@@ -0,0 +1,87 @@
1+{
2+ "tickHz": 30,
3+ "positionHz": 15,
4+ "dotsHz": 1,
5+ "reconnectSeconds": 5,
6+ "galaxy": {
7+ "seedFallback": 11702656774886230293,
8+ "radius": 300000,
9+ "starCount": 1500,
10+ "centerDensityPower": 1.0,
11+ "starSpacing": {
12+ "min": 3000,
13+ "max": 15000
14+ },
15+ "discoverRange": 8000,
16+ "orbitRange": 700,
17+ "planets": {
18+ "chance": 0.7,
19+ "max": 8,
20+ "orbitMin": 300,
21+ "orbitMax": 4000
22+ },
23+ "starRadius": {
24+ "min": 120,
25+ "max": 420
26+ },
27+ "planetRadius": {
28+ "min": 30,
29+ "max": 120
30+ },
31+ "extras": {
32+ "asteroidChance": 0.5,
33+ "commsChance": 0.25,
34+ "shipyardChance": 0.2,
35+ "wreckChance": 0.35,
36+ "fleetChance": 0.3,
37+ "edgeFade": 0.15
38+ }
39+ },
40+ "ship": {
41+ "pieceBaseHP": 100,
42+ "pieceBaseStat": 5,
43+ "shapeBonus": 5,
44+ "qualityMult": [
45+ 1,
46+ 1.5,
47+ 2.25
48+ ],
49+ "speedPerPoint": 10,
50+ "fuelPerPoint": 10,
51+ "minSeparation": 45,
52+ "attachMax": 140,
53+ "maxPieces": 64
54+ },
55+ "combat": {
56+ "range": 320,
57+ "cooldown": 0.5,
58+ "delay": 3,
59+ "projectileSpeed": 900,
60+ "hitRadius": 24,
61+ "armorFloor": 1
62+ },
63+ "fuel": {
64+ "perDistance": 700,
65+ "shareAmount": 10,
66+ "shareRange": 400
67+ },
68+ "radio": {
69+ "localRange": 40000
70+ },
71+ "cargo": {
72+ "pickupRange": 140,
73+ "ejectSpeed": 60,
74+ "rePickDelay": 1.0,
75+ "craftCost": 5,
76+ "upgradeCostPerLevel": 3,
77+ "repairCost": 1,
78+ "fieldOre": 24,
79+ "wreckPieces": 4
80+ },
81+ "npc": {
82+ "engageRange": 1500,
83+ "hailRange": 5000,
84+ "minFleetSize": 1,
85+ "maxFleetSize": 12
86+ }
87+}
@@ -0,0 +1,220 @@
1+package main
2+
3+import (
4+ "math"
5+ "strings"
6+)
7+
8+func inOrbitOf(p *Player, poi *POI) bool {
9+ return p.Pos.Dist(poi.Pos()) <= config.Galaxy.OrbitRange
10+}
11+
12+// ---- naming ---------------------------------------------------------------
13+
14+func (w *World) namePOI(p *Player, id, name string) {
15+ poi := w.galaxy.get(id)
16+ if poi == nil {
17+ return
18+ }
19+ name = strings.TrimSpace(name)
20+ switch {
21+ case name == "" || len(name) > 24:
22+ w.toast(p, "invalid name")
23+ case poi.Kind == kindFleet:
24+ w.toast(p, "fleets cannot be named")
25+ case poi.Name != "":
26+ w.toast(p, "this place is already named")
27+ case !inOrbitOf(p, poi):
28+ w.toast(p, "get closer to name this place")
29+ default:
30+ poi.Name = name
31+ poi.NamedBy = p.Callsign
32+ p.Stats.Named = append(p.Stats.Named, name)
33+ if w.store != nil {
34+ _ = w.store.savePOI(poi)
35+ }
36+ w.named = append(w.named, namedEvent{ID: id, Name: name, By: p.Callsign})
37+ }
38+}
39+
40+// ---- cargo / trading ------------------------------------------------------
41+
42+func (w *World) eject(p *Player, slot int) {
43+ if slot < 0 || slot >= len(p.Cargo) {
44+ return
45+ }
46+ item := p.Cargo[slot]
47+ p.Cargo = append(p.Cargo[:slot], p.Cargo[slot+1:]...)
48+ dir := rotate(Vec2{1, 0}, p.Angle)
49+ w.items[w.nextID("i")] = &Item{
50+ Item: item,
51+ Pos: p.Pos.Add(dir.Mul(30)),
52+ Vel: dir.Mul(config.Cargo.EjectSpeed),
53+ NoPickup: w.t + config.Cargo.RePickDelay,
54+ }
55+}
56+
57+func (w *World) pickup(p *Player, target string) {
58+ if poi := w.galaxy.get(target); poi != nil && inOrbitOf(p, poi) {
59+ w.salvage(p, poi)
60+ return
61+ }
62+ var best *Item
63+ bestD := config.Cargo.PickupRange
64+ for _, it := range w.items {
65+ if it.NoPickup > w.t {
66+ continue
67+ }
68+ if d := p.Pos.Dist(it.Pos); d < bestD {
69+ bestD, best = d, it
70+ }
71+ }
72+ if best != nil {
73+ w.stow(p, best.ID)
74+ }
75+}
76+
77+func (w *World) salvage(p *Player, poi *POI) {
78+ switch poi.Kind {
79+ case kindAsteroid:
80+ space := p.cargoCap() - len(p.Cargo)
81+ n := min(space, poi.Ore)
82+ for i := 0; i < n; i++ {
83+ p.Cargo = append(p.Cargo, CargoItem{Kind: "ore"})
84+ }
85+ poi.Ore -= n
86+ p.Stats.OreGathered += n
87+ case kindWreck:
88+ for len(p.Cargo) < p.cargoCap() && len(poi.Wreck) > 0 {
89+ pc := poi.Wreck[0]
90+ poi.Wreck = poi.Wreck[1:]
91+ p.Cargo = append(p.Cargo, CargoItem{Kind: "piece", Shape: pc.Shape, Quality: pc.Quality, HP: pc.HP})
92+ p.Stats.PiecesGathered++
93+ }
94+ }
95+}
96+
97+func (w *World) removeOre(p *Player, n int) bool {
98+ if countOre(p.Cargo) < n {
99+ return false
100+ }
101+ out := p.Cargo[:0]
102+ for _, c := range p.Cargo {
103+ if n > 0 && c.Kind == "ore" {
104+ n--
105+ continue
106+ }
107+ out = append(out, c)
108+ }
109+ p.Cargo = out
110+ return true
111+}
112+
113+func countOre(cargo []CargoItem) int {
114+ n := 0
115+ for _, c := range cargo {
116+ if c.Kind == "ore" {
117+ n++
118+ }
119+ }
120+ return n
121+}
122+
123+// ---- shipyard services ----------------------------------------------------
124+
125+func (w *World) atShipyard(p *Player) bool {
126+ for _, poi := range w.galaxy.nearby(p.Pos, config.Galaxy.OrbitRange) {
127+ if poi.Kind == kindShipyard {
128+ return true
129+ }
130+ }
131+ return false
132+}
133+
134+func (w *World) craft(p *Player, shape string) {
135+ if !validShape(shape) || !w.atShipyard(p) {
136+ return
137+ }
138+ if len(p.Cargo) >= p.cargoCap() {
139+ w.toast(p, "cargo is full")
140+ return
141+ }
142+ if !w.removeOre(p, config.Cargo.CraftCost) {
143+ w.toast(p, "not enough ore to craft")
144+ return
145+ }
146+ p.Cargo = append(p.Cargo, CargoItem{Kind: "piece", Shape: shape, Quality: 1})
147+}
148+
149+func (w *World) upgrade(p *Player, pieceID int) {
150+ if !w.atShipyard(p) {
151+ return
152+ }
153+ piece, ok := p.Ship.Pieces[pieceID]
154+ if !ok || piece.Quality >= maxQuality {
155+ return
156+ }
157+ cost := config.Cargo.UpgradeCostPerLevel * piece.Quality
158+ if !w.removeOre(p, cost) {
159+ w.toast(p, "not enough ore to upgrade")
160+ return
161+ }
162+ oldMax := piece.MaxHP
163+ ratio := piece.HP / oldMax
164+ piece.Quality++
165+ piece.MaxHP = config.Ship.PieceBaseHP * qualityMult(piece.Quality)
166+ piece.HP = piece.MaxHP * ratio
167+}
168+
169+func (w *World) repair(p *Player, pieceID int) {
170+ if !w.atShipyard(p) {
171+ return
172+ }
173+ piece, ok := p.Ship.Pieces[pieceID]
174+ if !ok || piece.HP >= piece.MaxHP {
175+ return
176+ }
177+ if !w.removeOre(p, config.Cargo.RepairCost) {
178+ w.toast(p, "not enough ore to repair")
179+ return
180+ }
181+ piece.HP = piece.MaxHP
182+}
183+
184+// ---- fuel sharing ---------------------------------------------------------
185+
186+func (w *World) shareFuel(p *Player, target string) {
187+ t := w.players[target]
188+ if t == nil || t == p {
189+ return
190+ }
191+ if p.inCombat(w.t) || t.inCombat(w.t) {
192+ w.toast(p, "cannot share fuel in combat")
193+ return
194+ }
195+ if p.Pos.Dist(t.Pos) > config.Fuel.ShareRange {
196+ w.toast(p, "target is too far")
197+ return
198+ }
199+ amt := math.Min(config.Fuel.ShareAmount, p.Fuel)
200+ if amt <= 0 {
201+ w.toast(p, "no fuel to share")
202+ return
203+ }
204+ p.Fuel -= amt
205+ t.Fuel = math.Min(t.fuelCap(), t.Fuel+amt)
206+ w.toast(p, "fuel shared")
207+ w.toast(t, "fuel received")
208+}
209+
210+// ---- items ----------------------------------------------------------------
211+
212+func (w *World) stepItems(dt float64) {
213+ for _, it := range w.items {
214+ it.Pos = it.Pos.Add(it.Vel.Mul(dt))
215+ it.Vel = it.Vel.Mul(1 - math.Min(1, 2*dt))
216+ if it.Vel.Len() < 1 {
217+ it.Vel = Vec2{}
218+ }
219+ }
220+}
@@ -0,0 +1,248 @@
1+package main
2+
3+import (
4+ "fmt"
5+ "math"
6+)
7+
8+const (
9+ kindStar = "star"
10+ kindPlanet = "planet"
11+ kindAsteroid = "asteroid"
12+ kindComms = "comms"
13+ kindShipyard = "shipyard"
14+ kindWreck = "wreck"
15+ kindFleet = "fleet"
16+)
17+
18+// POI is a place of interest. Some kinds orbit a star, others are anchors.
19+type POI struct {
20+ ID string `json:"id"`
21+ Kind string `json:"kind"`
22+ X float64 `json:"x"`
23+ Y float64 `json:"y"`
24+ Radius float64 `json:"r"`
25+ Star string `json:"star,omitempty"`
26+ Orbit float64 `json:"orbit,omitempty"`
27+ Angle float64 `json:"angle,omitempty"`
28+ Name string `json:"name,omitempty"`
29+ NamedBy string `json:"by,omitempty"`
30+ Explored bool `json:"explored"`
31+
32+ Ore int `json:"ore,omitempty"`
33+ Wreck []*Piece `json:"wreck,omitempty"`
34+
35+ Hostile bool `json:"hostile,omitempty"`
36+ FleetCap int `json:"-"`
37+ Linked map[string]bool `json:"-"`
38+}
39+
40+func (p *POI) Pos() Vec2 { return Vec2{p.X, p.Y} }
41+
42+// orbitAround re-derives world position from the parent star.
43+func (p *POI) orbitAround(star *POI) {
44+ p.X = star.X + p.Orbit*math.Cos(p.Angle)
45+ p.Y = star.Y + p.Orbit*math.Sin(p.Angle)
46+}
47+
48+type Galaxy struct {
49+ Seed uint64
50+ POIs []*POI
51+ byID map[string]*POI
52+ Stars []*POI
53+ Home *POI
54+}
55+
56+func (g *Galaxy) get(id string) *POI { return g.byID[id] }
57+
58+// remove deletes a POI from the galaxy (used when a fleet is destroyed).
59+func (g *Galaxy) remove(id string) {
60+ p := g.byID[id]
61+ if p == nil {
62+ return
63+ }
64+ delete(g.byID, id)
65+ for i, q := range g.POIs {
66+ if q == p {
67+ g.POIs = append(g.POIs[:i], g.POIs[i+1:]...)
68+ break
69+ }
70+ }
71+}
72+
73+func (g *Galaxy) add(poi *POI) *POI {
74+ g.byID[poi.ID] = poi
75+ g.POIs = append(g.POIs, poi)
76+ if poi.Kind == kindStar {
77+ g.Stars = append(g.Stars, poi)
78+ }
79+ return poi
80+}
81+
82+// generateGalaxy builds the deterministic shared galaxy. Density decreases
83+// outward from the center so the core is populated and the rim is sparse.
84+func generateGalaxy(seed uint64) *Galaxy {
85+ r := newRNG(seed ^ 0xA5A5A5A5A5A5A5A5)
86+ g := &Galaxy{Seed: seed, byID: map[string]*POI{}}
87+
88+ radius := config.Galaxy.Radius
89+ power := config.Galaxy.CenterDensityPower
90+ counts := map[string]int{}
91+
92+ for i := 0; i < config.Galaxy.StarCount; i++ {
93+ u := r.Float64()
94+ dist := radius * math.Pow(u, power)
95+ angle := r.Float64() * 2 * math.Pi
96+ star := &POI{
97+ ID: fmt.Sprintf("star:%d", counts["star"]),
98+ Kind: kindStar,
99+ X: dist * math.Cos(angle),
100+ Y: dist * math.Sin(angle),
101+ Radius: r.Range(config.Galaxy.StarRadius.Min, config.Galaxy.StarRadius.Max),
102+ }
103+ counts["star"]++
104+ g.add(star)
105+
106+ // extras become more common toward the galactic core
107+ density := 1 - math.Min(1, dist/radius)
108+ fade := config.Galaxy.Extras.EdgeFade + (1-config.Galaxy.Extras.EdgeFade)*density
109+
110+ // planets
111+ if r.Chance(config.Galaxy.Planets.Chance * fade) {
112+ n := 1 + r.Intn(config.Galaxy.Planets.Max)
113+ for j := 0; j < n; j++ {
114+ p := &POI{
115+ ID: fmt.Sprintf("planet:%d", counts["planet"]),
116+ Kind: kindPlanet,
117+ Star: star.ID,
118+ Orbit: r.Range(config.Galaxy.Planets.OrbitMin, config.Galaxy.Planets.OrbitMax),
119+ Angle: r.Float64() * 2 * math.Pi,
120+ Radius: r.Range(config.Galaxy.PlanetRadius.Min, config.Galaxy.PlanetRadius.Max),
121+ }
122+ counts["planet"]++
123+ p.orbitAround(star)
124+ g.add(p)
125+ }
126+ }
127+ if r.Chance(config.Galaxy.Extras.AsteroidChance * fade) {
128+ p := g.orbitPOI(kindAsteroid, "asteroid", star, counts, r)
129+ p.Ore = config.Cargo.FieldOre
130+ p.Radius = 260
131+ }
132+ if r.Chance(config.Galaxy.Extras.CommsChance * fade) {
133+ p := g.orbitPOI(kindComms, "comms", star, counts, r)
134+ p.Radius = 120
135+ p.Linked = map[string]bool{}
136+ }
137+ if r.Chance(config.Galaxy.Extras.ShipyardChance * fade) {
138+ p := g.orbitPOI(kindShipyard, "shipyard", star, counts, r)
139+ p.Radius = 180
140+ }
141+ if r.Chance(config.Galaxy.Extras.WreckChance * fade) {
142+ p := g.orbitPOI(kindWreck, "wreck", star, counts, r)
143+ p.Radius = 160
144+ p.Wreck = randomWreckPieces(r, config.Cargo.WreckPieces)
145+ }
146+ if r.Chance(config.Galaxy.Extras.FleetChance * fade) {
147+ p := g.orbitPOI(kindFleet, "fleet", star, counts, r)
148+ p.Radius = 0
149+ p.Hostile = r.Chance(0.45 + 0.35*density)
150+ p.FleetCap = config.NPC.MinFleetSize + r.Intn(config.NPC.MaxFleetSize-config.NPC.MinFleetSize+1)
151+ }
152+ }
153+
154+ g.homeSystem()
155+ return g
156+}
157+
158+func (g *Galaxy) orbitPOI(kind, prefix string, star *POI, counts map[string]int, r *rng) *POI {
159+ p := &POI{
160+ ID: fmt.Sprintf("%s:%d", prefix, counts[prefix]),
161+ Kind: kind,
162+ Star: star.ID,
163+ Orbit: r.Range(config.Galaxy.Planets.OrbitMin, config.Galaxy.Planets.OrbitMax),
164+ Angle: r.Float64() * 2 * math.Pi,
165+ Radius: 100,
166+ }
167+ counts[prefix]++
168+ p.orbitAround(star)
169+ return g.add(p)
170+}
171+
172+// homeSystem picks the star closest to the core and guarantees a shipyard so
173+// new players have somewhere to spawn and refuel.
174+func (g *Galaxy) homeSystem() {
175+ var best *POI
176+ bestD := math.Inf(1)
177+ for _, s := range g.Stars {
178+ d := Vec2{s.X, s.Y}.Len()
179+ if d < bestD {
180+ bestD, best = d, s
181+ }
182+ }
183+ g.Home = best
184+ for _, p := range g.POIs {
185+ if p.Kind == kindShipyard && p.Star == best.ID {
186+ return
187+ }
188+ }
189+ y := &POI{
190+ ID: fmt.Sprintf("shipyard:home"),
191+ Kind: kindShipyard,
192+ Star: best.ID,
193+ Orbit: 900,
194+ Angle: 0,
195+ Radius: 180,
196+ }
197+ y.orbitAround(best)
198+ g.add(y)
199+}
200+
201+// spawnPos returns a position in orbit around the home shipyard, offset
202+// outward from the star so a fresh ship never spawns inside it.
203+func (g *Galaxy) spawnPos() (Vec2, string) {
204+ for _, p := range g.POIs {
205+ if p.Kind == kindShipyard && p.Star == g.Home.ID {
206+ off := Vec2{p.X - g.Home.X, p.Y - g.Home.Y}
207+ if off.Len() == 0 {
208+ off = Vec2{1, 0}
209+ }
210+ dir := off.Norm()
211+ d := config.Galaxy.OrbitRange * 0.8
212+ return Vec2{p.X + dir.X*d, p.Y + dir.Y*d}, p.ID
213+ }
214+ }
215+ return Vec2{g.Home.X + config.Galaxy.OrbitRange, g.Home.Y}, g.Home.ID
216+}
217+
218+func randomWreckPieces(r *rng, n int) []*Piece {
219+ out := make([]*Piece, 0, n)
220+ for i := 0; i < n; i++ {
221+ out = append(out, newPiece(i, allShapes[r.Intn(len(allShapes))], 1+r.Intn(2)))
222+ }
223+ return out
224+}
225+
226+// starAt returns the star whose disc contains pos, if any (collision check).
227+func (g *Galaxy) starAt(pos Vec2, pad float64) *POI {
228+ for _, s := range g.Stars {
229+ if pos.Dist(Vec2{s.X, s.Y}) < s.Radius+pad {
230+ return s
231+ }
232+ }
233+ return nil
234+}
235+
236+// nearby returns POIs within range of pos (linear scan; galaxy is static).
237+func (g *Galaxy) nearby(pos Vec2, rng float64) []*POI {
238+ var out []*POI
239+ r2 := rng * rng
240+ for _, p := range g.POIs {
241+ dx := p.X - pos.X
242+ dy := p.Y - pos.Y
243+ if dx*dx+dy*dy <= r2 {
244+ out = append(out, p)
245+ }
246+ }
247+ return out
248+}
@@ -0,0 +1,20 @@
1+module space-browser/server
2+
3+go 1.27
4+
5+require (
6+ github.com/gorilla/websocket v1.5.3
7+ modernc.org/sqlite v1.60.1
8+)
9+
10+require (
11+ github.com/dustin/go-humanize v1.0.1 // indirect
12+ github.com/google/uuid v1.6.0 // indirect
13+ github.com/mattn/go-isatty v0.0.24 // indirect
14+ github.com/ncruces/go-strftime v1.0.0 // indirect
15+ github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
16+ golang.org/x/sys v0.48.0 // indirect
17+ modernc.org/libc v1.77.1 // indirect
18+ modernc.org/mathutil v1.7.1 // indirect
19+ modernc.org/memory v1.12.1 // indirect
20+)
@@ -0,0 +1,52 @@
1+github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
2+github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
3+github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3 h1:LMLX+LgTNWpfvCBdFebv6EsYotImrt/Ppc5cXIriCSo=
4+github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3/go.mod h1:jl5iWTm0/hd5PjEYEOuwAJ57L/CibdZfrqZ5XA5GrCk=
5+github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
6+github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
7+github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
8+github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
9+github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
10+github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
11+github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI=
12+github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A=
13+github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=
14+github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
15+github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
16+github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
17+golang.org/x/mod v0.41.0 h1:qJmnOUb4YB+FsEuM3HcWucdZASCPGhsX6uljO6pog0c=
18+golang.org/x/mod v0.41.0/go.mod h1:Ek9pY8RKWXwsWvd3rQiHYtMqkjSUV+s1Rj7j4H5Ur6o=
19+golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk=
20+golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
21+golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo=
22+golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
23+golang.org/x/tools v0.50.0 h1:c2ifzfcuY7L90lZ2aKd8S4K2NpASF08SZx9ZuJkHmSU=
24+golang.org/x/tools v0.50.0/go.mod h1:7ulVMw3831Mwi5EZD6RomGyffr4VFjuNYXf2BbCEAV0=
25+modernc.org/cc/v4 v4.29.7 h1:q+NXGJ0bK3b4TXFYQQVr9pYETGnmwFWkrUzJnMya/Tg=
26+modernc.org/cc/v4 v4.29.7/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI=
27+modernc.org/ccgo/v4 v4.36.1 h1:ZNIUZAryN0UgnJwtyxrdEzcFc3yD4Cu4AzjfPXsLsIE=
28+modernc.org/ccgo/v4 v4.36.1/go.mod h1:rrtGc2QkS239nYb/mQNuBMyjq3/y3ZXWbBjPoV3wqzA=
29+modernc.org/fileutil v1.4.0 h1:j6ZzNTftVS054gi281TyLjHPp6CPHr2KCxEXjEbD6SM=
30+modernc.org/fileutil v1.4.0/go.mod h1:EqdKFDxiByqxLk8ozOxObDSfcVOv/54xDs/DUHdvCUU=
31+modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI=
32+modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito=
33+modernc.org/gc/v3 v3.1.5 h1:21ldfPfRYE31Tb7B3mwAK8gy1AxP4+dKjrOQPfqakoc=
34+modernc.org/gc/v3 v3.1.5/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY=
35+modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks=
36+modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI=
37+modernc.org/libc v1.77.1 h1:Ct8j47QtiZ1Enj2DtFXQtUqrPCAjdCmPjtCuvrYQ0Hs=
38+modernc.org/libc v1.77.1/go.mod h1:87/pZ4L6nD1zqW4nItuS12YO7hN1igAah34xjnQo/W0=
39+modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
40+modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
41+modernc.org/memory v1.12.1 h1:nFMiWrpStgZczNl6XI9GnIk/rWhYIyHGUaR04pGbp9g=
42+modernc.org/memory v1.12.1/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
43+modernc.org/opt v0.2.0 h1:tGyef5ApycA7FSEOMraay9SaTk5zmbx7Tu+cJs4QKZg=
44+modernc.org/opt v0.2.0/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns=
45+modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w=
46+modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE=
47+modernc.org/sqlite v1.60.1 h1:/blz53O951KWFOso4QQvEs/Fq6cDBKLtMVrYNSeJVKw=
48+modernc.org/sqlite v1.60.1/go.mod h1:1dIoEagfDE72QytD5scH1lxARtaUgKgHC/NuApA27r0=
49+modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0=
50+modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A=
51+modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=
52+modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM=
@@ -0,0 +1,90 @@
1+package main
2+
3+import (
4+ "flag"
5+ "log"
6+ "net/http"
Cut short: this commit's diff is over 1000 lines.
Cut short: this commit's diff is over 1000 lines.
Cut short: this commit's diff is over 1000 lines.
Cut short: this commit's diff is over 1000 lines.
Cut short: this commit's diff is over 1000 lines.
Cut short: this commit's diff is over 1000 lines.
Cut short: this commit's diff is over 1000 lines.
Cut short: this commit's diff is over 1000 lines.
Cut short: this commit's diff is over 1000 lines.
Cut short: this commit's diff is over 1000 lines.