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