625170b174011382c5c099ad1a75a1ac4c682c4e
[oweals/minetest.git] / src / client.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 #ifndef CLIENT_HEADER
21 #define CLIENT_HEADER
22
23 #ifndef SERVER
24
25 #include "connection.h"
26 #include "environment.h"
27 #include "common_irrlicht.h"
28 #include "jmutex.h"
29 #include <ostream>
30 #include "clientobject.h"
31 #include "utility.h" // For IntervalLimiter
32 #include "gamedef.h"
33
34 struct MeshMakeData;
35 class IGameDef;
36 class IWritableTextureSource;
37 class IWritableToolDefManager;
38 class IWritableNodeDefManager;
39
40 class ClientNotReadyException : public BaseException
41 {
42 public:
43         ClientNotReadyException(const char *s):
44                 BaseException(s)
45         {}
46 };
47
48 struct QueuedMeshUpdate
49 {
50         v3s16 p;
51         MeshMakeData *data;
52         bool ack_block_to_server;
53
54         QueuedMeshUpdate();
55         ~QueuedMeshUpdate();
56 };
57
58 /*
59         A thread-safe queue of mesh update tasks
60 */
61 class MeshUpdateQueue
62 {
63 public:
64         MeshUpdateQueue();
65
66         ~MeshUpdateQueue();
67         
68         /*
69                 peer_id=0 adds with nobody to send to
70         */
71         void addBlock(v3s16 p, MeshMakeData *data, bool ack_block_to_server);
72
73         // Returned pointer must be deleted
74         // Returns NULL if queue is empty
75         QueuedMeshUpdate * pop();
76
77         u32 size()
78         {
79                 JMutexAutoLock lock(m_mutex);
80                 return m_queue.size();
81         }
82         
83 private:
84         core::list<QueuedMeshUpdate*> m_queue;
85         JMutex m_mutex;
86 };
87
88 struct MeshUpdateResult
89 {
90         v3s16 p;
91         scene::SMesh *mesh;
92         bool ack_block_to_server;
93
94         MeshUpdateResult():
95                 p(-1338,-1338,-1338),
96                 mesh(NULL),
97                 ack_block_to_server(false)
98         {
99         }
100 };
101
102 class MeshUpdateThread : public SimpleThread
103 {
104 public:
105
106         MeshUpdateThread(IGameDef *gamedef):
107                 m_gamedef(gamedef)
108         {
109         }
110
111         void * Thread();
112
113         MeshUpdateQueue m_queue_in;
114
115         MutexedQueue<MeshUpdateResult> m_queue_out;
116
117         IGameDef *m_gamedef;
118 };
119
120 enum ClientEventType
121 {
122         CE_NONE,
123         CE_PLAYER_DAMAGE,
124         CE_PLAYER_FORCE_MOVE,
125         CE_DEATHSCREEN,
126         CE_TEXTURES_UPDATED
127 };
128
129 struct ClientEvent
130 {
131         ClientEventType type;
132         union{
133                 struct{
134                 } none;
135                 struct{
136                         u8 amount;
137                 } player_damage;
138                 struct{
139                         f32 pitch;
140                         f32 yaw;
141                 } player_force_move;
142                 struct{
143                         bool set_camera_point_target;
144                         f32 camera_point_target_x;
145                         f32 camera_point_target_y;
146                         f32 camera_point_target_z;
147                 } deathscreen;
148                 struct{
149                 } textures_updated;
150         };
151 };
152
153 class Client : public con::PeerHandler, public InventoryManager, public IGameDef
154 {
155 public:
156         /*
157                 NOTE: Nothing is thread-safe here.
158         */
159
160         Client(
161                         IrrlichtDevice *device,
162                         const char *playername,
163                         std::string password,
164                         MapDrawControl &control,
165                         IWritableTextureSource *tsrc,
166                         IWritableToolDefManager *tooldef,
167                         IWritableNodeDefManager *nodedef
168         );
169         
170         ~Client();
171         /*
172                 The name of the local player should already be set when
173                 calling this, as it is sent in the initialization.
174         */
175         void connect(Address address);
176         /*
177                 returns true when
178                         m_con.Connected() == true
179                         AND m_server_ser_ver != SER_FMT_VER_INVALID
180                 throws con::PeerNotFoundException if connection has been deleted,
181                 eg. timed out.
182         */
183         bool connectedAndInitialized();
184         /*
185                 Stuff that references the environment is valid only as
186                 long as this is not called. (eg. Players)
187                 If this throws a PeerNotFoundException, the connection has
188                 timed out.
189         */
190         void step(float dtime);
191
192         // Called from updater thread
193         // Returns dtime
194         //float asyncStep();
195
196         void ProcessData(u8 *data, u32 datasize, u16 sender_peer_id);
197         // Returns true if something was received
198         bool AsyncProcessPacket();
199         bool AsyncProcessData();
200         void Send(u16 channelnum, SharedBuffer<u8> data, bool reliable);
201
202         // Pops out a packet from the packet queue
203         //IncomingPacket getPacket();
204
205         void groundAction(u8 action, v3s16 nodepos_undersurface,
206                         v3s16 nodepos_oversurface, u16 item);
207         void clickActiveObject(u8 button, u16 id, u16 item_i);
208
209         void sendSignNodeText(v3s16 p, std::string text);
210         void sendInventoryAction(InventoryAction *a);
211         void sendChatMessage(const std::wstring &message);
212         void sendChangePassword(const std::wstring oldpassword,
213                 const std::wstring newpassword);
214         void sendDamage(u8 damage);
215         void sendRespawn();
216         
217         // locks envlock
218         void removeNode(v3s16 p);
219         // locks envlock
220         void addNode(v3s16 p, MapNode n);
221         
222         void updateCamera(v3f pos, v3f dir, f32 fov);
223         
224         void renderPostFx();
225         
226         // Returns InvalidPositionException if not found
227         MapNode getNode(v3s16 p);
228         // Wrapper to Map
229         NodeMetadata* getNodeMetadata(v3s16 p);
230
231         LocalPlayer* getLocalPlayer();
232
233         void setPlayerControl(PlayerControl &control);
234
235         void selectPlayerItem(u16 item);
236
237         // Returns true if the inventory of the local player has been
238         // updated from the server. If it is true, it is set to false.
239         bool getLocalInventoryUpdated();
240         // Copies the inventory of the local player to parameter
241         void getLocalInventory(Inventory &dst);
242         
243         InventoryContext *getInventoryContext();
244
245         Inventory* getInventory(InventoryContext *c, std::string id);
246         void inventoryAction(InventoryAction *a);
247
248         // Gets closest object pointed by the shootline
249         // Returns NULL if not found
250         ClientActiveObject * getSelectedActiveObject(
251                         f32 max_d,
252                         v3f from_pos_f_on_map,
253                         core::line3d<f32> shootline_on_map
254         );
255
256         // Prints a line or two of info
257         void printDebugInfo(std::ostream &os);
258
259         u32 getDayNightRatio();
260
261         u16 getHP();
262
263         void setTempMod(v3s16 p, NodeMod mod);
264         void clearTempMod(v3s16 p);
265
266         float getAvgRtt()
267         {
268                 try{
269                         return m_con.GetPeerAvgRTT(PEER_ID_SERVER);
270                 } catch(con::PeerNotFoundException){
271                         return 1337;
272                 }
273         }
274
275         bool getChatMessage(std::wstring &message)
276         {
277                 if(m_chat_queue.size() == 0)
278                         return false;
279                 message = m_chat_queue.pop_front();
280                 return true;
281         }
282
283         void addChatMessage(const std::wstring &message)
284         {
285                 if (message[0] == L'/') {
286                         m_chat_queue.push_back(
287                                 (std::wstring)L"issued command: "+message);
288                         return;
289                 }
290
291                 //JMutexAutoLock envlock(m_env_mutex); //bulk comment-out
292                 LocalPlayer *player = m_env.getLocalPlayer();
293                 assert(player != NULL);
294                 std::wstring name = narrow_to_wide(player->getName());
295                 m_chat_queue.push_back(
296                                 (std::wstring)L"<"+name+L"> "+message);
297         }
298
299         u64 getMapSeed(){ return m_map_seed; }
300
301         void addUpdateMeshTask(v3s16 blockpos, bool ack_to_server=false);
302         // Including blocks at appropriate edges
303         void addUpdateMeshTaskWithEdge(v3s16 blockpos, bool ack_to_server=false);
304
305         // Get event from queue. CE_NONE is returned if queue is empty.
306         ClientEvent getClientEvent();
307         
308         bool accessDenied()
309         { return m_access_denied; }
310
311         std::wstring accessDeniedReason()
312         { return m_access_denied_reason; }
313
314         float textureReceiveProgress()
315         { return m_texture_receive_progress; }
316
317         bool texturesReceived()
318         { return m_textures_received; }
319         bool tooldefReceived()
320         { return m_tooldef_received; }
321         bool nodedefReceived()
322         { return m_nodedef_received; }
323         
324         float getRTT(void);
325
326         // IGameDef interface
327         // Under envlock
328         virtual IToolDefManager* getToolDefManager();
329         virtual INodeDefManager* getNodeDefManager();
330         virtual ITextureSource* getTextureSource();
331
332 private:
333         
334         // Virtual methods from con::PeerHandler
335         void peerAdded(con::Peer *peer);
336         void deletingPeer(con::Peer *peer, bool timeout);
337         
338         void ReceiveAll();
339         void Receive();
340         
341         void sendPlayerPos();
342         // This sends the player's current name etc to the server
343         void sendPlayerInfo();
344         // Send the item number 'item' as player item to the server
345         void sendPlayerItem(u16 item);
346         
347         float m_packetcounter_timer;
348         float m_connection_reinit_timer;
349         float m_avg_rtt_timer;
350         float m_playerpos_send_timer;
351         float m_ignore_damage_timer; // Used after server moves player
352         IntervalLimiter m_map_timer_and_unload_interval;
353
354         IWritableTextureSource *m_tsrc;
355         IWritableToolDefManager *m_tooldef;
356         IWritableNodeDefManager *m_nodedef;
357         MeshUpdateThread m_mesh_update_thread;
358         ClientEnvironment m_env;
359         con::Connection m_con;
360         IrrlichtDevice *m_device;
361         // Server serialization version
362         u8 m_server_ser_ver;
363         // This is behind m_env_mutex.
364         bool m_inventory_updated;
365         core::map<v3s16, bool> m_active_blocks;
366         PacketCounter m_packetcounter;
367         // Received from the server. 0-23999
368         u32 m_time_of_day;
369         // 0 <= m_daynight_i < DAYNIGHT_CACHE_COUNT
370         //s32 m_daynight_i;
371         //u32 m_daynight_ratio;
372         Queue<std::wstring> m_chat_queue;
373         // The seed returned by the server in TOCLIENT_INIT is stored here
374         u64 m_map_seed;
375         std::string m_password;
376         bool m_access_denied;
377         std::wstring m_access_denied_reason;
378         InventoryContext m_inventory_context;
379         Queue<ClientEvent> m_client_event_queue;
380         float m_texture_receive_progress;
381         bool m_textures_received;
382         bool m_tooldef_received;
383         bool m_nodedef_received;
384         friend class FarMesh;
385 };
386
387 #endif // !SERVER
388
389 #endif // !CLIENT_HEADER
390