]> git.lizzy.rs Git - minetest.git/blob - src/client.h
809e98b81c136fffb010542e215e2f95945a7056
[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
40 struct MeshMakeData;
41 class MapBlockMesh;
42 class IGameDef;
43 class IWritableTextureSource;
44 class IWritableShaderSource;
45 class IWritableItemDefManager;
46 class IWritableNodeDefManager;
47 //class IWritableCraftDefManager;
48 class ClientEnvironment;
49 struct MapDrawControl;
50 class MtEventManager;
51
52 class ClientNotReadyException : public BaseException
53 {
54 public:
55         ClientNotReadyException(const char *s):
56                 BaseException(s)
57         {}
58 };
59
60 struct QueuedMeshUpdate
61 {
62         v3s16 p;
63         MeshMakeData *data;
64         bool ack_block_to_server;
65
66         QueuedMeshUpdate();
67         ~QueuedMeshUpdate();
68 };
69
70 /*
71         A thread-safe queue of mesh update tasks
72 */
73 class MeshUpdateQueue
74 {
75 public:
76         MeshUpdateQueue();
77
78         ~MeshUpdateQueue();
79         
80         /*
81                 peer_id=0 adds with nobody to send to
82         */
83         void addBlock(v3s16 p, MeshMakeData *data,
84                         bool ack_block_to_server, bool urgent);
85
86         // Returned pointer must be deleted
87         // Returns NULL if queue is empty
88         QueuedMeshUpdate * pop();
89
90         u32 size()
91         {
92                 JMutexAutoLock lock(m_mutex);
93                 return m_queue.size();
94         }
95         
96 private:
97         std::vector<QueuedMeshUpdate*> m_queue;
98         std::set<v3s16> m_urgents;
99         JMutex m_mutex;
100 };
101
102 struct MeshUpdateResult
103 {
104         v3s16 p;
105         MapBlockMesh *mesh;
106         bool ack_block_to_server;
107
108         MeshUpdateResult():
109                 p(-1338,-1338,-1338),
110                 mesh(NULL),
111                 ack_block_to_server(false)
112         {
113         }
114 };
115
116 class MeshUpdateThread : public SimpleThread
117 {
118 public:
119
120         MeshUpdateThread(IGameDef *gamedef):
121                 m_gamedef(gamedef)
122         {
123         }
124
125         void * Thread();
126
127         MeshUpdateQueue m_queue_in;
128
129         MutexedQueue<MeshUpdateResult> m_queue_out;
130
131         IGameDef *m_gamedef;
132 };
133
134 class MediaFetchThread : public SimpleThread
135 {
136 public:
137
138         MediaFetchThread(IGameDef *gamedef):
139                 m_gamedef(gamedef)
140         {
141         }
142
143         void * Thread();
144
145         core::list<MediaRequest> m_file_requests;
146         MutexedQueue<std::pair<std::string, std::string> > m_file_data;
147         core::list<MediaRequest> m_failed;
148         std::string m_remote_url;
149         IGameDef *m_gamedef;
150 };
151
152 enum ClientEventType
153 {
154         CE_NONE,
155         CE_PLAYER_DAMAGE,
156         CE_PLAYER_FORCE_MOVE,
157         CE_DEATHSCREEN,
158         CE_TEXTURES_UPDATED,
159         CE_SHOW_FORMSPEC
160 };
161
162 struct ClientEvent
163 {
164         ClientEventType type;
165         union{
166                 struct{
167                 } none;
168                 struct{
169                         u8 amount;
170                 } player_damage;
171                 struct{
172                         f32 pitch;
173                         f32 yaw;
174                 } player_force_move;
175                 struct{
176                         bool set_camera_point_target;
177                         f32 camera_point_target_x;
178                         f32 camera_point_target_y;
179                         f32 camera_point_target_z;
180                 } deathscreen;
181                 struct{
182                         std::string* formspec;
183                         std::string* formname;
184                 } show_formspec;
185                 struct{
186                 } textures_updated;
187         };
188 };
189
190 class Client : public con::PeerHandler, public InventoryManager, public IGameDef
191 {
192 public:
193         /*
194                 NOTE: Nothing is thread-safe here.
195         */
196
197         Client(
198                         IrrlichtDevice *device,
199                         const char *playername,
200                         std::string password,
201                         MapDrawControl &control,
202                         IWritableTextureSource *tsrc,
203                         IWritableShaderSource *shsrc,
204                         IWritableItemDefManager *itemdef,
205                         IWritableNodeDefManager *nodedef,
206                         ISoundManager *sound,
207                         MtEventManager *event
208         );
209         
210         ~Client();
211         /*
212                 The name of the local player should already be set when
213                 calling this, as it is sent in the initialization.
214         */
215         void connect(Address address);
216         /*
217                 returns true when
218                         m_con.Connected() == true
219                         AND m_server_ser_ver != SER_FMT_VER_INVALID
220                 throws con::PeerNotFoundException if connection has been deleted,
221                 eg. timed out.
222         */
223         bool connectedAndInitialized();
224         /*
225                 Stuff that references the environment is valid only as
226                 long as this is not called. (eg. Players)
227                 If this throws a PeerNotFoundException, the connection has
228                 timed out.
229         */
230         void step(float dtime);
231
232         void ProcessData(u8 *data, u32 datasize, u16 sender_peer_id);
233         // Returns true if something was received
234         bool AsyncProcessPacket();
235         bool AsyncProcessData();
236         void Send(u16 channelnum, SharedBuffer<u8> data, bool reliable);
237
238         void interact(u8 action, const PointedThing& pointed);
239
240         void sendNodemetaFields(v3s16 p, const std::string &formname,
241                         const std::map<std::string, std::string> &fields);
242         void sendInventoryFields(const std::string &formname,
243                         const std::map<std::string, std::string> &fields);
244         void sendInventoryAction(InventoryAction *a);
245         void sendChatMessage(const std::wstring &message);
246         void sendChangePassword(const std::wstring oldpassword,
247                         const std::wstring newpassword);
248         void sendDamage(u8 damage);
249         void sendRespawn();
250
251         ClientEnvironment& getEnv()
252         { return m_env; }
253         
254         // Causes urgent mesh updates (unlike Map::add/removeNodeWithEvent)
255         void removeNode(v3s16 p);
256         void addNode(v3s16 p, MapNode n);
257         
258         void setPlayerControl(PlayerControl &control);
259
260         void selectPlayerItem(u16 item);
261         u16 getPlayerItem() const
262         { return m_playeritem; }
263
264         // Returns true if the inventory of the local player has been
265         // updated from the server. If it is true, it is set to false.
266         bool getLocalInventoryUpdated();
267         // Copies the inventory of the local player to parameter
268         void getLocalInventory(Inventory &dst);
269         
270         /* InventoryManager interface */
271         Inventory* getInventory(const InventoryLocation &loc);
272         void inventoryAction(InventoryAction *a);
273
274         // Gets closest object pointed by the shootline
275         // Returns NULL if not found
276         ClientActiveObject * getSelectedActiveObject(
277                         f32 max_d,
278                         v3f from_pos_f_on_map,
279                         core::line3d<f32> shootline_on_map
280         );
281
282         // Prints a line or two of info
283         void printDebugInfo(std::ostream &os);
284
285         core::list<std::wstring> getConnectedPlayerNames();
286
287         float getAnimationTime();
288
289         int getCrackLevel();
290         void setCrack(int level, v3s16 pos);
291
292         u16 getHP();
293
294         bool checkPrivilege(const std::string &priv)
295         { return (m_privileges.count(priv) != 0); }
296
297         bool getChatMessage(std::wstring &message);
298         void typeChatMessage(const std::wstring& message);
299
300         u64 getMapSeed(){ return m_map_seed; }
301
302         void addUpdateMeshTask(v3s16 blockpos, bool ack_to_server=false, bool urgent=false);
303         // Including blocks at appropriate edges
304         void addUpdateMeshTaskWithEdge(v3s16 blockpos, bool ack_to_server=false, bool urgent=false);
305         void addUpdateMeshTaskForNode(v3s16 nodepos, bool ack_to_server=false, bool urgent=false);
306
307         // Get event from queue. CE_NONE is returned if queue is empty.
308         ClientEvent getClientEvent();
309         
310         bool accessDenied()
311         { return m_access_denied; }
312
313         std::wstring accessDeniedReason()
314         { return m_access_denied_reason; }
315
316         float mediaReceiveProgress()
317         {
318                 if (!m_media_receive_started) return 0;
319                 return 1.0 * m_media_received_count / m_media_count;
320         }
321
322         bool texturesReceived()
323         { return m_media_receive_started && m_media_received_count == m_media_count; }
324         bool itemdefReceived()
325         { return m_itemdef_received; }
326         bool nodedefReceived()
327         { return m_nodedef_received; }
328         
329         void afterContentReceived();
330
331         float getRTT(void);
332
333         // IGameDef interface
334         virtual IItemDefManager* getItemDefManager();
335         virtual INodeDefManager* getNodeDefManager();
336         virtual ICraftDefManager* getCraftDefManager();
337         virtual ITextureSource* getTextureSource();
338         virtual IShaderSource* getShaderSource();
339         virtual u16 allocateUnknownNodeId(const std::string &name);
340         virtual ISoundManager* getSoundManager();
341         virtual MtEventManager* getEventManager();
342         virtual bool checkLocalPrivilege(const std::string &priv)
343         { return checkPrivilege(priv); }
344
345 private:
346         
347         // Insert a media file appropriately into the appropriate manager
348         bool loadMedia(const std::string &data, const std::string &filename);
349
350         void request_media(const core::list<MediaRequest> &file_requests);
351
352         // Virtual methods from con::PeerHandler
353         void peerAdded(con::Peer *peer);
354         void deletingPeer(con::Peer *peer, bool timeout);
355         
356         void ReceiveAll();
357         void Receive();
358         
359         void sendPlayerPos();
360         // This sends the player's current name etc to the server
361         void sendPlayerInfo();
362         // Send the item number 'item' as player item to the server
363         void sendPlayerItem(u16 item);
364         
365         float m_packetcounter_timer;
366         float m_connection_reinit_timer;
367         float m_avg_rtt_timer;
368         float m_playerpos_send_timer;
369         float m_ignore_damage_timer; // Used after server moves player
370         IntervalLimiter m_map_timer_and_unload_interval;
371
372         IWritableTextureSource *m_tsrc;
373         IWritableShaderSource *m_shsrc;
374         IWritableItemDefManager *m_itemdef;
375         IWritableNodeDefManager *m_nodedef;
376         ISoundManager *m_sound;
377         MtEventManager *m_event;
378
379         MeshUpdateThread m_mesh_update_thread;
380         core::list<MediaFetchThread*> m_media_fetch_threads;
381         ClientEnvironment m_env;
382         con::Connection m_con;
383         IrrlichtDevice *m_device;
384         // Server serialization version
385         u8 m_server_ser_ver;
386         u16 m_playeritem;
387         bool m_inventory_updated;
388         Inventory *m_inventory_from_server;
389         float m_inventory_from_server_age;
390         core::map<v3s16, bool> m_active_blocks;
391         PacketCounter m_packetcounter;
392         // Block mesh animation parameters
393         float m_animation_time;
394         int m_crack_level;
395         v3s16 m_crack_pos;
396         // 0 <= m_daynight_i < DAYNIGHT_CACHE_COUNT
397         //s32 m_daynight_i;
398         //u32 m_daynight_ratio;
399         Queue<std::wstring> m_chat_queue;
400         // The seed returned by the server in TOCLIENT_INIT is stored here
401         u64 m_map_seed;
402         std::string m_password;
403         bool m_access_denied;
404         std::wstring m_access_denied_reason;
405         Queue<ClientEvent> m_client_event_queue;
406         FileCache m_media_cache;
407         // Mapping from media file name to SHA1 checksum
408         core::map<std::string, std::string> m_media_name_sha1_map;
409         bool m_media_receive_started;
410         u32 m_media_count;
411         u32 m_media_received_count;
412         bool m_itemdef_received;
413         bool m_nodedef_received;
414         friend class FarMesh;
415
416         // time_of_day speed approximation for old protocol
417         bool m_time_of_day_set;
418         float m_last_time_of_day_f;
419         float m_time_of_day_update_timer;
420
421         // An interval for generally sending object positions and stuff
422         float m_recommended_send_interval;
423
424         // Sounds
425         float m_removed_sounds_check_timer;
426         // Mapping from server sound ids to our sound ids
427         std::map<s32, int> m_sounds_server_to_client;
428         // And the other way!
429         std::map<int, s32> m_sounds_client_to_server;
430         // And relations to objects
431         std::map<int, u16> m_sounds_to_objects;
432
433         // Privileges
434         std::set<std::string> m_privileges;
435
436         // Detached inventories
437         // key = name
438         std::map<std::string, Inventory*> m_detached_inventories;
439 };
440
441 #endif // !CLIENT_HEADER
442