]> git.lizzy.rs Git - dragonfireclient.git/blob - src/client.h
Omnicleanup: header cleanup, add ModApiUtil shared between game and mainmenu
[dragonfireclient.git] / src / client.h
1 /*
2 Minetest
3 Copyright (C) 2013 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
20 #ifndef CLIENT_HEADER
21 #define CLIENT_HEADER
22
23 #include "connection.h"
24 #include "environment.h"
25 #include "irrlichttypes_extrabloated.h"
26 #include "jmutex.h"
27 #include <ostream>
28 #include <map>
29 #include <set>
30 #include <vector>
31 #include "clientobject.h"
32 #include "gamedef.h"
33 #include "inventorymanager.h"
34 #include "filecache.h"
35 #include "localplayer.h"
36 #include "server.h"
37 #include "particles.h"
38 #include "util/pointedthing.h"
39 #include <algorithm>
40
41 struct MeshMakeData;
42 class MapBlockMesh;
43 class IGameDef;
44 class IWritableTextureSource;
45 class IWritableShaderSource;
46 class IWritableItemDefManager;
47 class IWritableNodeDefManager;
48 //class IWritableCraftDefManager;
49 class ClientEnvironment;
50 struct MapDrawControl;
51 class MtEventManager;
52
53 class ClientNotReadyException : public BaseException
54 {
55 public:
56         ClientNotReadyException(const char *s):
57                 BaseException(s)
58         {}
59 };
60
61 struct QueuedMeshUpdate
62 {
63         v3s16 p;
64         MeshMakeData *data;
65         bool ack_block_to_server;
66
67         QueuedMeshUpdate();
68         ~QueuedMeshUpdate();
69 };
70
71 /*
72         A thread-safe queue of mesh update tasks
73 */
74 class MeshUpdateQueue
75 {
76 public:
77         MeshUpdateQueue();
78
79         ~MeshUpdateQueue();
80         
81         /*
82                 peer_id=0 adds with nobody to send to
83         */
84         void addBlock(v3s16 p, MeshMakeData *data,
85                         bool ack_block_to_server, bool urgent);
86
87         // Returned pointer must be deleted
88         // Returns NULL if queue is empty
89         QueuedMeshUpdate * pop();
90
91         u32 size()
92         {
93                 JMutexAutoLock lock(m_mutex);
94                 return m_queue.size();
95         }
96         
97 private:
98         std::vector<QueuedMeshUpdate*> m_queue;
99         std::set<v3s16> m_urgents;
100         JMutex m_mutex;
101 };
102
103 struct MeshUpdateResult
104 {
105         v3s16 p;
106         MapBlockMesh *mesh;
107         bool ack_block_to_server;
108
109         MeshUpdateResult():
110                 p(-1338,-1338,-1338),
111                 mesh(NULL),
112                 ack_block_to_server(false)
113         {
114         }
115 };
116
117 class MeshUpdateThread : public SimpleThread
118 {
119 public:
120
121         MeshUpdateThread(IGameDef *gamedef):
122                 m_gamedef(gamedef)
123         {
124         }
125
126         void * Thread();
127
128         MeshUpdateQueue m_queue_in;
129
130         MutexedQueue<MeshUpdateResult> m_queue_out;
131
132         IGameDef *m_gamedef;
133 };
134
135 class MediaFetchThread : public SimpleThread
136 {
137 public:
138
139         MediaFetchThread(IGameDef *gamedef):
140                 m_gamedef(gamedef)
141         {
142         }
143
144         void * Thread();
145
146         std::list<MediaRequest> m_file_requests;
147         MutexedQueue<std::pair<std::string, std::string> > m_file_data;
148         std::list<MediaRequest> m_failed;
149         std::string m_remote_url;
150         IGameDef *m_gamedef;
151 };
152
153 enum ClientEventType
154 {
155         CE_NONE,
156         CE_PLAYER_DAMAGE,
157         CE_PLAYER_FORCE_MOVE,
158         CE_DEATHSCREEN,
159         CE_TEXTURES_UPDATED,
160         CE_SHOW_FORMSPEC,
161         CE_SPAWN_PARTICLE,
162         CE_ADD_PARTICLESPAWNER,
163         CE_DELETE_PARTICLESPAWNER,
164         CE_HUDADD,
165         CE_HUDRM,
166         CE_HUDCHANGE
167 };
168
169 struct ClientEvent
170 {
171         ClientEventType type;
172         union{
173                 struct{
174                 } none;
175                 struct{
176                         u8 amount;
177                 } player_damage;
178                 struct{
179                         f32 pitch;
180                         f32 yaw;
181                 } player_force_move;
182                 struct{
183                         bool set_camera_point_target;
184                         f32 camera_point_target_x;
185                         f32 camera_point_target_y;
186                         f32 camera_point_target_z;
187                 } deathscreen;
188                 struct{
189                         std::string *formspec;
190                         std::string *formname;
191                 } show_formspec;
192                 struct{
193                 } textures_updated;
194                 struct{
195                         v3f *pos;
196                         v3f *vel;
197                         v3f *acc;
198                         f32 expirationtime;
199                         f32 size;
200                         bool collisiondetection;
201                         std::string *texture;
202                 } spawn_particle;
203                 struct{
204                         u16 amount;
205                         f32 spawntime;
206                         v3f *minpos;
207                         v3f *maxpos;
208                         v3f *minvel;
209                         v3f *maxvel;
210                         v3f *minacc;
211                         v3f *maxacc;
212                         f32 minexptime;
213                         f32 maxexptime;
214                         f32 minsize;
215                         f32 maxsize;
216                         bool collisiondetection;
217                         std::string *texture;
218                         u32 id;
219                 } add_particlespawner;
220                 struct{
221                         u32 id;
222                 } delete_particlespawner;
223                 struct{
224                         u32 id;
225                         u8 type;
226                         v2f *pos;
227                         std::string *name;
228                         v2f *scale;
229                         std::string *text;
230                         u32 number;
231                         u32 item;
232                         u32 dir;
233                         v2f *align;
234                         v2f *offset;
235                 } hudadd;
236                 struct{
237                         u32 id;
238                 } hudrm;
239                 struct{
240                         u32 id;
241                         HudElementStat stat;
242                         v2f *v2fdata;
243                         std::string *sdata;
244                         u32 data;
245                 } hudchange;
246         };
247 };
248
249 /*
250         Packet counter
251 */
252
253 class PacketCounter
254 {
255 public:
256         PacketCounter()
257         {
258         }
259
260         void add(u16 command)
261         {
262                 std::map<u16, u16>::iterator n = m_packets.find(command);
263                 if(n == m_packets.end())
264                 {
265                         m_packets[command] = 1;
266                 }
267                 else
268                 {
269                         n->second++;
270                 }
271         }
272
273         void clear()
274         {
275                 for(std::map<u16, u16>::iterator
276                                 i = m_packets.begin();
277                                 i != m_packets.end(); ++i)
278                 {
279                         i->second = 0;
280                 }
281         }
282
283         void print(std::ostream &o)
284         {
285                 for(std::map<u16, u16>::iterator
286                                 i = m_packets.begin();
287                                 i != m_packets.end(); ++i)
288                 {
289                         o<<"cmd "<<i->first
290                                         <<" count "<<i->second
291                                         <<std::endl;
292                 }
293         }
294
295 private:
296         // command, count
297         std::map<u16, u16> m_packets;
298 };
299
300 class Client : public con::PeerHandler, public InventoryManager, public IGameDef
301 {
302 public:
303         /*
304                 NOTE: Nothing is thread-safe here.
305         */
306
307         Client(
308                         IrrlichtDevice *device,
309                         const char *playername,
310                         std::string password,
311                         MapDrawControl &control,
312                         IWritableTextureSource *tsrc,
313                         IWritableShaderSource *shsrc,
314                         IWritableItemDefManager *itemdef,
315                         IWritableNodeDefManager *nodedef,
316                         ISoundManager *sound,
317                         MtEventManager *event,
318                         bool ipv6
319         );
320         
321         ~Client();
322         /*
323                 The name of the local player should already be set when
324                 calling this, as it is sent in the initialization.
325         */
326         void connect(Address address);
327         /*
328                 returns true when
329                         m_con.Connected() == true
330                         AND m_server_ser_ver != SER_FMT_VER_INVALID
331                 throws con::PeerNotFoundException if connection has been deleted,
332                 eg. timed out.
333         */
334         bool connectedAndInitialized();
335         /*
336                 Stuff that references the environment is valid only as
337                 long as this is not called. (eg. Players)
338                 If this throws a PeerNotFoundException, the connection has
339                 timed out.
340         */
341         void step(float dtime);
342
343         void ProcessData(u8 *data, u32 datasize, u16 sender_peer_id);
344         // Returns true if something was received
345         bool AsyncProcessPacket();
346         bool AsyncProcessData();
347         void Send(u16 channelnum, SharedBuffer<u8> data, bool reliable);
348
349         void interact(u8 action, const PointedThing& pointed);
350
351         void sendNodemetaFields(v3s16 p, const std::string &formname,
352                         const std::map<std::string, std::string> &fields);
353         void sendInventoryFields(const std::string &formname,
354                         const std::map<std::string, std::string> &fields);
355         void sendInventoryAction(InventoryAction *a);
356         void sendChatMessage(const std::wstring &message);
357         void sendChangePassword(const std::wstring oldpassword,
358                         const std::wstring newpassword);
359         void sendDamage(u8 damage);
360         void sendBreath(u16 breath);
361         void sendRespawn();
362
363         ClientEnvironment& getEnv()
364         { return m_env; }
365         
366         // Causes urgent mesh updates (unlike Map::add/removeNodeWithEvent)
367         void removeNode(v3s16 p);
368         void addNode(v3s16 p, MapNode n);
369         
370         void setPlayerControl(PlayerControl &control);
371
372         void selectPlayerItem(u16 item);
373         u16 getPlayerItem() const
374         { return m_playeritem; }
375
376         // Returns true if the inventory of the local player has been
377         // updated from the server. If it is true, it is set to false.
378         bool getLocalInventoryUpdated();
379         // Copies the inventory of the local player to parameter
380         void getLocalInventory(Inventory &dst);
381         
382         /* InventoryManager interface */
383         Inventory* getInventory(const InventoryLocation &loc);
384         void inventoryAction(InventoryAction *a);
385
386         // Gets closest object pointed by the shootline
387         // Returns NULL if not found
388         ClientActiveObject * getSelectedActiveObject(
389                         f32 max_d,
390                         v3f from_pos_f_on_map,
391                         core::line3d<f32> shootline_on_map
392         );
393
394         // Prints a line or two of info
395         void printDebugInfo(std::ostream &os);
396
397         std::list<std::string> getConnectedPlayerNames();
398
399         float getAnimationTime();
400
401         int getCrackLevel();
402         void setCrack(int level, v3s16 pos);
403
404         u16 getHP();
405         u16 getBreath();
406
407         bool checkPrivilege(const std::string &priv)
408         { return (m_privileges.count(priv) != 0); }
409
410         bool getChatMessage(std::wstring &message);
411         void typeChatMessage(const std::wstring& message);
412
413         u64 getMapSeed(){ return m_map_seed; }
414
415         void addUpdateMeshTask(v3s16 blockpos, bool ack_to_server=false, bool urgent=false);
416         // Including blocks at appropriate edges
417         void addUpdateMeshTaskWithEdge(v3s16 blockpos, bool ack_to_server=false, bool urgent=false);
418         void addUpdateMeshTaskForNode(v3s16 nodepos, bool ack_to_server=false, bool urgent=false);
419
420         // Get event from queue. CE_NONE is returned if queue is empty.
421         ClientEvent getClientEvent();
422         
423         bool accessDenied()
424         { return m_access_denied; }
425
426         std::wstring accessDeniedReason()
427         { return m_access_denied_reason; }
428
429         float mediaReceiveProgress()
430         {
431                 if (!m_media_receive_started) return 0;
432                 return 1.0 * m_media_received_count / m_media_count;
433         }
434
435         bool texturesReceived()
436         { return m_media_receive_started && m_media_received_count == m_media_count; }
437         bool itemdefReceived()
438         { return m_itemdef_received; }
439         bool nodedefReceived()
440         { return m_nodedef_received; }
441         
442         void afterContentReceived(IrrlichtDevice *device, gui::IGUIFont* font);
443
444         float getRTT(void);
445
446         // IGameDef interface
447         virtual IItemDefManager* getItemDefManager();
448         virtual INodeDefManager* getNodeDefManager();
449         virtual ICraftDefManager* getCraftDefManager();
450         virtual ITextureSource* getTextureSource();
451         virtual IShaderSource* getShaderSource();
452         virtual u16 allocateUnknownNodeId(const std::string &name);
453         virtual ISoundManager* getSoundManager();
454         virtual MtEventManager* getEventManager();
455         virtual bool checkLocalPrivilege(const std::string &priv)
456         { return checkPrivilege(priv); }
457
458 private:
459         
460         // Insert a media file appropriately into the appropriate manager
461         bool loadMedia(const std::string &data, const std::string &filename);
462
463         void request_media(const std::list<MediaRequest> &file_requests);
464
465         // Virtual methods from con::PeerHandler
466         void peerAdded(con::Peer *peer);
467         void deletingPeer(con::Peer *peer, bool timeout);
468         
469         void ReceiveAll();
470         void Receive();
471         
472         void sendPlayerPos();
473         // Send the item number 'item' as player item to the server
474         void sendPlayerItem(u16 item);
475         
476         float m_packetcounter_timer;
477         float m_connection_reinit_timer;
478         float m_avg_rtt_timer;
479         float m_playerpos_send_timer;
480         float m_ignore_damage_timer; // Used after server moves player
481         IntervalLimiter m_map_timer_and_unload_interval;
482
483         IWritableTextureSource *m_tsrc;
484         IWritableShaderSource *m_shsrc;
485         IWritableItemDefManager *m_itemdef;
486         IWritableNodeDefManager *m_nodedef;
487         ISoundManager *m_sound;
488         MtEventManager *m_event;
489
490         MeshUpdateThread m_mesh_update_thread;
491         std::list<MediaFetchThread*> m_media_fetch_threads;
492         ClientEnvironment m_env;
493         con::Connection m_con;
494         IrrlichtDevice *m_device;
495         // Server serialization version
496         u8 m_server_ser_ver;
497         u16 m_playeritem;
498         bool m_inventory_updated;
499         Inventory *m_inventory_from_server;
500         float m_inventory_from_server_age;
501         std::set<v3s16> m_active_blocks;
502         PacketCounter m_packetcounter;
503         // Block mesh animation parameters
504         float m_animation_time;
505         int m_crack_level;
506         v3s16 m_crack_pos;
507         // 0 <= m_daynight_i < DAYNIGHT_CACHE_COUNT
508         //s32 m_daynight_i;
509         //u32 m_daynight_ratio;
510         Queue<std::wstring> m_chat_queue;
511         // The seed returned by the server in TOCLIENT_INIT is stored here
512         u64 m_map_seed;
513         std::string m_password;
514         bool m_access_denied;
515         std::wstring m_access_denied_reason;
516         Queue<ClientEvent> m_client_event_queue;
517         FileCache m_media_cache;
518         // Mapping from media file name to SHA1 checksum
519         std::map<std::string, std::string> m_media_name_sha1_map;
520         bool m_media_receive_started;
521         u32 m_media_count;
522         u32 m_media_received_count;
523         bool m_itemdef_received;
524         bool m_nodedef_received;
525
526         // time_of_day speed approximation for old protocol
527         bool m_time_of_day_set;
528         float m_last_time_of_day_f;
529         float m_time_of_day_update_timer;
530
531         // An interval for generally sending object positions and stuff
532         float m_recommended_send_interval;
533
534         // Sounds
535         float m_removed_sounds_check_timer;
536         // Mapping from server sound ids to our sound ids
537         std::map<s32, int> m_sounds_server_to_client;
538         // And the other way!
539         std::map<int, s32> m_sounds_client_to_server;
540         // And relations to objects
541         std::map<int, u16> m_sounds_to_objects;
542
543         // Privileges
544         std::set<std::string> m_privileges;
545
546         // Detached inventories
547         // key = name
548         std::map<std::string, Inventory*> m_detached_inventories;
549 };
550
551 #endif // !CLIENT_HEADER
552