client.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  1. /*
  2. Minetest
  3. Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU Lesser General Public License as published by
  6. the Free Software Foundation; either version 2.1 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public License along
  13. with this program; if not, write to the Free Software Foundation, Inc.,
  14. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  15. */
  16. #pragma once
  17. #include "clientenvironment.h"
  18. #include "irrlichttypes_extrabloated.h"
  19. #include <ostream>
  20. #include <map>
  21. #include <set>
  22. #include <vector>
  23. #include <unordered_set>
  24. #include "clientobject.h"
  25. #include "gamedef.h"
  26. #include "inventorymanager.h"
  27. #include "localplayer.h"
  28. #include "client/hud.h"
  29. #include "particles.h"
  30. #include "mapnode.h"
  31. #include "tileanimation.h"
  32. #include "mesh_generator_thread.h"
  33. #include "network/address.h"
  34. #include "network/peerhandler.h"
  35. #include <fstream>
  36. #define CLIENT_CHAT_MESSAGE_LIMIT_PER_10S 10.0f
  37. struct ClientEvent;
  38. struct MeshMakeData;
  39. struct ChatMessage;
  40. class MapBlockMesh;
  41. class IWritableTextureSource;
  42. class IWritableShaderSource;
  43. class IWritableItemDefManager;
  44. class ISoundManager;
  45. class NodeDefManager;
  46. //class IWritableCraftDefManager;
  47. class ClientMediaDownloader;
  48. struct MapDrawControl;
  49. class ModChannelMgr;
  50. class MtEventManager;
  51. struct PointedThing;
  52. class MapDatabase;
  53. class Minimap;
  54. struct MinimapMapblock;
  55. class Camera;
  56. class NetworkPacket;
  57. namespace con {
  58. class Connection;
  59. }
  60. enum LocalClientState {
  61. LC_Created,
  62. LC_Init,
  63. LC_Ready
  64. };
  65. /*
  66. Packet counter
  67. */
  68. class PacketCounter
  69. {
  70. public:
  71. PacketCounter() = default;
  72. void add(u16 command)
  73. {
  74. auto n = m_packets.find(command);
  75. if (n == m_packets.end())
  76. m_packets[command] = 1;
  77. else
  78. n->second++;
  79. }
  80. void clear()
  81. {
  82. m_packets.clear();
  83. }
  84. u32 sum() const;
  85. void print(std::ostream &o) const;
  86. private:
  87. // command, count
  88. std::map<u16, u32> m_packets;
  89. };
  90. class ClientScripting;
  91. class GameUI;
  92. class Client : public con::PeerHandler, public InventoryManager, public IGameDef
  93. {
  94. public:
  95. /*
  96. NOTE: Nothing is thread-safe here.
  97. */
  98. Client(
  99. const char *playername,
  100. const std::string &password,
  101. const std::string &address_name,
  102. MapDrawControl &control,
  103. IWritableTextureSource *tsrc,
  104. IWritableShaderSource *shsrc,
  105. IWritableItemDefManager *itemdef,
  106. NodeDefManager *nodedef,
  107. ISoundManager *sound,
  108. MtEventManager *event,
  109. bool ipv6,
  110. GameUI *game_ui
  111. );
  112. ~Client();
  113. DISABLE_CLASS_COPY(Client);
  114. // Load local mods into memory
  115. void scanModSubfolder(const std::string &mod_name, const std::string &mod_path,
  116. std::string mod_subpath);
  117. inline void scanModIntoMemory(const std::string &mod_name, const std::string &mod_path)
  118. {
  119. scanModSubfolder(mod_name, mod_path, "");
  120. }
  121. /*
  122. request all threads managed by client to be stopped
  123. */
  124. void Stop();
  125. bool isShutdown();
  126. /*
  127. The name of the local player should already be set when
  128. calling this, as it is sent in the initialization.
  129. */
  130. void connect(Address address, bool is_local_server);
  131. /*
  132. Stuff that references the environment is valid only as
  133. long as this is not called. (eg. Players)
  134. If this throws a PeerNotFoundException, the connection has
  135. timed out.
  136. */
  137. void step(float dtime);
  138. /*
  139. * Command Handlers
  140. */
  141. void handleCommand(NetworkPacket* pkt);
  142. void handleCommand_Null(NetworkPacket* pkt) {};
  143. void handleCommand_Deprecated(NetworkPacket* pkt);
  144. void handleCommand_Hello(NetworkPacket* pkt);
  145. void handleCommand_AuthAccept(NetworkPacket* pkt);
  146. void handleCommand_AcceptSudoMode(NetworkPacket* pkt);
  147. void handleCommand_DenySudoMode(NetworkPacket* pkt);
  148. void handleCommand_AccessDenied(NetworkPacket* pkt);
  149. void handleCommand_RemoveNode(NetworkPacket* pkt);
  150. void handleCommand_AddNode(NetworkPacket* pkt);
  151. void handleCommand_NodemetaChanged(NetworkPacket *pkt);
  152. void handleCommand_BlockData(NetworkPacket* pkt);
  153. void handleCommand_Inventory(NetworkPacket* pkt);
  154. void handleCommand_TimeOfDay(NetworkPacket* pkt);
  155. void handleCommand_ChatMessage(NetworkPacket *pkt);
  156. void handleCommand_ActiveObjectRemoveAdd(NetworkPacket* pkt);
  157. void handleCommand_ActiveObjectMessages(NetworkPacket* pkt);
  158. void handleCommand_Movement(NetworkPacket* pkt);
  159. void handleCommand_Fov(NetworkPacket *pkt);
  160. void handleCommand_HP(NetworkPacket* pkt);
  161. void handleCommand_Breath(NetworkPacket* pkt);
  162. void handleCommand_MovePlayer(NetworkPacket* pkt);
  163. void handleCommand_DeathScreen(NetworkPacket* pkt);
  164. void handleCommand_AnnounceMedia(NetworkPacket* pkt);
  165. void handleCommand_Media(NetworkPacket* pkt);
  166. void handleCommand_NodeDef(NetworkPacket* pkt);
  167. void handleCommand_ItemDef(NetworkPacket* pkt);
  168. void handleCommand_PlaySound(NetworkPacket* pkt);
  169. void handleCommand_StopSound(NetworkPacket* pkt);
  170. void handleCommand_FadeSound(NetworkPacket *pkt);
  171. void handleCommand_Privileges(NetworkPacket* pkt);
  172. void handleCommand_InventoryFormSpec(NetworkPacket* pkt);
  173. void handleCommand_DetachedInventory(NetworkPacket* pkt);
  174. void handleCommand_ShowFormSpec(NetworkPacket* pkt);
  175. void handleCommand_SpawnParticle(NetworkPacket* pkt);
  176. void handleCommand_AddParticleSpawner(NetworkPacket* pkt);
  177. void handleCommand_DeleteParticleSpawner(NetworkPacket* pkt);
  178. void handleCommand_HudAdd(NetworkPacket* pkt);
  179. void handleCommand_HudRemove(NetworkPacket* pkt);
  180. void handleCommand_HudChange(NetworkPacket* pkt);
  181. void handleCommand_HudSetFlags(NetworkPacket* pkt);
  182. void handleCommand_HudSetParam(NetworkPacket* pkt);
  183. void handleCommand_HudSetSky(NetworkPacket* pkt);
  184. void handleCommand_HudSetSun(NetworkPacket* pkt);
  185. void handleCommand_HudSetMoon(NetworkPacket* pkt);
  186. void handleCommand_HudSetStars(NetworkPacket* pkt);
  187. void handleCommand_CloudParams(NetworkPacket* pkt);
  188. void handleCommand_OverrideDayNightRatio(NetworkPacket* pkt);
  189. void handleCommand_LocalPlayerAnimations(NetworkPacket* pkt);
  190. void handleCommand_EyeOffset(NetworkPacket* pkt);
  191. void handleCommand_UpdatePlayerList(NetworkPacket* pkt);
  192. void handleCommand_ModChannelMsg(NetworkPacket *pkt);
  193. void handleCommand_ModChannelSignal(NetworkPacket *pkt);
  194. void handleCommand_SrpBytesSandB(NetworkPacket *pkt);
  195. void handleCommand_FormspecPrepend(NetworkPacket *pkt);
  196. void handleCommand_CSMRestrictionFlags(NetworkPacket *pkt);
  197. void handleCommand_PlayerSpeed(NetworkPacket *pkt);
  198. void handleCommand_MediaPush(NetworkPacket *pkt);
  199. void ProcessData(NetworkPacket *pkt);
  200. void Send(NetworkPacket* pkt);
  201. void interact(InteractAction action, const PointedThing &pointed);
  202. void sendNodemetaFields(v3s16 p, const std::string &formname,
  203. const StringMap &fields);
  204. void sendInventoryFields(const std::string &formname,
  205. const StringMap &fields);
  206. void sendInventoryAction(InventoryAction *a);
  207. void sendChatMessage(const std::wstring &message);
  208. void clearOutChatQueue();
  209. void sendChangePassword(const std::string &oldpassword,
  210. const std::string &newpassword);
  211. void sendDamage(u16 damage);
  212. void sendRespawn();
  213. void sendReady();
  214. ClientEnvironment& getEnv() { return m_env; }
  215. ITextureSource *tsrc() { return getTextureSource(); }
  216. ISoundManager *sound() { return getSoundManager(); }
  217. static const std::string &getBuiltinLuaPath();
  218. static const std::string &getClientModsLuaPath();
  219. const std::vector<ModSpec> &getMods() const override;
  220. const ModSpec* getModSpec(const std::string &modname) const override;
  221. // Causes urgent mesh updates (unlike Map::add/removeNodeWithEvent)
  222. void removeNode(v3s16 p);
  223. // helpers to enforce CSM restrictions
  224. MapNode CSMGetNode(v3s16 p, bool *is_valid_position);
  225. int CSMClampRadius(v3s16 pos, int radius);
  226. v3s16 CSMClampPos(v3s16 pos);
  227. void addNode(v3s16 p, MapNode n, bool remove_metadata = true);
  228. void setPlayerControl(PlayerControl &control);
  229. // Returns true if the inventory of the local player has been
  230. // updated from the server. If it is true, it is set to false.
  231. bool updateWieldedItem();
  232. /* InventoryManager interface */
  233. Inventory* getInventory(const InventoryLocation &loc) override;
  234. void inventoryAction(InventoryAction *a) override;
  235. // Send the item number 'item' as player item to the server
  236. void setPlayerItem(u16 item);
  237. const std::list<std::string> &getConnectedPlayerNames()
  238. {
  239. return m_env.getPlayerNames();
  240. }
  241. float getAnimationTime();
  242. int getCrackLevel();
  243. v3s16 getCrackPos();
  244. void setCrack(int level, v3s16 pos);
  245. u16 getHP();
  246. bool checkPrivilege(const std::string &priv) const
  247. { return (m_privileges.count(priv) != 0); }
  248. const std::unordered_set<std::string> &getPrivilegeList() const
  249. { return m_privileges; }
  250. bool getChatMessage(std::wstring &message);
  251. void typeChatMessage(const std::wstring& message);
  252. u64 getMapSeed(){ return m_map_seed; }
  253. void addUpdateMeshTask(v3s16 blockpos, bool ack_to_server=false, bool urgent=false);
  254. // Including blocks at appropriate edges
  255. void addUpdateMeshTaskWithEdge(v3s16 blockpos, bool ack_to_server=false, bool urgent=false);
  256. void addUpdateMeshTaskForNode(v3s16 nodepos, bool ack_to_server=false, bool urgent=false);
  257. void updateCameraOffset(v3s16 camera_offset)
  258. { m_mesh_update_thread.m_camera_offset = camera_offset; }
  259. bool hasClientEvents() const { return !m_client_event_queue.empty(); }
  260. // Get event from queue. If queue is empty, it triggers an assertion failure.
  261. ClientEvent * getClientEvent();
  262. bool accessDenied() const { return m_access_denied; }
  263. bool reconnectRequested() const { return m_access_denied_reconnect; }
  264. void setFatalError(const std::string &reason)
  265. {
  266. m_access_denied = true;
  267. m_access_denied_reason = reason;
  268. }
  269. // Renaming accessDeniedReason to better name could be good as it's used to
  270. // disconnect client when CSM failed.
  271. const std::string &accessDeniedReason() const { return m_access_denied_reason; }
  272. const bool itemdefReceived() const
  273. { return m_itemdef_received; }
  274. const bool nodedefReceived() const
  275. { return m_nodedef_received; }
  276. const bool mediaReceived() const
  277. { return !m_media_downloader; }
  278. const bool activeObjectsReceived() const
  279. { return m_activeobjects_received; }
  280. u16 getProtoVersion()
  281. { return m_proto_ver; }
  282. bool connectedToServer();
  283. void confirmRegistration();
  284. bool m_is_registration_confirmation_state = false;
  285. bool m_simple_singleplayer_mode;
  286. float mediaReceiveProgress();
  287. void afterContentReceived();
  288. float getRTT();
  289. float getCurRate();
  290. Minimap* getMinimap() { return m_minimap; }
  291. void setCamera(Camera* camera) { m_camera = camera; }
  292. Camera* getCamera () { return m_camera; }
  293. bool shouldShowMinimap() const;
  294. // IGameDef interface
  295. IItemDefManager* getItemDefManager() override;
  296. const NodeDefManager* getNodeDefManager() override;
  297. ICraftDefManager* getCraftDefManager() override;
  298. ITextureSource* getTextureSource();
  299. virtual IWritableShaderSource* getShaderSource();
  300. u16 allocateUnknownNodeId(const std::string &name) override;
  301. virtual ISoundManager* getSoundManager();
  302. MtEventManager* getEventManager();
  303. virtual ParticleManager* getParticleManager();
  304. bool checkLocalPrivilege(const std::string &priv)
  305. { return checkPrivilege(priv); }
  306. virtual scene::IAnimatedMesh* getMesh(const std::string &filename, bool cache = false);
  307. const std::string* getModFile(std::string filename);
  308. std::string getModStoragePath() const override;
  309. bool registerModStorage(ModMetadata *meta) override;
  310. void unregisterModStorage(const std::string &name) override;
  311. // The following set of functions is used by ClientMediaDownloader
  312. // Insert a media file appropriately into the appropriate manager
  313. bool loadMedia(const std::string &data, const std::string &filename,
  314. bool from_media_push = false);
  315. // Send a request for conventional media transfer
  316. void request_media(const std::vector<std::string> &file_requests);
  317. LocalClientState getState() { return m_state; }
  318. void makeScreenshot();
  319. inline void pushToChatQueue(ChatMessage *cec)
  320. {
  321. m_chat_queue.push(cec);
  322. }
  323. ClientScripting *getScript() { return m_script; }
  324. const bool modsLoaded() const { return m_mods_loaded; }
  325. void pushToEventQueue(ClientEvent *event);
  326. void showMinimap(bool show = true);
  327. const Address getServerAddress();
  328. const std::string &getAddressName() const
  329. {
  330. return m_address_name;
  331. }
  332. inline u64 getCSMRestrictionFlags() const
  333. {
  334. return m_csm_restriction_flags;
  335. }
  336. inline bool checkCSMRestrictionFlag(CSMRestrictionFlags flag) const
  337. {
  338. return m_csm_restriction_flags & flag;
  339. }
  340. u32 getCSMNodeRangeLimit() const
  341. {
  342. return m_csm_restriction_noderange;
  343. }
  344. inline std::unordered_map<u32, u32> &getHUDTranslationMap()
  345. {
  346. return m_hud_server_to_client;
  347. }
  348. bool joinModChannel(const std::string &channel) override;
  349. bool leaveModChannel(const std::string &channel) override;
  350. bool sendModChannelMessage(const std::string &channel,
  351. const std::string &message) override;
  352. ModChannel *getModChannel(const std::string &channel) override;
  353. const std::string &getFormspecPrepend() const
  354. {
  355. return m_env.getLocalPlayer()->formspec_prepend;
  356. }
  357. private:
  358. void loadMods();
  359. bool checkBuiltinIntegrity();
  360. // Virtual methods from con::PeerHandler
  361. void peerAdded(con::Peer *peer) override;
  362. void deletingPeer(con::Peer *peer, bool timeout) override;
  363. void initLocalMapSaving(const Address &address,
  364. const std::string &hostname,
  365. bool is_local_server);
  366. void ReceiveAll();
  367. void sendPlayerPos();
  368. void deleteAuthData();
  369. // helper method shared with clientpackethandler
  370. static AuthMechanism choseAuthMech(const u32 mechs);
  371. void sendInit(const std::string &playerName);
  372. void promptConfirmRegistration(AuthMechanism chosen_auth_mechanism);
  373. void startAuth(AuthMechanism chosen_auth_mechanism);
  374. void sendDeletedBlocks(std::vector<v3s16> &blocks);
  375. void sendGotBlocks(const std::vector<v3s16> &blocks);
  376. void sendRemovedSounds(std::vector<s32> &soundList);
  377. // Helper function
  378. inline std::string getPlayerName()
  379. { return m_env.getLocalPlayer()->getName(); }
  380. bool canSendChatMessage() const;
  381. float m_packetcounter_timer = 0.0f;
  382. float m_connection_reinit_timer = 0.1f;
  383. float m_avg_rtt_timer = 0.0f;
  384. float m_playerpos_send_timer = 0.0f;
  385. IntervalLimiter m_map_timer_and_unload_interval;
  386. IWritableTextureSource *m_tsrc;
  387. IWritableShaderSource *m_shsrc;
  388. IWritableItemDefManager *m_itemdef;
  389. NodeDefManager *m_nodedef;
  390. ISoundManager *m_sound;
  391. MtEventManager *m_event;
  392. MeshUpdateThread m_mesh_update_thread;
  393. ClientEnvironment m_env;
  394. ParticleManager m_particle_manager;
  395. std::unique_ptr<con::Connection> m_con;
  396. std::string m_address_name;
  397. Camera *m_camera = nullptr;
  398. Minimap *m_minimap = nullptr;
  399. bool m_minimap_disabled_by_server = false;
  400. // Server serialization version
  401. u8 m_server_ser_ver;
  402. // Used version of the protocol with server
  403. // Values smaller than 25 only mean they are smaller than 25,
  404. // and aren't accurate. We simply just don't know, because
  405. // the server didn't send the version back then.
  406. // If 0, server init hasn't been received yet.
  407. u16 m_proto_ver = 0;
  408. bool m_update_wielded_item = false;
  409. Inventory *m_inventory_from_server = nullptr;
  410. float m_inventory_from_server_age = 0.0f;
  411. PacketCounter m_packetcounter;
  412. // Block mesh animation parameters
  413. float m_animation_time = 0.0f;
  414. int m_crack_level = -1;
  415. v3s16 m_crack_pos;
  416. // 0 <= m_daynight_i < DAYNIGHT_CACHE_COUNT
  417. //s32 m_daynight_i;
  418. //u32 m_daynight_ratio;
  419. std::queue<std::wstring> m_out_chat_queue;
  420. u32 m_last_chat_message_sent;
  421. float m_chat_message_allowance = 5.0f;
  422. std::queue<ChatMessage *> m_chat_queue;
  423. // The authentication methods we can use to enter sudo mode (=change password)
  424. u32 m_sudo_auth_methods;
  425. // The seed returned by the server in TOCLIENT_INIT is stored here
  426. u64 m_map_seed = 0;
  427. // Auth data
  428. std::string m_playername;
  429. std::string m_password;
  430. // If set, this will be sent (and cleared) upon a TOCLIENT_ACCEPT_SUDO_MODE
  431. std::string m_new_password;
  432. // Usable by auth mechanisms.
  433. AuthMechanism m_chosen_auth_mech;
  434. void *m_auth_data = nullptr;
  435. bool m_access_denied = false;
  436. bool m_access_denied_reconnect = false;
  437. std::string m_access_denied_reason = "";
  438. std::queue<ClientEvent *> m_client_event_queue;
  439. bool m_itemdef_received = false;
  440. bool m_nodedef_received = false;
  441. bool m_activeobjects_received = false;
  442. bool m_mods_loaded = false;
  443. ClientMediaDownloader *m_media_downloader;
  444. // Set of media filenames pushed by server at runtime
  445. std::unordered_set<std::string> m_media_pushed_files;
  446. // time_of_day speed approximation for old protocol
  447. bool m_time_of_day_set = false;
  448. float m_last_time_of_day_f = -1.0f;
  449. float m_time_of_day_update_timer = 0.0f;
  450. // An interval for generally sending object positions and stuff
  451. float m_recommended_send_interval = 0.1f;
  452. // Sounds
  453. float m_removed_sounds_check_timer = 0.0f;
  454. // Mapping from server sound ids to our sound ids
  455. std::unordered_map<s32, int> m_sounds_server_to_client;
  456. // And the other way!
  457. std::unordered_map<int, s32> m_sounds_client_to_server;
  458. // Relation of client id to object id
  459. std::unordered_map<int, u16> m_sounds_to_objects;
  460. // Map server hud ids to client hud ids
  461. std::unordered_map<u32, u32> m_hud_server_to_client;
  462. // Privileges
  463. std::unordered_set<std::string> m_privileges;
  464. // Detached inventories
  465. // key = name
  466. std::unordered_map<std::string, Inventory*> m_detached_inventories;
  467. // Storage for mesh data for creating multiple instances of the same mesh
  468. StringMap m_mesh_data;
  469. // own state
  470. LocalClientState m_state;
  471. GameUI *m_game_ui;
  472. // Used for saving server map to disk client-side
  473. MapDatabase *m_localdb = nullptr;
  474. IntervalLimiter m_localdb_save_interval;
  475. u16 m_cache_save_interval;
  476. // Client modding
  477. ClientScripting *m_script = nullptr;
  478. bool m_modding_enabled;
  479. std::unordered_map<std::string, ModMetadata *> m_mod_storages;
  480. float m_mod_storage_save_timer = 10.0f;
  481. std::vector<ModSpec> m_mods;
  482. StringMap m_mod_vfs;
  483. bool m_shutdown = false;
  484. // CSM restrictions byteflag
  485. u64 m_csm_restriction_flags = CSMRestrictionFlags::CSM_RF_NONE;
  486. u32 m_csm_restriction_noderange = 8;
  487. std::unique_ptr<ModChannelMgr> m_modchannel_mgr;
  488. };