summaryrefslogtreecommitdiff
path: root/server/server.lua
blob: 1c637bc3f0643f3585e4a45aefd1653e0047c3da (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
local enet = require"enet"
local json = require"common.dkjson"
local chunk = require"common.chunk"
local noise = require"noise"
local coords = require"common.coords"
local Pos = coords.Pos
local worldgen = require"worldgen"
local MapS = require"map".MapS
local Player=require'player'.Player
local posix_time = require"posix.time"
local posix_signal = require"posix.signal"
local db = require'db'

math.randomseed(os.time())

local host = enet.host_create("*:8473",nil,2)
print(host:get_socket_address())

-- sequential list of all players
local playerlist = {}

local function player_by_id(id)
	for i,pl in ipairs(playerlist) do
		if pl.id == id then return pl, i end
	end
	return nil
end
local function player_by_peer(peer)
	for i,pl in ipairs(playerlist) do
		if pl.peer == peer then return pl, i end
	end
	return nil
end


local function player_join_packet(player)
	return json.encode{t="join",pl=player:info_part()}
end
local function player_you_packet(player)
	return json.encode{t="you",pl=player:info_part()}
end
local function player_leave_packet(player)
	return json.encode{t="leave",id=player.id}
end
local function player_move_packet(player,x,y)
	return json.encode{t="move",id=player.id,x=x,y=y}
end
local function chat_packet(msg)
	return json.encode{t="chat",msg=msg}
end
local function settile_packet(h,tile)
	return json.encode{t='settile',q=h.q,r=h.r,tile=tile}
end
local function give_packet(tile)
	return json.encode{t='give',tile=tile}
end

local map = MapS:make()





-- set of peers currently within handshake procedure
local connecting_peers = {}

local function create_player(...)
	-- advances connecting peer to player
	local player = Player:make(...)
	table.insert(playerlist, player)

	connecting_peers[player.peer] = nil

	player.peer:send(player_you_packet(player))

	for i,otherplayer in ipairs(playerlist) do
		if otherplayer ~= player then
			player.peer:send(player_join_packet(otherplayer))
			otherplayer.peer:send(player_join_packet(player))
			otherplayer.peer:send(
				chat_packet(player.username .. " joined"))
		end
	end

	print("connect",player.id,player.peer)
end

local function connecting_peer_ev()
	local ev = coroutine.yield()
	print("hello")
	local j = json.decode(ev.data)
	local op = j.t
	if op == "handshake" then
		print(ev,'handshake; username',j.username)
		create_player(ev.peer,j.username)
	else
		error("weird handshake: "..op)
	end
end


local function on_peer_connect(peer)
	print("peer connect: ",peer)
	local co = coroutine.create(connecting_peer_ev)
	assert(coroutine.resume(co))
	connecting_peers[peer] = co
end


local function on_peer_disconnect(peer)
	print("peer disconnect: ",peer)
	connecting_peers[peer] = nil
	local player,idx = player_by_peer(peer)
	if player then
		table.remove(playerlist, idx)
		for i,otherplayer in ipairs(playerlist) do
			otherplayer.peer:send(player_leave_packet(player))
			otherplayer.peer:send(chat_packet(player.username..' left'))
		end
		print("disconnect", player.id, player.peer)
	end
end

local function handle_player_packet(player,ev)
	local j = json.decode(ev.data)
	-- print(ev.channel,ev.data)
	local op = j.t
	if op == "ppos" then
		local x,y = j.x,j.y
		player.pos = coords.Pos:make(x,y)
		-- print(player.id,"-->",player.pos[1],player.pos[2])
		for i,otherplayer in ipairs(playerlist) do
			if otherplayer ~= player then
				otherplayer.peer:send(player_move_packet(player,x,y),1)
			end
		end
	elseif op == "settile" then
		local h = coords.Hex:make(j.q,j.r)
		local old_tile = map:at(h)
		local new_tile = j.tile
		local inv = player.inv

		if old_tile == 0 then
			local nc = inv[new_tile] or 0
			if nc <= 0 then
				print("nooo")
				player.peer:send(settile_packet(h,old_tile))
				return
			end
			inv[new_tile] = nc - 1
		elseif new_tile == 0 then
			inv[old_tile] = (inv[old_tile] or 0) + 1
			player.peer:send(give_packet(old_tile))
		else
			-- can't replace one tile with another
			print("nooooo")
			player.peer:send(settile_packet(h,old_tile))
			return
		end

		print('settile', player.username, inv[old_tile], inv[new_tile])

		map:set_at(h, new_tile)
		
		for i,otherplayer in ipairs(playerlist) do
			if otherplayer ~= player then
				-- same packet structure s2c as c2s
				-- when multiple chunks exist and players only get info
				-- about stuff near to them, that won't be the case any more
				otherplayer.peer:send(ev.data)
			end
		end
	elseif op == "reqchunk" then
		-- i am not certain this is the best way for this to work
		-- i might change it later
		local cp = coords.ChunkPos:make(j.u,j.v)
		local ch = map:obtain(cp)
		player.peer:send(ch:data_packet())
	elseif op == "chat" then
		print("chat ["..player.id.."] "..j.msg)
		for i,otherplayer in ipairs(playerlist) do
			otherplayer.peer:send(
				chat_packet('['..player.username..'] '..j.msg))
		end
	end
end

local function handle_ev(ev)
	if ev.type == 'connect' then
		on_peer_connect(ev.peer)
	elseif ev.type == 'disconnect' then
		on_peer_disconnect(ev.peer)
	elseif ev.type == 'receive' then
		-- print("recv:",ev.peer,ev.data)
		if connecting_peers[ev.peer] then
			local co = connecting_peers[ev.peer]
			print("\t-> hshake",co,coroutine.status(co))
			local ok,err = coroutine.resume(co, ev)
			if not ok then
				print("hshake error: ",ev.peer,err)
				connecting_peers[ev.peer] = nil
				ev.peer:disconnect_now()
			end
		else
			local player = player_by_peer(ev.peer)
			if not player then error("packet from unknown peer ",ev.peer) end
			-- print("\t-> player",player)
			handle_player_packet(player, ev)
		end
	end
end

local function timenow()
	-- monotonic clock, guaranteed to never go backwards
	local tv = posix_time.clock_gettime(posix_time.CLOCK_MONOTONIC)
	-- this discards some precision but i don't care
	return tv.tv_sec + (tv.tv_nsec/1000000000)
end

local tick_interval = 1 -- seconds
local last_tick_time = timenow()


local function player_near_chunk(cp)
	-- true: chunk at cp should stay loaded (because of a nearby player),
	-- false: no players nearby, can be unloaded
	-- this is maybe not as efficient as it possibly could be
	for _,player in ipairs(playerlist) do
		local pcp = player.pos:to_hex():containing_chunk()
		for _,neighb in ipairs(pcp:neighborhood()) do
			if neighb == cp then
				return true
			end
		end
	end
	return false
end

local function save_things()
	local txn = db.txn(true)
	for cp,ch in map:iter_chunks() do
		map:save_chunk(cp,txn)
		if not player_near_chunk(cp) then
			-- print("unloading chunk",cp)
			map:remove_chunk(cp)
		end
	end
	txn:commit()
end

local function tick(ntick)
	if ntick % 30 == 0 then
		-- print("saving things")
		save_things()
	end
end

local stopping=false

posix_signal.signal(posix_signal.SIGINT, function() stopping=true end)

local ntick = 0

while true do
	if stopping then
		print("stopping...")
		save_things()
		break
	end

	local now = timenow()
	local dt = now - last_tick_time
	local time_till_next_tick = (last_tick_time+tick_interval)-now
	if time_till_next_tick > 0.001 then
		local ev = host:service(time_till_next_tick*1000)
		if ev then handle_ev(ev) end
	else
		last_tick_time = now
		ntick = ntick + 1
		tick(ntick)
	end
end