]> git.lizzy.rs Git - minetest.git/blob - src/client.h
7cbfadd50fd36f98d636388c12b8b572c0c9868b
[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 "network/connection.h"
24 #include "clientenvironment.h"
25 #include "irrlichttypes_extrabloated.h"
26 #include "threading/mutex.h"
27 #include <ostream>
28 #include <map>
29 #include <set>
30 #include <vector>
31 #include "clientobject.h"
32 #include "gamedef.h"
33 #include "inventorymanager.h"
34 #include "localplayer.h"
35 #include "hud.h"
36 #include "particles.h"
37 #include "mapnode.h"
38 #include "tileanimation.h"
39 #include "mesh_generator_thread.h"
40
41 struct MeshMakeData;
42 class MapBlockMesh;
43 class IWritableTextureSource;
44 class IWritableShaderSource;
45 class IWritableItemDefManager;
46 class IWritableNodeDefManager;
47 //class IWritableCraftDefManager;
48 class ClientMediaDownloader;
49 struct MapDrawControl;
50 class MtEventManager;
51 struct PointedThing;
52 class MapDatabase;
53 class Minimap;
54 struct MinimapMapblock;
55 class Camera;
56 class NetworkPacket;
57
58 enum LocalClientState {
59         LC_Created,
60         LC_Init,
61         LC_Ready
62 };
63
64 enum ClientEventType
65 {
66         CE_NONE,
67         CE_PLAYER_DAMAGE,
68         CE_PLAYER_FORCE_MOVE,
69         CE_DEATHSCREEN,
70         CE_SHOW_FORMSPEC,
71         CE_SHOW_LOCAL_FORMSPEC,
72         CE_SPAWN_PARTICLE,
73         CE_ADD_PARTICLESPAWNER,
74         CE_DELETE_PARTICLESPAWNER,
75         CE_HUDADD,
76         CE_HUDRM,
77         CE_HUDCHANGE,
78         CE_SET_SKY,
79         CE_OVERRIDE_DAY_NIGHT_RATIO,
80         CE_CLOUD_PARAMS,
81 };
82
83 struct ClientEvent
84 {
85         ClientEventType type;
86         union{
87                 //struct{
88                 //} none;
89                 struct{
90                         u8 amount;
91                 } player_damage;
92                 struct{
93                         f32 pitch;
94                         f32 yaw;
95                 } player_force_move;
96                 struct{
97                         bool set_camera_point_target;
98                         f32 camera_point_target_x;
99                         f32 camera_point_target_y;
100                         f32 camera_point_target_z;
101                 } deathscreen;
102                 struct{
103                         std::string *formspec;
104                         std::string *formname;
105                 } show_formspec;
106                 //struct{
107                 //} textures_updated;
108                 struct{
109                         v3f *pos;
110                         v3f *vel;
111                         v3f *acc;
112                         f32 expirationtime;
113                         f32 size;
114                         bool collisiondetection;
115                         bool collision_removal;
116                         bool vertical;
117                         std::string *texture;
118                         struct TileAnimationParams animation;
119                         u8 glow;
120                 } spawn_particle;
121                 struct{
122                         u16 amount;
123                         f32 spawntime;
124                         v3f *minpos;
125                         v3f *maxpos;
126                         v3f *minvel;
127                         v3f *maxvel;
128                         v3f *minacc;
129                         v3f *maxacc;
130                         f32 minexptime;
131                         f32 maxexptime;
132                         f32 minsize;
133                         f32 maxsize;
134                         bool collisiondetection;
135                         bool collision_removal;
136                         u16 attached_id;
137                         bool vertical;
138                         std::string *texture;
139                         u32 id;
140                         struct TileAnimationParams animation;
141                         u8 glow;
142                 } add_particlespawner;
143                 struct{
144                         u32 id;
145                 } delete_particlespawner;
146                 struct{
147                         u32 id;
148                         u8 type;
149                         v2f *pos;
150                         std::string *name;
151                         v2f *scale;
152                         std::string *text;
153                         u32 number;
154                         u32 item;
155                         u32 dir;
156                         v2f *align;
157                         v2f *offset;
158                         v3f *world_pos;
159                         v2s32 * size;
160                 } hudadd;
161                 struct{
162                         u32 id;
163                 } hudrm;
164                 struct{
165                         u32 id;
166                         HudElementStat stat;
167                         v2f *v2fdata;
168                         std::string *sdata;
169                         u32 data;
170                         v3f *v3fdata;
171                         v2s32 * v2s32data;
172                 } hudchange;
173                 struct{
174                         video::SColor *bgcolor;
175                         std::string *type;
176                         std::vector<std::string> *params;
177                 } set_sky;
178                 struct{
179                         bool do_override;
180                         float ratio_f;
181                 } override_day_night_ratio;
182                 struct {
183                         f32 density;
184                         u32 color_bright;
185                         u32 color_ambient;
186                         f32 height;
187                         f32 thickness;
188                         f32 speed_x;
189                         f32 speed_y;
190                 } cloud_params;
191         };
192 };
193
194 /*
195         Packet counter
196 */
197
198 class PacketCounter
199 {
200 public:
201         PacketCounter()
202         {
203         }
204
205         void add(u16 command)
206         {
207                 std::map<u16, u16>::iterator n = m_packets.find(command);
208                 if(n == m_packets.end())
209                 {
210                         m_packets[command] = 1;
211                 }
212                 else
213                 {
214                         n->second++;
215                 }
216         }
217
218         void clear()
219         {
220                 for(std::map<u16, u16>::iterator
221                                 i = m_packets.begin();
222                                 i != m_packets.end(); ++i)
223                 {
224                         i->second = 0;
225                 }
226         }
227
228         void print(std::ostream &o)
229         {
230                 for(std::map<u16, u16>::iterator
231                                 i = m_packets.begin();
232                                 i != m_packets.end(); ++i)
233                 {
234                         o<<"cmd "<<i->first
235                                         <<" count "<<i->second
236                                         <<std::endl;
237                 }
238         }
239
240 private:
241         // command, count
242         std::map<u16, u16> m_packets;
243 };
244
245 class ClientScripting;
246 struct GameUIFlags;
247
248 class Client : public con::PeerHandler, public InventoryManager, public IGameDef
249 {
250 public:
251         /*
252                 NOTE: Nothing is thread-safe here.
253         */
254
255         Client(
256                         IrrlichtDevice *device,
257                         const char *playername,
258                         const std::string &password,
259                         MapDrawControl &control,
260                         IWritableTextureSource *tsrc,
261                         IWritableShaderSource *shsrc,
262                         IWritableItemDefManager *itemdef,
263                         IWritableNodeDefManager *nodedef,
264                         ISoundManager *sound,
265                         MtEventManager *event,
266                         bool ipv6,
267                         GameUIFlags *game_ui_flags
268         );
269
270         ~Client();
271
272         void initMods();
273
274         /*
275          request all threads managed by client to be stopped
276          */
277         void Stop();
278
279
280         bool isShutdown();
281
282         /*
283                 The name of the local player should already be set when
284                 calling this, as it is sent in the initialization.
285         */
286         void connect(Address address,
287                         const std::string &address_name,
288                         bool is_local_server);
289
290         /*
291                 Stuff that references the environment is valid only as
292                 long as this is not called. (eg. Players)
293                 If this throws a PeerNotFoundException, the connection has
294                 timed out.
295         */
296         void step(float dtime);
297
298         /*
299          * Command Handlers
300          */
301
302         void handleCommand(NetworkPacket* pkt);
303
304         void handleCommand_Null(NetworkPacket* pkt) {};
305         void handleCommand_Deprecated(NetworkPacket* pkt);
306         void handleCommand_Hello(NetworkPacket* pkt);
307         void handleCommand_AuthAccept(NetworkPacket* pkt);
308         void handleCommand_AcceptSudoMode(NetworkPacket* pkt);
309         void handleCommand_DenySudoMode(NetworkPacket* pkt);
310         void handleCommand_InitLegacy(NetworkPacket* pkt);
311         void handleCommand_AccessDenied(NetworkPacket* pkt);
312         void handleCommand_RemoveNode(NetworkPacket* pkt);
313         void handleCommand_AddNode(NetworkPacket* pkt);
314         void handleCommand_BlockData(NetworkPacket* pkt);
315         void handleCommand_Inventory(NetworkPacket* pkt);
316         void handleCommand_TimeOfDay(NetworkPacket* pkt);
317         void handleCommand_ChatMessage(NetworkPacket* pkt);
318         void handleCommand_ActiveObjectRemoveAdd(NetworkPacket* pkt);
319         void handleCommand_ActiveObjectMessages(NetworkPacket* pkt);
320         void handleCommand_Movement(NetworkPacket* pkt);
321         void handleCommand_HP(NetworkPacket* pkt);
322         void handleCommand_Breath(NetworkPacket* pkt);
323         void handleCommand_MovePlayer(NetworkPacket* pkt);
324         void handleCommand_DeathScreen(NetworkPacket* pkt);
325         void handleCommand_AnnounceMedia(NetworkPacket* pkt);
326         void handleCommand_Media(NetworkPacket* pkt);
327         void handleCommand_NodeDef(NetworkPacket* pkt);
328         void handleCommand_ItemDef(NetworkPacket* pkt);
329         void handleCommand_PlaySound(NetworkPacket* pkt);
330         void handleCommand_StopSound(NetworkPacket* pkt);
331         void handleCommand_Privileges(NetworkPacket* pkt);
332         void handleCommand_InventoryFormSpec(NetworkPacket* pkt);
333         void handleCommand_DetachedInventory(NetworkPacket* pkt);
334         void handleCommand_ShowFormSpec(NetworkPacket* pkt);
335         void handleCommand_SpawnParticle(NetworkPacket* pkt);
336         void handleCommand_AddParticleSpawner(NetworkPacket* pkt);
337         void handleCommand_DeleteParticleSpawner(NetworkPacket* pkt);
338         void handleCommand_HudAdd(NetworkPacket* pkt);
339         void handleCommand_HudRemove(NetworkPacket* pkt);
340         void handleCommand_HudChange(NetworkPacket* pkt);
341         void handleCommand_HudSetFlags(NetworkPacket* pkt);
342         void handleCommand_HudSetParam(NetworkPacket* pkt);
343         void handleCommand_HudSetSky(NetworkPacket* pkt);
344         void handleCommand_CloudParams(NetworkPacket* pkt);
345         void handleCommand_OverrideDayNightRatio(NetworkPacket* pkt);
346         void handleCommand_LocalPlayerAnimations(NetworkPacket* pkt);
347         void handleCommand_EyeOffset(NetworkPacket* pkt);
348         void handleCommand_SrpBytesSandB(NetworkPacket* pkt);
349
350         void ProcessData(NetworkPacket *pkt);
351
352         void Send(NetworkPacket* pkt);
353
354         void interact(u8 action, const PointedThing& pointed);
355
356         void sendNodemetaFields(v3s16 p, const std::string &formname,
357                 const StringMap &fields);
358         void sendInventoryFields(const std::string &formname,
359                 const StringMap &fields);
360         void sendInventoryAction(InventoryAction *a);
361         void sendChatMessage(const std::wstring &message);
362         void sendChangePassword(const std::string &oldpassword,
363                 const std::string &newpassword);
364         void sendDamage(u8 damage);
365         void sendBreath(u16 breath);
366         void sendRespawn();
367         void sendReady();
368
369         ClientEnvironment& getEnv() { return m_env; }
370         ITextureSource *tsrc() { return getTextureSource(); }
371         ISoundManager *sound() { return getSoundManager(); }
372         static const std::string &getBuiltinLuaPath();
373         static const std::string &getClientModsLuaPath();
374
375         virtual const std::vector<ModSpec> &getMods() const;
376         virtual const ModSpec* getModSpec(const std::string &modname) const;
377
378         // Causes urgent mesh updates (unlike Map::add/removeNodeWithEvent)
379         void removeNode(v3s16 p);
380         MapNode getNode(v3s16 p, bool *is_valid_position);
381         void addNode(v3s16 p, MapNode n, bool remove_metadata = true);
382
383         void setPlayerControl(PlayerControl &control);
384
385         void selectPlayerItem(u16 item);
386         u16 getPlayerItem() const
387         { return m_playeritem; }
388
389         // Returns true if the inventory of the local player has been
390         // updated from the server. If it is true, it is set to false.
391         bool getLocalInventoryUpdated();
392         // Copies the inventory of the local player to parameter
393         void getLocalInventory(Inventory &dst);
394
395         /* InventoryManager interface */
396         Inventory* getInventory(const InventoryLocation &loc);
397         void inventoryAction(InventoryAction *a);
398
399         const std::list<std::string> &getConnectedPlayerNames()
400         {
401                 return m_env.getPlayerNames();
402         }
403
404         float getAnimationTime();
405
406         int getCrackLevel();
407         v3s16 getCrackPos();
408         void setCrack(int level, v3s16 pos);
409
410         u16 getHP();
411
412         bool checkPrivilege(const std::string &priv) const
413         { return (m_privileges.count(priv) != 0); }
414
415         bool getChatMessage(std::wstring &message);
416         void typeChatMessage(const std::wstring& message);
417
418         u64 getMapSeed(){ return m_map_seed; }
419
420         void addUpdateMeshTask(v3s16 blockpos, bool ack_to_server=false, bool urgent=false);
421         // Including blocks at appropriate edges
422         void addUpdateMeshTaskWithEdge(v3s16 blockpos, bool ack_to_server=false, bool urgent=false);
423         void addUpdateMeshTaskForNode(v3s16 nodepos, bool ack_to_server=false, bool urgent=false);
424
425         void updateCameraOffset(v3s16 camera_offset)
426         { m_mesh_update_thread.m_camera_offset = camera_offset; }
427
428         bool hasClientEvents() const { return !m_client_event_queue.empty(); }
429         // Get event from queue. If queue is empty, it triggers an assertion failure.
430         ClientEvent getClientEvent();
431
432         bool accessDenied() const { return m_access_denied; }
433
434         bool reconnectRequested() const { return m_access_denied_reconnect; }
435
436         void setFatalError(const std::string &reason)
437         {
438                 m_access_denied = true;
439                 m_access_denied_reason = reason;
440         }
441
442         // Renaming accessDeniedReason to better name could be good as it's used to
443         // disconnect client when CSM failed.
444         const std::string &accessDeniedReason() const { return m_access_denied_reason; }
445
446         bool itemdefReceived()
447         { return m_itemdef_received; }
448         bool nodedefReceived()
449         { return m_nodedef_received; }
450         bool mediaReceived()
451         { return m_media_downloader == NULL; }
452
453         u8 getProtoVersion()
454         { return m_proto_ver; }
455
456         bool connectedToServer()
457         { return m_con.Connected(); }
458
459         float mediaReceiveProgress();
460
461         void afterContentReceived(IrrlichtDevice *device);
462
463         float getRTT();
464         float getCurRate();
465
466         Minimap* getMinimap() { return m_minimap; }
467         void setCamera(Camera* camera) { m_camera = camera; }
468
469         Camera* getCamera ()
470         { return m_camera; }
471
472         bool shouldShowMinimap() const;
473
474         // IGameDef interface
475         virtual IItemDefManager* getItemDefManager();
476         virtual INodeDefManager* getNodeDefManager();
477         virtual ICraftDefManager* getCraftDefManager();
478         ITextureSource* getTextureSource();
479         virtual IShaderSource* getShaderSource();
480         IShaderSource *shsrc() { return getShaderSource(); }
481         scene::ISceneManager* getSceneManager();
482         virtual u16 allocateUnknownNodeId(const std::string &name);
483         virtual ISoundManager* getSoundManager();
484         virtual MtEventManager* getEventManager();
485         virtual ParticleManager* getParticleManager();
486         bool checkLocalPrivilege(const std::string &priv)
487         { return checkPrivilege(priv); }
488         virtual scene::IAnimatedMesh* getMesh(const std::string &filename);
489
490         virtual std::string getModStoragePath() const;
491         virtual bool registerModStorage(ModMetadata *meta);
492         virtual void unregisterModStorage(const std::string &name);
493
494         // The following set of functions is used by ClientMediaDownloader
495         // Insert a media file appropriately into the appropriate manager
496         bool loadMedia(const std::string &data, const std::string &filename);
497         // Send a request for conventional media transfer
498         void request_media(const std::vector<std::string> &file_requests);
499
500         LocalClientState getState() { return m_state; }
501
502         void makeScreenshot(IrrlichtDevice *device);
503
504         inline void pushToChatQueue(const std::wstring &input)
505         {
506                 m_chat_queue.push(input);
507         }
508
509         ClientScripting *getScript() { return m_script; }
510         const bool moddingEnabled() const { return m_modding_enabled; }
511
512         inline void pushToEventQueue(const ClientEvent &event)
513         {
514                 m_client_event_queue.push(event);
515         }
516
517         void showGameChat(const bool show = true);
518         void showGameHud(const bool show = true);
519         void showMinimap(const bool show = true);
520         void showProfiler(const bool show = true);
521         void showGameFog(const bool show = true);
522         void showGameDebug(const bool show = true);
523
524         IrrlichtDevice *getDevice() const { return m_device; }
525
526 private:
527
528         // Virtual methods from con::PeerHandler
529         void peerAdded(con::Peer *peer);
530         void deletingPeer(con::Peer *peer, bool timeout);
531
532         void initLocalMapSaving(const Address &address,
533                         const std::string &hostname,
534                         bool is_local_server);
535
536         void ReceiveAll();
537         void Receive();
538
539         void sendPlayerPos();
540         // Send the item number 'item' as player item to the server
541         void sendPlayerItem(u16 item);
542
543         void deleteAuthData();
544         // helper method shared with clientpackethandler
545         static AuthMechanism choseAuthMech(const u32 mechs);
546
547         void sendLegacyInit(const char* playerName, const char* playerPassword);
548         void sendInit(const std::string &playerName);
549         void startAuth(AuthMechanism chosen_auth_mechanism);
550         void sendDeletedBlocks(std::vector<v3s16> &blocks);
551         void sendGotBlocks(v3s16 block);
552         void sendRemovedSounds(std::vector<s32> &soundList);
553
554         // Helper function
555         inline std::string getPlayerName()
556         { return m_env.getLocalPlayer()->getName(); }
557
558         float m_packetcounter_timer;
559         float m_connection_reinit_timer;
560         float m_avg_rtt_timer;
561         float m_playerpos_send_timer;
562         float m_ignore_damage_timer; // Used after server moves player
563         IntervalLimiter m_map_timer_and_unload_interval;
564
565         IWritableTextureSource *m_tsrc;
566         IWritableShaderSource *m_shsrc;
567         IWritableItemDefManager *m_itemdef;
568         IWritableNodeDefManager *m_nodedef;
569         ISoundManager *m_sound;
570         MtEventManager *m_event;
571
572
573         MeshUpdateThread m_mesh_update_thread;
574         ClientEnvironment m_env;
575         ParticleManager m_particle_manager;
576         con::Connection m_con;
577         IrrlichtDevice *m_device;
578         Camera *m_camera;
579         Minimap *m_minimap;
580         bool m_minimap_disabled_by_server;
581         // Server serialization version
582         u8 m_server_ser_ver;
583
584         // Used version of the protocol with server
585         // Values smaller than 25 only mean they are smaller than 25,
586         // and aren't accurate. We simply just don't know, because
587         // the server didn't send the version back then.
588         // If 0, server init hasn't been received yet.
589         u8 m_proto_ver;
590
591         u16 m_playeritem;
592         bool m_inventory_updated;
593         Inventory *m_inventory_from_server;
594         float m_inventory_from_server_age;
595         PacketCounter m_packetcounter;
596         // Block mesh animation parameters
597         float m_animation_time;
598         int m_crack_level;
599         v3s16 m_crack_pos;
600         // 0 <= m_daynight_i < DAYNIGHT_CACHE_COUNT
601         //s32 m_daynight_i;
602         //u32 m_daynight_ratio;
603         std::queue<std::wstring> m_chat_queue;
604
605         // The authentication methods we can use to enter sudo mode (=change password)
606         u32 m_sudo_auth_methods;
607
608         // The seed returned by the server in TOCLIENT_INIT is stored here
609         u64 m_map_seed;
610
611         // Auth data
612         std::string m_playername;
613         std::string m_password;
614         // If set, this will be sent (and cleared) upon a TOCLIENT_ACCEPT_SUDO_MODE
615         std::string m_new_password;
616         // Usable by auth mechanisms.
617         AuthMechanism m_chosen_auth_mech;
618         void * m_auth_data;
619
620
621         bool m_access_denied;
622         bool m_access_denied_reconnect;
623         std::string m_access_denied_reason;
624         std::queue<ClientEvent> m_client_event_queue;
625         bool m_itemdef_received;
626         bool m_nodedef_received;
627         ClientMediaDownloader *m_media_downloader;
628
629         // time_of_day speed approximation for old protocol
630         bool m_time_of_day_set;
631         float m_last_time_of_day_f;
632         float m_time_of_day_update_timer;
633
634         // An interval for generally sending object positions and stuff
635         float m_recommended_send_interval;
636
637         // Sounds
638         float m_removed_sounds_check_timer;
639         // Mapping from server sound ids to our sound ids
640         UNORDERED_MAP<s32, int> m_sounds_server_to_client;
641         // And the other way!
642         UNORDERED_MAP<int, s32> m_sounds_client_to_server;
643         // And relations to objects
644         UNORDERED_MAP<int, u16> m_sounds_to_objects;
645
646         // Privileges
647         UNORDERED_SET<std::string> m_privileges;
648
649         // Detached inventories
650         // key = name
651         UNORDERED_MAP<std::string, Inventory*> m_detached_inventories;
652
653         // Storage for mesh data for creating multiple instances of the same mesh
654         StringMap m_mesh_data;
655
656         // own state
657         LocalClientState m_state;
658
659         // Used for saving server map to disk client-side
660         MapDatabase *m_localdb;
661         IntervalLimiter m_localdb_save_interval;
662         u16 m_cache_save_interval;
663
664         ClientScripting *m_script;
665         bool m_modding_enabled;
666         UNORDERED_MAP<std::string, ModMetadata *> m_mod_storages;
667         float m_mod_storage_save_timer;
668         GameUIFlags *m_game_ui_flags;
669
670         bool m_shutdown;
671         DISABLE_CLASS_COPY(Client);
672 };
673
674 #endif // !CLIENT_HEADER