]> git.lizzy.rs Git - minetest.git/blob - src/server.h
fixing
[minetest.git] / src / server.h
1 /*
2 Minetest-c55
3 Copyright (C) 2010 celeron55, Perttu Ahola <celeron55@gmail.com>
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 /*
21 (c) 2010 Perttu Ahola <celeron55@gmail.com>
22 */
23
24 #ifndef SERVER_HEADER
25 #define SERVER_HEADER
26
27 #include "connection.h"
28 #include "environment.h"
29 #include "common_irrlicht.h"
30 #include <string>
31 #include "utility.h"
32 #include "porting.h"
33 #include "map.h"
34 #include "inventory.h"
35
36 struct QueuedBlockEmerge
37 {
38         v3s16 pos;
39         // key = peer_id, value = flags
40         core::map<u16, u8> peer_ids;
41 };
42
43 /*
44         This is a thread-safe class.
45 */
46 class BlockEmergeQueue
47 {
48 public:
49         BlockEmergeQueue()
50         {
51                 m_mutex.Init();
52         }
53
54         ~BlockEmergeQueue()
55         {
56                 JMutexAutoLock lock(m_mutex);
57
58                 core::list<QueuedBlockEmerge*>::Iterator i;
59                 for(i=m_queue.begin(); i!=m_queue.end(); i++)
60                 {
61                         QueuedBlockEmerge *q = *i;
62                         delete q;
63                 }
64         }
65         
66         /*
67                 peer_id=0 adds with nobody to send to
68         */
69         void addBlock(u16 peer_id, v3s16 pos, u8 flags)
70         {
71                 DSTACK(__FUNCTION_NAME);
72         
73                 JMutexAutoLock lock(m_mutex);
74
75                 if(peer_id != 0)
76                 {
77                         /*
78                                 Find if block is already in queue.
79                                 If it is, update the peer to it and quit.
80                         */
81                         core::list<QueuedBlockEmerge*>::Iterator i;
82                         for(i=m_queue.begin(); i!=m_queue.end(); i++)
83                         {
84                                 QueuedBlockEmerge *q = *i;
85                                 if(q->pos == pos)
86                                 {
87                                         q->peer_ids[peer_id] = flags;
88                                         return;
89                                 }
90                         }
91                 }
92                 
93                 /*
94                         Add the block
95                 */
96                 QueuedBlockEmerge *q = new QueuedBlockEmerge;
97                 q->pos = pos;
98                 if(peer_id != 0)
99                         q->peer_ids[peer_id] = flags;
100                 m_queue.push_back(q);
101         }
102
103         // Returned pointer must be deleted
104         // Returns NULL if queue is empty
105         QueuedBlockEmerge * pop()
106         {
107                 JMutexAutoLock lock(m_mutex);
108
109                 core::list<QueuedBlockEmerge*>::Iterator i = m_queue.begin();
110                 if(i == m_queue.end())
111                         return NULL;
112                 QueuedBlockEmerge *q = *i;
113                 m_queue.erase(i);
114                 return q;
115         }
116
117         u32 size()
118         {
119                 JMutexAutoLock lock(m_mutex);
120                 return m_queue.size();
121         }
122         
123         u32 peerItemCount(u16 peer_id)
124         {
125                 JMutexAutoLock lock(m_mutex);
126
127                 u32 count = 0;
128
129                 core::list<QueuedBlockEmerge*>::Iterator i;
130                 for(i=m_queue.begin(); i!=m_queue.end(); i++)
131                 {
132                         QueuedBlockEmerge *q = *i;
133                         if(q->peer_ids.find(peer_id) != NULL)
134                                 count++;
135                 }
136
137                 return count;
138         }
139
140 private:
141         core::list<QueuedBlockEmerge*> m_queue;
142         JMutex m_mutex;
143 };
144
145 class Server;
146
147 class ServerThread : public SimpleThread
148 {
149         Server *m_server;
150
151 public:
152
153         ServerThread(Server *server):
154                 SimpleThread(),
155                 m_server(server)
156         {
157         }
158
159         void * Thread();
160 };
161
162 class EmergeThread : public SimpleThread
163 {
164         Server *m_server;
165
166 public:
167
168         EmergeThread(Server *server):
169                 SimpleThread(),
170                 m_server(server)
171         {
172         }
173
174         void * Thread();
175
176         void trigger()
177         {
178                 setRun(true);
179                 if(IsRunning() == false)
180                 {
181                         Start();
182                 }
183         }
184 };
185
186 struct PlayerInfo
187 {
188         u16 id;
189         char name[PLAYERNAME_SIZE];
190         v3f position;
191         Address address;
192         float avg_rtt;
193
194         PlayerInfo();
195         void PrintLine(std::ostream *s);
196 };
197
198 u32 PIChecksum(core::list<PlayerInfo> &l);
199
200 /*
201         Used for queueing and sorting block transfers in containers
202         
203         Lower priority number means higher priority.
204 */
205 struct PrioritySortedBlockTransfer
206 {
207         PrioritySortedBlockTransfer(float a_priority, v3s16 a_pos, u16 a_peer_id)
208         {
209                 priority = a_priority;
210                 pos = a_pos;
211                 peer_id = a_peer_id;
212         }
213         bool operator < (PrioritySortedBlockTransfer &other)
214         {
215                 return priority < other.priority;
216         }
217         float priority;
218         v3s16 pos;
219         u16 peer_id;
220 };
221
222 class RemoteClient
223 {
224 public:
225         // peer_id=0 means this client has no associated peer
226         // NOTE: If client is made allowed to exist while peer doesn't,
227         //       this has to be set to 0 when there is no peer.
228         //       Also, the client must be moved to some other container.
229         u16 peer_id;
230         // The serialization version to use with the client
231         u8 serialization_version;
232         // Version is stored in here after INIT before INIT2
233         u8 pending_serialization_version;
234
235         RemoteClient():
236                 m_time_from_building(9999),
237                 m_excess_gotblocks(0)
238         {
239                 peer_id = 0;
240                 serialization_version = SER_FMT_VER_INVALID;
241                 pending_serialization_version = SER_FMT_VER_INVALID;
242                 m_nearest_unsent_d = 0;
243                 m_nearest_unsent_reset_timer = 0.0;
244         }
245         ~RemoteClient()
246         {
247         }
248         
249         /*
250                 Finds block that should be sent next to the client.
251                 Environment should be locked when this is called.
252                 dtime is used for resetting send radius at slow interval
253         */
254         void GetNextBlocks(Server *server, float dtime,
255                         core::array<PrioritySortedBlockTransfer> &dest);
256
257         /*
258                 Connection and environment should be locked when this is called.
259                 steps() objects of blocks not found in active_blocks, then
260                 adds those blocks to active_blocks
261         */
262         void SendObjectData(
263                         Server *server,
264                         float dtime,
265                         core::map<v3s16, bool> &stepped_blocks
266                 );
267
268         void GotBlock(v3s16 p);
269
270         void SentBlock(v3s16 p);
271
272         void SetBlockNotSent(v3s16 p);
273         void SetBlocksNotSent(core::map<v3s16, MapBlock*> &blocks);
274
275         s32 SendingCount()
276         {
277                 return m_blocks_sending.size();
278         }
279         
280         // Increments timeouts and removes timed-out blocks from list
281         // NOTE: This doesn't fix the server-not-sending-block bug
282         //       because it is related to emerging, not sending.
283         //void RunSendingTimeouts(float dtime, float timeout);
284
285         void PrintInfo(std::ostream &o)
286         {
287                 o<<"RemoteClient "<<peer_id<<": "
288                                 <<"m_blocks_sent.size()="<<m_blocks_sent.size()
289                                 <<", m_blocks_sending.size()="<<m_blocks_sending.size()
290                                 <<", m_nearest_unsent_d="<<m_nearest_unsent_d
291                                 <<", m_excess_gotblocks="<<m_excess_gotblocks
292                                 <<std::endl;
293                 m_excess_gotblocks = 0;
294         }
295
296         // Time from last placing or removing blocks
297         float m_time_from_building;
298         
299         /*JMutex m_dig_mutex;
300         float m_dig_time_remaining;
301         // -1 = not digging
302         s16 m_dig_tool_item;
303         v3s16 m_dig_position;*/
304         
305         /*
306                 List of active objects that the client knows of.
307                 Value is dummy.
308         */
309         core::map<u16, bool> m_known_objects;
310
311 private:
312         /*
313                 Blocks that have been sent to client.
314                 - These don't have to be sent again.
315                 - A block is cleared from here when client says it has
316                   deleted it from it's memory
317                 
318                 Key is position, value is dummy.
319                 No MapBlock* is stored here because the blocks can get deleted.
320         */
321         core::map<v3s16, bool> m_blocks_sent;
322         s16 m_nearest_unsent_d;
323         v3s16 m_last_center;
324         float m_nearest_unsent_reset_timer;
325         
326         /*
327                 Blocks that are currently on the line.
328                 This is used for throttling the sending of blocks.
329                 - The size of this list is limited to some value
330                 Block is added when it is sent with BLOCKDATA.
331                 Block is removed when GOTBLOCKS is received.
332                 Value is time from sending. (not used at the moment)
333         */
334         core::map<v3s16, float> m_blocks_sending;
335
336         /*
337                 Count of excess GotBlocks().
338                 There is an excess amount because the client sometimes
339                 gets a block so late that the server sends it again,
340                 and the client then sends two GOTBLOCKs.
341                 This is resetted by PrintInfo()
342         */
343         u32 m_excess_gotblocks;
344 };
345
346 class Server : public con::PeerHandler, public MapEventReceiver,
347                 public InventoryManager
348 {
349 public:
350         /*
351                 NOTE: Every public method should be thread-safe
352         */
353
354         Server(
355                 std::string mapsavedir
356         );
357         ~Server();
358         void start(unsigned short port);
359         void stop();
360         // This is mainly a way to pass the time to the server.
361         // Actual processing is done in an another thread.
362         void step(float dtime);
363         // This is run by ServerThread and does the actual processing
364         void AsyncRunStep();
365         void Receive();
366         void ProcessData(u8 *data, u32 datasize, u16 peer_id);
367
368         core::list<PlayerInfo> getPlayerInfo();
369
370         u32 getDayNightRatio()
371         {
372                 return time_to_daynight_ratio(m_time_of_day.get());
373         }
374
375         bool getShutdownRequested()
376         {
377                 return m_shutdown_requested.get();
378         }
379         
380         /*
381                 Shall be called with the environment locked.
382                 This is accessed by the map, which is inside the environment,
383                 so it shouldn't be a problem.
384         */
385         void onMapEditEvent(MapEditEvent *event);
386
387         /*
388                 Shall be called with the environment and the connection locked.
389         */
390         Inventory* getInventory(InventoryContext *c, std::string id);
391         void inventoryModified(InventoryContext *c, std::string id);
392
393 private:
394
395         // Virtual methods from con::PeerHandler.
396         // As of now, these create and remove clients and players.
397         void peerAdded(con::Peer *peer);
398         void deletingPeer(con::Peer *peer, bool timeout);
399         
400         // Envlock and conlock should be locked when calling these
401         void SendObjectData(float dtime);
402         void SendPlayerInfos();
403         void SendInventory(u16 peer_id);
404         void SendChatMessage(u16 peer_id, const std::wstring &message);
405         void BroadcastChatMessage(const std::wstring &message);
406         /*
407                 Send a node removal/addition event to all clients except ignore_id.
408                 Additionally, if far_players!=NULL, players further away than
409                 far_d_nodes are ignored and their peer_ids are added to far_players
410         */
411         void sendRemoveNode(v3s16 p, u16 ignore_id=0,
412                         core::list<u16> *far_players=NULL, float far_d_nodes=100);
413         void sendAddNode(v3s16 p, MapNode n, u16 ignore_id=0,
414                         core::list<u16> *far_players=NULL, float far_d_nodes=100);
415         
416         // Environment and Connection must be locked when  called
417         void SendBlockNoLock(u16 peer_id, MapBlock *block, u8 ver);
418         
419         // Sends blocks to clients
420         void SendBlocks(float dtime);
421         
422         // When called, connection mutex should be locked
423         RemoteClient* getClient(u16 peer_id);
424         
425         // Connection must be locked when called
426         std::wstring getStatusString();
427         
428         /*
429                 Get a player from memory or creates one.
430                 If player is already connected, return NULL
431
432                 Call with env and con locked.
433         */
434         Player *emergePlayer(const char *name, const char *password,
435                         u16 peer_id);
436
437         /*
438                 Update water pressure.
439                 This also adds suitable nodes to active_nodes.
440
441                 environment has to be locked when calling.
442         */
443         /*void UpdateBlockWaterPressure(MapBlock *block,
444                         core::map<v3s16, MapBlock*> &modified_blocks);*/
445         
446         // Locks environment and connection by its own
447         struct PeerChange;
448         void handlePeerChange(PeerChange &c);
449         void handlePeerChanges();
450         
451         //float m_flowwater_timer;
452         float m_liquid_transform_timer;
453         float m_print_info_timer;
454         float m_objectdata_timer;
455         float m_emergethread_trigger_timer;
456         float m_savemap_timer;
457         
458         // NOTE: If connection and environment are both to be locked,
459         // environment shall be locked first.
460         JMutex m_env_mutex;
461         ServerEnvironment m_env;
462
463         JMutex m_con_mutex;
464         con::Connection m_con;
465         core::map<u16, RemoteClient*> m_clients; // Behind the con mutex
466
467         float m_step_dtime;
468         JMutex m_step_dtime_mutex;
469
470         ServerThread m_thread;
471         EmergeThread m_emergethread;
472
473         BlockEmergeQueue m_emerge_queue;
474         
475         // Nodes that are destinations of flowing liquid at the moment
476         //core::map<v3s16, u8> m_flow_active_nodes;
477
478         // 0-23999
479         MutexedVariable<u32> m_time_of_day;
480         // Used to buffer dtime for adding to m_time_of_day
481         float m_time_counter;
482         float m_time_of_day_send_timer;
483         
484         MutexedVariable<double> m_uptime;
485         
486         enum PeerChangeType
487         {
488                 PEER_ADDED,
489                 PEER_REMOVED
490         };
491
492         struct PeerChange
493         {
494                 PeerChangeType type;
495                 u16 peer_id;
496                 bool timeout;
497         };
498         
499         Queue<PeerChange> m_peer_change_queue;
500
501         std::string m_mapsavedir;
502
503         MutexedVariable<bool> m_shutdown_requested;
504         
505         /*
506                 Queue of map edits from the environment for sending to the clients
507                 This is behind m_env_mutex
508         */
509         Queue<MapEditEvent*> m_unsent_map_edit_queue;
510         /*
511                 Set to true when the server itself is modifying the map and does
512                 all sending of information by itself.
513                 This is behind m_env_mutex
514         */
515         bool m_ignore_map_edit_events;
516         /*
517                 If set to !=0, the incoming MapEditEvents are modified to have
518                 this peed id as the disabled recipient
519                 This is behind m_env_mutex
520         */
521         u16 m_ignore_map_edit_events_peer_id;
522
523         friend class EmergeThread;
524         friend class RemoteClient;
525 };
526
527 /*
528         Runs a simple dedicated server loop.
529
530         Shuts down when run is set to false.
531 */
532 void dedicated_server_loop(Server &server, bool &run);
533
534 #endif
535