]> git.lizzy.rs Git - minetest.git/blob - src/client.h
33872864e6c31d9bf705d1223e4fe0e84cb95bb0
[minetest.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 <set>
29 #include <vector>
30 #include "clientobject.h"
31 #include "gamedef.h"
32 #include "inventorymanager.h"
33 #include "filesys.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         CE_HUD_BUILTIN_ENABLE
168 };
169
170 struct ClientEvent
171 {
172         ClientEventType type;
173         union{
174                 struct{
175                 } none;
176                 struct{
177                         u8 amount;
178                 } player_damage;
179                 struct{
180                         f32 pitch;
181                         f32 yaw;
182                 } player_force_move;
183                 struct{
184                         bool set_camera_point_target;
185                         f32 camera_point_target_x;
186                         f32 camera_point_target_y;
187                         f32 camera_point_target_z;
188                 } deathscreen;
189                 struct{
190                         std::string *formspec;
191                         std::string *formname;
192                 } show_formspec;
193                 struct{
194                 } textures_updated;
195                 struct{
196                         v3f *pos;
197                         v3f *vel;
198                         v3f *acc;
199                         f32 expirationtime;
200                         f32 size;
201                         bool collisiondetection;
202                         std::string *texture;
203                 } spawn_particle;
204                 struct{
205                         u16 amount;
206                         f32 spawntime;
207                         v3f *minpos;
208                         v3f *maxpos;
209                         v3f *minvel;
210                         v3f *maxvel;
211                         v3f *minacc;
212                         v3f *maxacc;
213                         f32 minexptime;
214                         f32 maxexptime;
215                         f32 minsize;
216                         f32 maxsize;
217                         bool collisiondetection;
218                         std::string *texture;
219                         u32 id;
220                 } add_particlespawner;
221                 struct{
222                         u32 id;
223                 } delete_particlespawner;
224                 struct{
225                         u32 id;
226                         u8 type;
227                         v2f *pos;
228                         std::string *name;
229                         v2f *scale;
230                         std::string *text;
231                         u32 number;
232                         u32 item;
233                         u32 dir;
234                         v2f *align;
235                         v2f *offset;
236                 } hudadd;
237                 struct{
238                         u32 id;
239                 } hudrm;
240                 struct{
241                         u32 id;
242                         HudElementStat stat;
243                         v2f *v2fdata;
244                         std::string *sdata;
245                         u32 data;
246                 } hudchange;
247                 struct{
248                         u32 id;
249                         u32 flag;
250                 } hudbuiltin;
251         };
252 };
253
254 class Client : public con::PeerHandler, public InventoryManager, public IGameDef
255 {
256 public:
257         /*
258                 NOTE: Nothing is thread-safe here.
259         */
260
261         Client(
262                         IrrlichtDevice *device,
263                         const char *playername,
264                         std::string password,
265                         MapDrawControl &control,
266                         IWritableTextureSource *tsrc,
267                         IWritableShaderSource *shsrc,
268                         IWritableItemDefManager *itemdef,
269                         IWritableNodeDefManager *nodedef,
270                         ISoundManager *sound,
271                         MtEventManager *event
272         );
273         
274         ~Client();
275         /*
276                 The name of the local player should already be set when
277                 calling this, as it is sent in the initialization.
278         */
279         void connect(Address address);
280         /*
281                 returns true when
282                         m_con.Connected() == true
283                         AND m_server_ser_ver != SER_FMT_VER_INVALID
284                 throws con::PeerNotFoundException if connection has been deleted,
285                 eg. timed out.
286         */
287         bool connectedAndInitialized();
288         /*
289                 Stuff that references the environment is valid only as
290                 long as this is not called. (eg. Players)
291                 If this throws a PeerNotFoundException, the connection has
292                 timed out.
293         */
294         void step(float dtime);
295
296         void ProcessData(u8 *data, u32 datasize, u16 sender_peer_id);
297         // Returns true if something was received
298         bool AsyncProcessPacket();
299         bool AsyncProcessData();
300         void Send(u16 channelnum, SharedBuffer<u8> data, bool reliable);
301
302         void interact(u8 action, const PointedThing& pointed);
303
304         void sendNodemetaFields(v3s16 p, const std::string &formname,
305                         const std::map<std::string, std::string> &fields);
306         void sendInventoryFields(const std::string &formname,
307                         const std::map<std::string, std::string> &fields);
308         void sendInventoryAction(InventoryAction *a);
309         void sendChatMessage(const std::wstring &message);
310         void sendChangePassword(const std::wstring oldpassword,
311                         const std::wstring newpassword);
312         void sendDamage(u8 damage);
313         void sendRespawn();
314
315         ClientEnvironment& getEnv()
316         { return m_env; }
317         
318         // Causes urgent mesh updates (unlike Map::add/removeNodeWithEvent)
319         void removeNode(v3s16 p);
320         void addNode(v3s16 p, MapNode n);
321         
322         void setPlayerControl(PlayerControl &control);
323
324         void selectPlayerItem(u16 item);
325         u16 getPlayerItem() const
326         { return m_playeritem; }
327
328         // Returns true if the inventory of the local player has been
329         // updated from the server. If it is true, it is set to false.
330         bool getLocalInventoryUpdated();
331         // Copies the inventory of the local player to parameter
332         void getLocalInventory(Inventory &dst);
333         
334         /* InventoryManager interface */
335         Inventory* getInventory(const InventoryLocation &loc);
336         void inventoryAction(InventoryAction *a);
337
338         // Gets closest object pointed by the shootline
339         // Returns NULL if not found
340         ClientActiveObject * getSelectedActiveObject(
341                         f32 max_d,
342                         v3f from_pos_f_on_map,
343                         core::line3d<f32> shootline_on_map
344         );
345
346         // Prints a line or two of info
347         void printDebugInfo(std::ostream &os);
348
349         std::list<std::string> getConnectedPlayerNames();
350
351         float getAnimationTime();
352
353         int getCrackLevel();
354         void setCrack(int level, v3s16 pos);
355
356         u16 getHP();
357
358         bool checkPrivilege(const std::string &priv)
359         { return (m_privileges.count(priv) != 0); }
360
361         bool getChatMessage(std::wstring &message);
362         void typeChatMessage(const std::wstring& message);
363
364         u64 getMapSeed(){ return m_map_seed; }
365
366         void addUpdateMeshTask(v3s16 blockpos, bool ack_to_server=false, bool urgent=false);
367         // Including blocks at appropriate edges
368         void addUpdateMeshTaskWithEdge(v3s16 blockpos, bool ack_to_server=false, bool urgent=false);
369         void addUpdateMeshTaskForNode(v3s16 nodepos, bool ack_to_server=false, bool urgent=false);
370
371         // Get event from queue. CE_NONE is returned if queue is empty.
372         ClientEvent getClientEvent();
373         
374         bool accessDenied()
375         { return m_access_denied; }
376
377         std::wstring accessDeniedReason()
378         { return m_access_denied_reason; }
379
380         float mediaReceiveProgress()
381         {
382                 if (!m_media_receive_started) return 0;
383                 return 1.0 * m_media_received_count / m_media_count;
384         }
385
386         bool texturesReceived()
387         { return m_media_receive_started && m_media_received_count == m_media_count; }
388         bool itemdefReceived()
389         { return m_itemdef_received; }
390         bool nodedefReceived()
391         { return m_nodedef_received; }
392         
393         void afterContentReceived();
394
395         float getRTT(void);
396
397         // IGameDef interface
398         virtual IItemDefManager* getItemDefManager();
399         virtual INodeDefManager* getNodeDefManager();
400         virtual ICraftDefManager* getCraftDefManager();
401         virtual ITextureSource* getTextureSource();
402         virtual IShaderSource* getShaderSource();
403         virtual u16 allocateUnknownNodeId(const std::string &name);
404         virtual ISoundManager* getSoundManager();
405         virtual MtEventManager* getEventManager();
406         virtual bool checkLocalPrivilege(const std::string &priv)
407         { return checkPrivilege(priv); }
408
409 private:
410         
411         // Insert a media file appropriately into the appropriate manager
412         bool loadMedia(const std::string &data, const std::string &filename);
413
414         void request_media(const std::list<MediaRequest> &file_requests);
415
416         // Virtual methods from con::PeerHandler
417         void peerAdded(con::Peer *peer);
418         void deletingPeer(con::Peer *peer, bool timeout);
419         
420         void ReceiveAll();
421         void Receive();
422         
423         void sendPlayerPos();
424         // This sends the player's current name etc to the server
425         void sendPlayerInfo();
426         // Send the item number 'item' as player item to the server
427         void sendPlayerItem(u16 item);
428         
429         float m_packetcounter_timer;
430         float m_connection_reinit_timer;
431         float m_avg_rtt_timer;
432         float m_playerpos_send_timer;
433         float m_ignore_damage_timer; // Used after server moves player
434         IntervalLimiter m_map_timer_and_unload_interval;
435
436         IWritableTextureSource *m_tsrc;
437         IWritableShaderSource *m_shsrc;
438         IWritableItemDefManager *m_itemdef;
439         IWritableNodeDefManager *m_nodedef;
440         ISoundManager *m_sound;
441         MtEventManager *m_event;
442
443         MeshUpdateThread m_mesh_update_thread;
444         std::list<MediaFetchThread*> m_media_fetch_threads;
445         ClientEnvironment m_env;
446         con::Connection m_con;
447         IrrlichtDevice *m_device;
448         // Server serialization version
449         u8 m_server_ser_ver;
450         u16 m_playeritem;
451         bool m_inventory_updated;
452         Inventory *m_inventory_from_server;
453         float m_inventory_from_server_age;
454         std::set<v3s16> m_active_blocks;
455         PacketCounter m_packetcounter;
456         // Block mesh animation parameters
457         float m_animation_time;
458         int m_crack_level;
459         v3s16 m_crack_pos;
460         // 0 <= m_daynight_i < DAYNIGHT_CACHE_COUNT
461         //s32 m_daynight_i;
462         //u32 m_daynight_ratio;
463         Queue<std::wstring> m_chat_queue;
464         // The seed returned by the server in TOCLIENT_INIT is stored here
465         u64 m_map_seed;
466         std::string m_password;
467         bool m_access_denied;
468         std::wstring m_access_denied_reason;
469         Queue<ClientEvent> m_client_event_queue;
470         FileCache m_media_cache;
471         // Mapping from media file name to SHA1 checksum
472         std::map<std::string, std::string> m_media_name_sha1_map;
473         bool m_media_receive_started;
474         u32 m_media_count;
475         u32 m_media_received_count;
476         bool m_itemdef_received;
477         bool m_nodedef_received;
478         friend class FarMesh;
479
480         // time_of_day speed approximation for old protocol
481         bool m_time_of_day_set;
482         float m_last_time_of_day_f;
483         float m_time_of_day_update_timer;
484
485         // An interval for generally sending object positions and stuff
486         float m_recommended_send_interval;
487
488         // Sounds
489         float m_removed_sounds_check_timer;
490         // Mapping from server sound ids to our sound ids
491         std::map<s32, int> m_sounds_server_to_client;
492         // And the other way!
493         std::map<int, s32> m_sounds_client_to_server;
494         // And relations to objects
495         std::map<int, u16> m_sounds_to_objects;
496
497         // Privileges
498         std::set<std::string> m_privileges;
499
500         // Detached inventories
501         // key = name
502         std::map<std::string, Inventory*> m_detached_inventories;
503 };
504
505 #endif // !CLIENT_HEADER
506