129d3f861a84e534f978ca4f3bebc1a1920d1605
[oweals/minetest.git] / src / clientiface.h
1 /*
2 Minetest
3 Copyright (C) 2010-2014 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 Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser 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 #ifndef _CLIENTIFACE_H_
20 #define _CLIENTIFACE_H_
21
22 #include "irr_v3d.h"                   // for irrlicht datatypes
23
24 #include "constants.h"
25 #include "serialization.h"             // for SER_FMT_VER_INVALID
26 #include "jthread/jmutex.h"
27 #include "network/networkpacket.h"
28
29 #include <list>
30 #include <vector>
31 #include <map>
32 #include <set>
33
34 class MapBlock;
35 class ServerEnvironment;
36 class EmergeManager;
37
38 /*
39  * State Transitions
40
41       Start
42   (peer connect)
43         |
44         v
45       /-----------------\
46       |                 |
47       |    Created      |
48       |                 |
49       \-----------------/
50                |
51                |
52 +-----------------------------+            invalid playername, password
53 |IN:                          |                    or denied by mod
54 | TOSERVER_INIT               |------------------------------
55 +-----------------------------+                             |
56                |                                            |
57                | Auth ok                                    |
58                |                                            |
59 +-----------------------------+                             |
60 |OUT:                         |                             |
61 | TOCLIENT_INIT               |                             |
62 +-----------------------------+                             |
63                |                                            |
64                v                                            |
65       /-----------------\                                   |
66       |                 |                                   |
67       |    InitSent     |                                   |
68       |                 |                                   |
69       \-----------------/                                   +------------------
70                |                                            |                 |
71 +-----------------------------+             +-----------------------------+   |
72 |IN:                          |             |OUT:                         |   |
73 | TOSERVER_INIT2              |             | TOCLIENT_ACCESS_DENIED      |   |
74 +-----------------------------+             +-----------------------------+   |
75                |                                            |                 |
76                v                                            v                 |
77       /-----------------\                           /-----------------\       |
78       |                 |                           |                 |       |
79       |    InitDone     |                           |     Denied      |       |
80       |                 |                           |                 |       |
81       \-----------------/                           \-----------------/       |
82                |                                                              |
83 +-----------------------------+                                               |
84 |OUT:                         |                                               |
85 | TOCLIENT_MOVEMENT           |                                               |
86 | TOCLIENT_ITEMDEF            |                                               |
87 | TOCLIENT_NODEDEF            |                                               |
88 | TOCLIENT_ANNOUNCE_MEDIA     |                                               |
89 | TOCLIENT_DETACHED_INVENTORY |                                               |
90 | TOCLIENT_TIME_OF_DAY        |                                               |
91 +-----------------------------+                                               |
92                |                                                              |
93                |                                                              |
94                |      -----------------------------------                     |
95                v      |                                 |                     |
96       /-----------------\                               v                     |
97       |                 |                   +-----------------------------+   |
98       | DefinitionsSent |                   |IN:                          |   |
99       |                 |                   | TOSERVER_REQUEST_MEDIA      |   |
100       \-----------------/                   | TOSERVER_RECEIVED_MEDIA     |   |
101                |                            +-----------------------------+   |
102                |      ^                                 |                     |
103                |      -----------------------------------                     |
104                |                                                              |
105 +-----------------------------+                                               |
106 |IN:                          |                                               |
107 | TOSERVER_CLIENT_READY       |                                               |
108 +-----------------------------+                                               |
109                |                                                    async     |
110                v                                                  mod action  |
111 +-----------------------------+                                   (ban,kick)  |
112 |OUT:                         |                                               |
113 | TOCLIENT_MOVE_PLAYER        |                                               |
114 | TOCLIENT_PRIVILEGES         |                                               |
115 | TOCLIENT_INVENTORY_FORMSPEC |                                               |
116 | UpdateCrafting              |                                               |
117 | TOCLIENT_INVENTORY          |                                               |
118 | TOCLIENT_HP (opt)           |                                               |
119 | TOCLIENT_BREATH             |                                               |
120 | TOCLIENT_DEATHSCREEN        |                                               |
121 +-----------------------------+                                               |
122               |                                                               |
123               v                                                               |
124       /-----------------\                                                     |
125       |                 |------------------------------------------------------
126       |     Active      |
127       |                 |----------------------------------
128       \-----------------/      timeout                    |
129                |                            +-----------------------------+
130                |                            |OUT:                         |
131                |                            | TOCLIENT_DISCONNECT         |
132                |                            +-----------------------------+
133                |                                          |
134                |                                          v
135 +-----------------------------+                    /-----------------\
136 |IN:                          |                    |                 |
137 | TOSERVER_DISCONNECT         |------------------->|  Disconnecting  |
138 +-----------------------------+                    |                 |
139                                                    \-----------------/
140 */
141 namespace con {
142         class Connection;
143 }
144
145 #define CI_ARRAYSIZE(a) (sizeof(a) / sizeof((a)[0]))
146
147 enum ClientState
148 {
149         CS_Invalid,
150         CS_Disconnecting,
151         CS_Denied,
152         CS_Created,
153         CS_InitSent,
154         CS_InitDone,
155         CS_DefinitionsSent,
156         CS_Active
157 };
158
159 enum ClientStateEvent
160 {
161         CSE_Init,
162         CSE_GotInit2,
163         CSE_SetDenied,
164         CSE_SetDefinitionsSent,
165         CSE_SetClientReady,
166         CSE_Disconnect
167 };
168
169 /*
170         Used for queueing and sorting block transfers in containers
171
172         Lower priority number means higher priority.
173 */
174 struct PrioritySortedBlockTransfer
175 {
176         PrioritySortedBlockTransfer(float a_priority, v3s16 a_pos, u16 a_peer_id)
177         {
178                 priority = a_priority;
179                 pos = a_pos;
180                 peer_id = a_peer_id;
181         }
182         bool operator < (const PrioritySortedBlockTransfer &other) const
183         {
184                 return priority < other.priority;
185         }
186         float priority;
187         v3s16 pos;
188         u16 peer_id;
189 };
190
191 class RemoteClient
192 {
193 public:
194         // peer_id=0 means this client has no associated peer
195         // NOTE: If client is made allowed to exist while peer doesn't,
196         //       this has to be set to 0 when there is no peer.
197         //       Also, the client must be moved to some other container.
198         u16 peer_id;
199         // The serialization version to use with the client
200         u8 serialization_version;
201         //
202         u16 net_proto_version;
203
204         RemoteClient():
205                 peer_id(PEER_ID_INEXISTENT),
206                 serialization_version(SER_FMT_VER_INVALID),
207                 net_proto_version(0),
208                 m_time_from_building(9999),
209                 m_pending_serialization_version(SER_FMT_VER_INVALID),
210                 m_state(CS_Created),
211                 m_nearest_unsent_d(0),
212                 m_nearest_unsent_reset_timer(0.0),
213                 m_excess_gotblocks(0),
214                 m_nothing_to_send_pause_timer(0.0),
215                 m_name(""),
216                 m_version_major(0),
217                 m_version_minor(0),
218                 m_version_patch(0),
219                 m_full_version("unknown"),
220                 m_connection_time(getTime(PRECISION_SECONDS))
221         {
222         }
223         ~RemoteClient()
224         {
225         }
226
227         /*
228                 Finds block that should be sent next to the client.
229                 Environment should be locked when this is called.
230                 dtime is used for resetting send radius at slow interval
231         */
232         void GetNextBlocks(ServerEnvironment *env, EmergeManager* emerge,
233                         float dtime, std::vector<PrioritySortedBlockTransfer> &dest);
234
235         void GotBlock(v3s16 p);
236
237         void SentBlock(v3s16 p);
238
239         void SetBlockNotSent(v3s16 p);
240         void SetBlocksNotSent(std::map<v3s16, MapBlock*> &blocks);
241
242         /**
243          * tell client about this block being modified right now.
244          * this information is required to requeue the block in case it's "on wire"
245          * while modification is processed by server
246          * @param p position of modified block
247          */
248         void ResendBlockIfOnWire(v3s16 p);
249
250         s32 SendingCount()
251         {
252                 return m_blocks_sending.size();
253         }
254
255         // Increments timeouts and removes timed-out blocks from list
256         // NOTE: This doesn't fix the server-not-sending-block bug
257         //       because it is related to emerging, not sending.
258         //void RunSendingTimeouts(float dtime, float timeout);
259
260         void PrintInfo(std::ostream &o)
261         {
262                 o<<"RemoteClient "<<peer_id<<": "
263                                 <<"m_blocks_sent.size()="<<m_blocks_sent.size()
264                                 <<", m_blocks_sending.size()="<<m_blocks_sending.size()
265                                 <<", m_nearest_unsent_d="<<m_nearest_unsent_d
266                                 <<", m_excess_gotblocks="<<m_excess_gotblocks
267                                 <<std::endl;
268                 m_excess_gotblocks = 0;
269         }
270
271         // Time from last placing or removing blocks
272         float m_time_from_building;
273
274         /*
275                 List of active objects that the client knows of.
276                 Value is dummy.
277         */
278         std::set<u16> m_known_objects;
279
280         ClientState getState()
281                 { return m_state; }
282
283         std::string getName()
284                 { return m_name; }
285
286         void setName(std::string name)
287                 { m_name = name; }
288
289         /* update internal client state */
290         void notifyEvent(ClientStateEvent event);
291
292         /* set expected serialization version */
293         void setPendingSerializationVersion(u8 version)
294                 { m_pending_serialization_version = version; }
295
296         void confirmSerializationVersion()
297                 { serialization_version = m_pending_serialization_version; }
298
299         /* get uptime */
300         u32 uptime();
301
302
303         /* set version information */
304         void setVersionInfo(u8 major, u8 minor, u8 patch, std::string full) {
305                 m_version_major = major;
306                 m_version_minor = minor;
307                 m_version_patch = patch;
308                 m_full_version = full;
309         }
310
311         /* read version information */
312         u8 getMajor() { return m_version_major; }
313         u8 getMinor() { return m_version_minor; }
314         u8 getPatch() { return m_version_patch; }
315         std::string getVersion() { return m_full_version; }
316 private:
317         // Version is stored in here after INIT before INIT2
318         u8 m_pending_serialization_version;
319
320         /* current state of client */
321         ClientState m_state;
322
323         /*
324                 Blocks that have been sent to client.
325                 - These don't have to be sent again.
326                 - A block is cleared from here when client says it has
327                   deleted it from it's memory
328
329                 Key is position, value is dummy.
330                 No MapBlock* is stored here because the blocks can get deleted.
331         */
332         std::set<v3s16> m_blocks_sent;
333         s16 m_nearest_unsent_d;
334         v3s16 m_last_center;
335         float m_nearest_unsent_reset_timer;
336
337         /*
338                 Blocks that are currently on the line.
339                 This is used for throttling the sending of blocks.
340                 - The size of this list is limited to some value
341                 Block is added when it is sent with BLOCKDATA.
342                 Block is removed when GOTBLOCKS is received.
343                 Value is time from sending. (not used at the moment)
344         */
345         std::map<v3s16, float> m_blocks_sending;
346
347         /*
348                 Count of excess GotBlocks().
349                 There is an excess amount because the client sometimes
350                 gets a block so late that the server sends it again,
351                 and the client then sends two GOTBLOCKs.
352                 This is resetted by PrintInfo()
353         */
354         u32 m_excess_gotblocks;
355
356         // CPU usage optimization
357         float m_nothing_to_send_pause_timer;
358
359         /*
360                 name of player using this client
361         */
362         std::string m_name;
363
364         /*
365                 client information
366          */
367         u8 m_version_major;
368         u8 m_version_minor;
369         u8 m_version_patch;
370
371         std::string m_full_version;
372
373         /*
374                 time this client was created
375          */
376         const u32 m_connection_time;
377 };
378
379 class ClientInterface {
380 public:
381
382         friend class Server;
383
384         ClientInterface(con::Connection* con);
385         ~ClientInterface();
386
387         /* run sync step */
388         void step(float dtime);
389
390         /* get list of active client id's */
391         std::list<u16> getClientIDs(ClientState min_state=CS_Active);
392
393         /* get list of client player names */
394         std::vector<std::string> getPlayerNames();
395
396         /* send message to client */
397         void send(u16 peer_id, u8 channelnum, NetworkPacket* pkt, bool reliable, bool deletepkt=true);
398
399         /* send to all clients */
400         void sendToAll(u16 channelnum, NetworkPacket* pkt, bool reliable);
401
402         /* delete a client */
403         void DeleteClient(u16 peer_id);
404
405         /* create client */
406         void CreateClient(u16 peer_id);
407
408         /* get a client by peer_id */
409         RemoteClient* getClientNoEx(u16 peer_id,  ClientState state_min=CS_Active);
410
411         /* get client by peer_id (make sure you have list lock before!*/
412         RemoteClient* lockedGetClientNoEx(u16 peer_id,  ClientState state_min=CS_Active);
413
414         /* get state of client by id*/
415         ClientState getClientState(u16 peer_id);
416
417         /* set client playername */
418         void setPlayerName(u16 peer_id,std::string name);
419
420         /* get protocol version of client */
421         u16 getProtocolVersion(u16 peer_id);
422
423         /* set client version */
424         void setClientVersion(u16 peer_id, u8 major, u8 minor, u8 patch, std::string full);
425
426         /* event to update client state */
427         void event(u16 peer_id, ClientStateEvent event);
428
429         /* set environment */
430         void setEnv(ServerEnvironment* env)
431         { assert(m_env == 0); m_env = env; }
432
433         static std::string state2Name(ClientState state);
434
435 protected:
436         //TODO find way to avoid this functions
437         void Lock()
438                 { m_clients_mutex.Lock(); }
439         void Unlock()
440                 { m_clients_mutex.Unlock(); }
441
442         std::map<u16, RemoteClient*>& getClientList()
443                 { return m_clients; }
444
445 private:
446         /* update internal player list */
447         void UpdatePlayerList();
448
449         // Connection
450         con::Connection* m_con;
451         JMutex m_clients_mutex;
452         // Connected clients (behind the con mutex)
453         std::map<u16, RemoteClient*> m_clients;
454         std::vector<std::string> m_clients_names; //for announcing masterserver
455
456         // Environment
457         ServerEnvironment *m_env;
458         JMutex m_env_mutex;
459
460         float m_print_info_timer;
461
462         static const char *statenames[];
463 };
464
465 #endif