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