xonecas.ioDon't click! Sean Caetano Martin Sign in
space-browser / server / main.go 122 lines3.1 kB Raw
1// The server owns everything a client draws: celestial bodies, ships, hulls and
2// loose pieces. Clients send intents (pick, drag, drop) and render the state
3// they are handed.
4
5package main
6
7import (
8	"encoding/json"
9	"flag"
10	"log"
11	"math"
12	"net/http"
13	"strconv"
14
15	"github.com/gorilla/websocket"
16)
17
18var upgrader = websocket.Upgrader{CheckOrigin: func(*http.Request) bool { return true }}
19
20var addr = flag.String("addr", ":8090", "listen address")
21
22func main() {
23	flag.Parse()
24	h := newHub()
25	go h.tick()
26	http.HandleFunc("/ws", h.handle)
27	http.HandleFunc("/debug/state", h.debugState)
28	log.Fatal(http.ListenAndServe(*addr, nil))
29}
30
31func newHub() *hub {
32	h := &hub{clients: map[*client]bool{}, loose: []*loose{}, ore: []*ore{}}
33	// Empty, not nil: a nil slice marshals as null, and the client walks these.
34	h.galaxy() // ten star systems, drawn fresh on every boot: there is no seed
35	// Place the bodies before anything is born around them, then fill every yard
36	// with its passive AI traffic. A run starts at any yard near the middle, so new
37	// ships spread over the inner systems instead of stacking on one ring.
38	for _, b := range h.bodies {
39		b.place(0)
40		if b.Kind != "shipyard" {
41			continue
42		}
43		if math.Hypot(b.cx, b.cy) < rimRing {
44			h.spawns = append(h.spawns, b.ID)
45		}
46		for i := 0; i < aiPerYard; i++ {
47			h.ai = append(h.ai, h.spawnAI(b))
48		}
49	}
50	h.rogues() // the gaps between the stars, after the systems are where they are
51	log.Printf("galaxy: %d systems, %d bodies", 1+midCount+rimCount, len(h.bodies))
52	return h
53}
54
55func (h *hub) handle(w http.ResponseWriter, r *http.Request) {
56	ws, err := upgrader.Upgrade(w, r, nil)
57	if err != nil {
58		return
59	}
60	h.mu.Lock()
61	h.nextID++
62	c := &client{ws: ws, p: &player{ID: h.nextID}}
63	c.p.Name = "P" + strconv.Itoa(c.p.ID)
64	c.p.Pieces = []piece{h.fitted("triangle", 0)} // every run starts from one triangle
65	c.p.FuelMax = c.p.capacity()
66	c.p.Fuel = c.p.FuelMax
67	h.deploy(c.p)
68	h.clients[c] = true
69	h.mu.Unlock()
70
71	for {
72		_, msg, err := ws.ReadMessage()
73		if err != nil {
74			break
75		}
76		var in struct {
77			T string   `json:"t"`
78			X *float64 `json:"x"`
79			Y *float64 `json:"y"`
80		}
81		if json.Unmarshal(msg, &in) != nil {
82			continue
83		}
84		if in.X == nil || in.Y == nil || !finite(*in.X) || !finite(*in.Y) {
85			continue
86		}
87		if math.Abs(*in.X) > reach || math.Abs(*in.Y) > reach {
88			continue
89		}
90		h.mu.Lock()
91		switch in.T {
92		case "pick":
93			h.pick(c.p, *in.X, *in.Y)
94		case "drag":
95			h.drag(c.p, *in.X, *in.Y)
96		case "drop":
97			h.drop(c.p, *in.X, *in.Y)
98		}
99		h.mu.Unlock()
100	}
101
102	h.mu.Lock()
103	delete(h.clients, c)
104	h.forgive(c.p.ID)
105	h.abandon(c.p)
106	h.mu.Unlock()
107	ws.Close()
108}
109
110// The same state the websocket pushes, for a test that only needs to look: no
111// client, so you and held are zero. The socket stays the only way to act.
112func (h *hub) debugState(w http.ResponseWriter, r *http.Request) {
113	h.mu.Lock()
114	b, err := json.Marshal(state{T: "state", Bodies: h.bodies, Systems: h.systems, Loose: h.loose, Ore: h.ore, Shots: h.shots, Players: h.players()})
115	h.mu.Unlock()
116	if err != nil {
117		http.Error(w, err.Error(), http.StatusInternalServerError)
118		return
119	}
120	w.Header().Set("Content-Type", "application/json")
121	w.Write(b)
122}