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