11f27e9bdab97d1faee30e029d2704c2822f5c76
[oweals/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 #pragma once
21
22 #include "clientenvironment.h"
23 #include "irrlichttypes_extrabloated.h"
24 #include <ostream>
25 #include <map>
26 #include <set>
27 #include <vector>
28 #include <unordered_set>
29 #include "clientobject.h"
30 #include "gamedef.h"
31 #include "inventorymanager.h"
32 #include "localplayer.h"
33 #include "hud.h"
34 #include "particles.h"
35 #include "mapnode.h"
36 #include "tileanimation.h"
37 #include "mesh_generator_thread.h"
38 #include "network/address.h"
39 #include "network/peerhandler.h"
40 #include <fstream>
41
42 #define CLIENT_CHAT_MESSAGE_LIMIT_PER_10S 10.0f
43
44 struct ClientEvent;
45 struct MeshMakeData;
46 struct ChatMessage;
47 class MapBlockMesh;
48 class IWritableTextureSource;
49 class IWritableShaderSource;
50 class IWritableItemDefManager;
51 class IWritableNodeDefManager;
52 //class IWritableCraftDefManager;
53 class ClientMediaDownloader;
54 struct MapDrawControl;
55 class ModChannelMgr;
56 class MtEventManager;
57 struct PointedThing;
58 class MapDatabase;
59 class Minimap;
60 struct MinimapMapblock;
61 class Camera;
62 class NetworkPacket;
63 namespace con {
64 class Connection;
65 }
66
67 enum LocalClientState {
68         LC_Created,
69         LC_Init,
70         LC_Ready
71 };
72
73 /*
74         Packet counter
75 */
76
77 class PacketCounter
78 {
79 public:
80         PacketCounter() = default;
81
82         void add(u16 command)
83         {
84                 std::map<u16, u16>::iterator n = m_packets.find(command);
85                 if(n == m_packets.end())
86                 {
87                         m_packets[command] = 1;
88                 }
89                 else
90                 {
91                         n->second++;
92                 }
93         }
94
95         void clear()
96         {
97                 for (auto &m_packet : m_packets) {
98                         m_packet.second = 0;
99                 }
100         }
101
102         void print(std::ostream &o)
103         {
104                 for (const auto &m_packet : m_packets) {
105                         o << "cmd "<< m_packet.first <<" count "<< m_packet.second << std::endl;
106                 }
107         }
108
109 private:
110         // command, count
111         std::map<u16, u16> m_packets;
112 };
113
114 class ClientScripting;
115 class GameUI;
116
117 class Client : public con::PeerHandler, public InventoryManager, public IGameDef
118 {
119 public:
120         /*
121                 NOTE: Nothing is thread-safe here.
122         */
123
124         Client(
125                         const char *playername,
126                         const std::string &password,
127                         const std::string &address_name,
128                         MapDrawControl &control,
129                         IWritableTextureSource *tsrc,
130                         IWritableShaderSource *shsrc,
131                         IWritableItemDefManager *itemdef,
132                         IWritableNodeDefManager *nodedef,
133                         ISoundManager *sound,
134                         MtEventManager *event,
135                         bool ipv6,
136                         GameUI *game_ui
137         );
138
139         ~Client();
140         DISABLE_CLASS_COPY(Client);
141
142         // Load local mods into memory
143         void loadBuiltin();
144         void scanModSubfolder(const std::string &mod_name, const std::string &mod_path,
145                                 std::string mod_subpath);
146         inline void scanModIntoMemory(const std::string &mod_name, const std::string &mod_path)
147         {
148                 scanModSubfolder(mod_name, mod_path, "");
149         }
150
151         /*
152          request all threads managed by client to be stopped
153          */
154         void Stop();
155
156
157         bool isShutdown();
158
159         /*
160                 The name of the local player should already be set when
161                 calling this, as it is sent in the initialization.
162         */
163         void connect(Address address, bool is_local_server);
164
165         /*
166                 Stuff that references the environment is valid only as
167                 long as this is not called. (eg. Players)
168                 If this throws a PeerNotFoundException, the connection has
169                 timed out.
170         */
171         void step(float dtime);
172
173         /*
174          * Command Handlers
175          */
176
177         void handleCommand(NetworkPacket* pkt);
178
179         void handleCommand_Null(NetworkPacket* pkt) {};
180         void handleCommand_Deprecated(NetworkPacket* pkt);
181         void handleCommand_Hello(NetworkPacket* pkt);
182         void handleCommand_AuthAccept(NetworkPacket* pkt);
183         void handleCommand_AcceptSudoMode(NetworkPacket* pkt);
184         void handleCommand_DenySudoMode(NetworkPacket* pkt);
185         void handleCommand_AccessDenied(NetworkPacket* pkt);
186         void handleCommand_RemoveNode(NetworkPacket* pkt);
187         void handleCommand_AddNode(NetworkPacket* pkt);
188         void handleCommand_BlockData(NetworkPacket* pkt);
189         void handleCommand_Inventory(NetworkPacket* pkt);
190         void handleCommand_TimeOfDay(NetworkPacket* pkt);
191         void handleCommand_ChatMessageOld(NetworkPacket *pkt);
192         void handleCommand_ChatMessage(NetworkPacket *pkt);
193         void handleCommand_ActiveObjectRemoveAdd(NetworkPacket* pkt);
194         void handleCommand_ActiveObjectMessages(NetworkPacket* pkt);
195         void handleCommand_Movement(NetworkPacket* pkt);
196         void handleCommand_HP(NetworkPacket* pkt);
197         void handleCommand_Breath(NetworkPacket* pkt);
198         void handleCommand_MovePlayer(NetworkPacket* pkt);
199         void handleCommand_DeathScreen(NetworkPacket* pkt);
200         void handleCommand_AnnounceMedia(NetworkPacket* pkt);
201         void handleCommand_Media(NetworkPacket* pkt);
202         void handleCommand_NodeDef(NetworkPacket* pkt);
203         void handleCommand_ItemDef(NetworkPacket* pkt);
204         void handleCommand_PlaySound(NetworkPacket* pkt);
205         void handleCommand_StopSound(NetworkPacket* pkt);
206         void handleCommand_FadeSound(NetworkPacket *pkt);
207         void handleCommand_Privileges(NetworkPacket* pkt);
208         void handleCommand_InventoryFormSpec(NetworkPacket* pkt);
209         void handleCommand_DetachedInventory(NetworkPacket* pkt);
210         void handleCommand_ShowFormSpec(NetworkPacket* pkt);
211         void handleCommand_SpawnParticle(NetworkPacket* pkt);
212         void handleCommand_AddParticleSpawner(NetworkPacket* pkt);
213         void handleCommand_DeleteParticleSpawner(NetworkPacket* pkt);
214         void handleCommand_HudAdd(NetworkPacket* pkt);
215         void handleCommand_HudRemove(NetworkPacket* pkt);
216         void handleCommand_HudChange(NetworkPacket* pkt);
217         void handleCommand_HudSetFlags(NetworkPacket* pkt);
218         void handleCommand_HudSetParam(NetworkPacket* pkt);
219         void handleCommand_HudSetSky(NetworkPacket* pkt);
220         void handleCommand_CloudParams(NetworkPacket* pkt);
221         void handleCommand_OverrideDayNightRatio(NetworkPacket* pkt);
222         void handleCommand_LocalPlayerAnimations(NetworkPacket* pkt);
223         void handleCommand_EyeOffset(NetworkPacket* pkt);
224         void handleCommand_UpdatePlayerList(NetworkPacket* pkt);
225         void handleCommand_ModChannelMsg(NetworkPacket *pkt);
226         void handleCommand_ModChannelSignal(NetworkPacket *pkt);
227         void handleCommand_SrpBytesSandB(NetworkPacket* pkt);
228         void handleCommand_CSMFlavourLimits(NetworkPacket *pkt);
229
230         void ProcessData(NetworkPacket *pkt);
231
232         void Send(NetworkPacket* pkt);
233
234         void interact(u8 action, const PointedThing& pointed);
235
236         void sendNodemetaFields(v3s16 p, const std::string &formname,
237                 const StringMap &fields);
238         void sendInventoryFields(const std::string &formname,
239                 const StringMap &fields);
240         void sendInventoryAction(InventoryAction *a);
241         void sendChatMessage(const std::wstring &message);
242         void clearOutChatQueue();
243         void sendChangePassword(const std::string &oldpassword,
244                 const std::string &newpassword);
245         void sendDamage(u8 damage);
246         void sendRespawn();
247         void sendReady();
248
249         ClientEnvironment& getEnv() { return m_env; }
250         ITextureSource *tsrc() { return getTextureSource(); }
251         ISoundManager *sound() { return getSoundManager(); }
252         static const std::string &getBuiltinLuaPath();
253         static const std::string &getClientModsLuaPath();
254
255         virtual const std::vector<ModSpec> &getMods() const;
256         virtual const ModSpec* getModSpec(const std::string &modname) const;
257
258         // Causes urgent mesh updates (unlike Map::add/removeNodeWithEvent)
259         void removeNode(v3s16 p);
260
261         /**
262          * Helper function for Client Side Modding
263          * Flavour is applied there, this should not be used for core engine
264          * @param p
265          * @param is_valid_position
266          * @return
267          */
268         MapNode getNode(v3s16 p, bool *is_valid_position);
269         void addNode(v3s16 p, MapNode n, bool remove_metadata = true);
270
271         void setPlayerControl(PlayerControl &control);
272
273         void selectPlayerItem(u16 item);
274         u16 getPlayerItem() const
275         { return m_playeritem; }
276
277         // Returns true if the inventory of the local player has been
278         // updated from the server. If it is true, it is set to false.
279         bool getLocalInventoryUpdated();
280         // Copies the inventory of the local player to parameter
281         void getLocalInventory(Inventory &dst);
282
283         /* InventoryManager interface */
284         Inventory* getInventory(const InventoryLocation &loc);
285         void inventoryAction(InventoryAction *a);
286
287         const std::list<std::string> &getConnectedPlayerNames()
288         {
289                 return m_env.getPlayerNames();
290         }
291
292         float getAnimationTime();
293
294         int getCrackLevel();
295         v3s16 getCrackPos();
296         void setCrack(int level, v3s16 pos);
297
298         u16 getHP();
299
300         bool checkPrivilege(const std::string &priv) const
301         { return (m_privileges.count(priv) != 0); }
302
303         const std::unordered_set<std::string> &getPrivilegeList() const
304         { return m_privileges; }
305
306         bool getChatMessage(std::wstring &message);
307         void typeChatMessage(const std::wstring& message);
308
309         u64 getMapSeed(){ return m_map_seed; }
310
311         void addUpdateMeshTask(v3s16 blockpos, bool ack_to_server=false, bool urgent=false);
312         // Including blocks at appropriate edges
313         void addUpdateMeshTaskWithEdge(v3s16 blockpos, bool ack_to_server=false, bool urgent=false);
314         void addUpdateMeshTaskForNode(v3s16 nodepos, bool ack_to_server=false, bool urgent=false);
315
316         void updateCameraOffset(v3s16 camera_offset)
317         { m_mesh_update_thread.m_camera_offset = camera_offset; }
318
319         bool hasClientEvents() const { return !m_client_event_queue.empty(); }
320         // Get event from queue. If queue is empty, it triggers an assertion failure.
321         ClientEvent * getClientEvent();
322
323         bool accessDenied() const { return m_access_denied; }
324
325         bool reconnectRequested() const { return m_access_denied_reconnect; }
326
327         void setFatalError(const std::string &reason)
328         {
329                 m_access_denied = true;
330                 m_access_denied_reason = reason;
331         }
332
333         // Renaming accessDeniedReason to better name could be good as it's used to
334         // disconnect client when CSM failed.
335         const std::string &accessDeniedReason() const { return m_access_denied_reason; }
336
337         bool itemdefReceived()
338         { return m_itemdef_received; }
339         bool nodedefReceived()
340         { return m_nodedef_received; }
341         bool mediaReceived()
342         { return !m_media_downloader; }
343
344         u8 getProtoVersion()
345         { return m_proto_ver; }
346
347         bool connectedToServer();
348         void confirmRegistration();
349         bool m_is_registration_confirmation_state = false;
350         bool m_simple_singleplayer_mode;
351
352         float mediaReceiveProgress();
353
354         void afterContentReceived();
355
356         float getRTT();
357         float getCurRate();
358
359         Minimap* getMinimap() { return m_minimap; }
360         void setCamera(Camera* camera) { m_camera = camera; }
361
362         Camera* getCamera () { return m_camera; }
363
364         bool shouldShowMinimap() const;
365
366         // IGameDef interface
367         virtual IItemDefManager* getItemDefManager();
368         virtual INodeDefManager* getNodeDefManager();
369         virtual ICraftDefManager* getCraftDefManager();
370         ITextureSource* getTextureSource();
371         virtual IShaderSource* getShaderSource();
372         IShaderSource *shsrc() { return getShaderSource(); }
373         virtual u16 allocateUnknownNodeId(const std::string &name);
374         virtual ISoundManager* getSoundManager();
375         virtual MtEventManager* getEventManager();
376         virtual ParticleManager* getParticleManager();
377         bool checkLocalPrivilege(const std::string &priv)
378         { return checkPrivilege(priv); }
379         virtual scene::IAnimatedMesh* getMesh(const std::string &filename, bool cache = false);
380         const std::string* getModFile(const std::string &filename);
381
382         virtual std::string getModStoragePath() const;
383         virtual bool registerModStorage(ModMetadata *meta);
384         virtual void unregisterModStorage(const std::string &name);
385
386         // The following set of functions is used by ClientMediaDownloader
387         // Insert a media file appropriately into the appropriate manager
388         bool loadMedia(const std::string &data, const std::string &filename);
389         // Send a request for conventional media transfer
390         void request_media(const std::vector<std::string> &file_requests);
391
392         LocalClientState getState() { return m_state; }
393
394         void makeScreenshot();
395
396         inline void pushToChatQueue(ChatMessage *cec)
397         {
398                 m_chat_queue.push(cec);
399         }
400
401         ClientScripting *getScript() { return m_script; }
402         const bool moddingEnabled() const { return m_modding_enabled; }
403
404         void pushToEventQueue(ClientEvent *event);
405
406         void showMinimap(bool show = true);
407
408         const Address getServerAddress();
409
410         const std::string &getAddressName() const
411         {
412                 return m_address_name;
413         }
414
415         inline bool checkCSMFlavourLimit(CSMFlavourLimit flag) const
416         {
417                 return m_csm_flavour_limits & flag;
418         }
419
420         u32 getCSMNodeRangeLimit() const
421         {
422                 return m_csm_noderange_limit;
423         }
424
425         bool joinModChannel(const std::string &channel);
426         bool leaveModChannel(const std::string &channel);
427         bool sendModChannelMessage(const std::string &channel, const std::string &message);
428         ModChannel *getModChannel(const std::string &channel);
429
430 private:
431         void loadMods();
432         bool checkBuiltinIntegrity();
433
434         // Virtual methods from con::PeerHandler
435         void peerAdded(con::Peer *peer);
436         void deletingPeer(con::Peer *peer, bool timeout);
437
438         void initLocalMapSaving(const Address &address,
439                         const std::string &hostname,
440                         bool is_local_server);
441
442         void ReceiveAll();
443         void Receive();
444
445         void sendPlayerPos();
446         // Send the item number 'item' as player item to the server
447         void sendPlayerItem(u16 item);
448
449         void deleteAuthData();
450         // helper method shared with clientpackethandler
451         static AuthMechanism choseAuthMech(const u32 mechs);
452
453         void sendInit(const std::string &playerName);
454         void promptConfirmRegistration(AuthMechanism chosen_auth_mechanism);
455         void startAuth(AuthMechanism chosen_auth_mechanism);
456         void sendDeletedBlocks(std::vector<v3s16> &blocks);
457         void sendGotBlocks(v3s16 block);
458         void sendRemovedSounds(std::vector<s32> &soundList);
459
460         // Helper function
461         inline std::string getPlayerName()
462         { return m_env.getLocalPlayer()->getName(); }
463
464         bool canSendChatMessage() const;
465
466         float m_packetcounter_timer = 0.0f;
467         float m_connection_reinit_timer = 0.1f;
468         float m_avg_rtt_timer = 0.0f;
469         float m_playerpos_send_timer = 0.0f;
470         IntervalLimiter m_map_timer_and_unload_interval;
471
472         IWritableTextureSource *m_tsrc;
473         IWritableShaderSource *m_shsrc;
474         IWritableItemDefManager *m_itemdef;
475         IWritableNodeDefManager *m_nodedef;
476         ISoundManager *m_sound;
477         MtEventManager *m_event;
478
479
480         MeshUpdateThread m_mesh_update_thread;
481         ClientEnvironment m_env;
482         ParticleManager m_particle_manager;
483         std::unique_ptr<con::Connection> m_con;
484         std::string m_address_name;
485         Camera *m_camera = nullptr;
486         Minimap *m_minimap = nullptr;
487         bool m_minimap_disabled_by_server = false;
488         // Server serialization version
489         u8 m_server_ser_ver;
490
491         // Used version of the protocol with server
492         // Values smaller than 25 only mean they are smaller than 25,
493         // and aren't accurate. We simply just don't know, because
494         // the server didn't send the version back then.
495         // If 0, server init hasn't been received yet.
496         u8 m_proto_ver = 0;
497
498         u16 m_playeritem = 0;
499         bool m_inventory_updated = false;
500         Inventory *m_inventory_from_server = nullptr;
501         float m_inventory_from_server_age = 0.0f;
502         PacketCounter m_packetcounter;
503         // Block mesh animation parameters
504         float m_animation_time = 0.0f;
505         int m_crack_level = -1;
506         v3s16 m_crack_pos;
507         // 0 <= m_daynight_i < DAYNIGHT_CACHE_COUNT
508         //s32 m_daynight_i;
509         //u32 m_daynight_ratio;
510         std::queue<std::wstring> m_out_chat_queue;
511         u32 m_last_chat_message_sent;
512         float m_chat_message_allowance = 5.0f;
513         std::queue<ChatMessage *> m_chat_queue;
514
515         // The authentication methods we can use to enter sudo mode (=change password)
516         u32 m_sudo_auth_methods;
517
518         // The seed returned by the server in TOCLIENT_INIT is stored here
519         u64 m_map_seed = 0;
520
521         // Auth data
522         std::string m_playername;
523         std::string m_password;
524         // If set, this will be sent (and cleared) upon a TOCLIENT_ACCEPT_SUDO_MODE
525         std::string m_new_password;
526         // Usable by auth mechanisms.
527         AuthMechanism m_chosen_auth_mech;
528         void *m_auth_data = nullptr;
529
530
531         bool m_access_denied = false;
532         bool m_access_denied_reconnect = false;
533         std::string m_access_denied_reason = "";
534         std::queue<ClientEvent *> m_client_event_queue;
535         bool m_itemdef_received = false;
536         bool m_nodedef_received = false;
537         bool m_mods_loaded = false;
538         ClientMediaDownloader *m_media_downloader;
539
540         // time_of_day speed approximation for old protocol
541         bool m_time_of_day_set = false;
542         float m_last_time_of_day_f = -1.0f;
543         float m_time_of_day_update_timer = 0.0f;
544
545         // An interval for generally sending object positions and stuff
546         float m_recommended_send_interval = 0.1f;
547
548         // Sounds
549         float m_removed_sounds_check_timer = 0.0f;
550         // Mapping from server sound ids to our sound ids
551         std::unordered_map<s32, int> m_sounds_server_to_client;
552         // And the other way!
553         std::unordered_map<int, s32> m_sounds_client_to_server;
554         // And relations to objects
555         std::unordered_map<int, u16> m_sounds_to_objects;
556
557         // Privileges
558         std::unordered_set<std::string> m_privileges;
559
560         // Detached inventories
561         // key = name
562         std::unordered_map<std::string, Inventory*> m_detached_inventories;
563
564         // Storage for mesh data for creating multiple instances of the same mesh
565         StringMap m_mesh_data;
566
567         StringMap m_mod_files;
568
569         // own state
570         LocalClientState m_state;
571
572         GameUI *m_game_ui;
573
574         // Used for saving server map to disk client-side
575         MapDatabase *m_localdb = nullptr;
576         IntervalLimiter m_localdb_save_interval;
577         u16 m_cache_save_interval;
578
579         ClientScripting *m_script = nullptr;
580         bool m_modding_enabled;
581         std::unordered_map<std::string, ModMetadata *> m_mod_storages;
582         float m_mod_storage_save_timer = 10.0f;
583         std::vector<ModSpec> m_mods;
584
585         bool m_shutdown = false;
586
587         // CSM flavour limits byteflag
588         u64 m_csm_flavour_limits = CSMFlavourLimit::CSM_FL_NONE;
589         u32 m_csm_noderange_limit = 8;
590
591         std::unique_ptr<ModChannelMgr> m_modchannel_mgr;
592 };