You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

1975 lines
56 KiB

  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. #include <iostream>
  17. #include <algorithm>
  18. #include <sstream>
  19. #include <cmath>
  20. #include <IFileSystem.h>
  21. #include "client.h"
  22. #include "network/clientopcodes.h"
  23. #include "network/networkpacket.h"
  24. #include "threading/mutex_auto_lock.h"
  25. #include "client/renderingengine.h"
  26. #include "util/auth.h"
  27. #include "util/directiontables.h"
  28. #include "util/pointedthing.h"
  29. #include "util/serialize.h"
  30. #include "util/string.h"
  31. #include "util/srp.h"
  32. #include "filesys.h"
  33. #include "mapblock_mesh.h"
  34. #include "mapblock.h"
  35. #include "minimap.h"
  36. #include "mods.h"
  37. #include "profiler.h"
  38. #include "shader.h"
  39. #include "gettext.h"
  40. #include "clientmap.h"
  41. #include "clientmedia.h"
  42. #include "version.h"
  43. #include "database-sqlite3.h"
  44. #include "serialization.h"
  45. #include "guiscalingfilter.h"
  46. #include "script/scripting_client.h"
  47. #include "game.h"
  48. #include "chatmessage.h"
  49. #include "translation.h"
  50. extern gui::IGUIEnvironment* guienv;
  51. /*
  52. Client
  53. */
  54. Client::Client(
  55. const char *playername,
  56. const std::string &password,
  57. const std::string &address_name,
  58. MapDrawControl &control,
  59. IWritableTextureSource *tsrc,
  60. IWritableShaderSource *shsrc,
  61. IWritableItemDefManager *itemdef,
  62. IWritableNodeDefManager *nodedef,
  63. ISoundManager *sound,
  64. MtEventManager *event,
  65. bool ipv6,
  66. GameUIFlags *game_ui_flags
  67. ):
  68. m_tsrc(tsrc),
  69. m_shsrc(shsrc),
  70. m_itemdef(itemdef),
  71. m_nodedef(nodedef),
  72. m_sound(sound),
  73. m_event(event),
  74. m_mesh_update_thread(this),
  75. m_env(
  76. new ClientMap(this, control, 666),
  77. tsrc, this
  78. ),
  79. m_particle_manager(&m_env),
  80. m_con(PROTOCOL_ID, 512, CONNECTION_TIMEOUT, ipv6, this),
  81. m_address_name(address_name),
  82. m_server_ser_ver(SER_FMT_VER_INVALID),
  83. m_last_chat_message_sent(time(NULL)),
  84. m_password(password),
  85. m_chosen_auth_mech(AUTH_MECHANISM_NONE),
  86. m_media_downloader(new ClientMediaDownloader()),
  87. m_state(LC_Created),
  88. m_game_ui_flags(game_ui_flags)
  89. {
  90. // Add local player
  91. m_env.setLocalPlayer(new LocalPlayer(this, playername));
  92. if (g_settings->getBool("enable_minimap")) {
  93. m_minimap = new Minimap(this);
  94. }
  95. m_cache_save_interval = g_settings->getU16("server_map_save_interval");
  96. m_modding_enabled = g_settings->getBool("enable_client_modding");
  97. // Only create the client script environment if client scripting
  98. // is enabled by the client.
  99. if (m_modding_enabled) {
  100. m_script = new ClientScripting(this);
  101. m_env.setScript(m_script);
  102. m_script->setEnv(&m_env);
  103. }
  104. }
  105. void Client::loadMods()
  106. {
  107. // Don't load mods twice. Additionally, don't proceed unless CSM
  108. // is enabled.
  109. if (m_mods_loaded || !m_modding_enabled) return;
  110. // Load builtin
  111. scanModIntoMemory (BUILTIN_MOD_NAME, getBuiltinLuaPath());
  112. m_script->loadModFromMemory (BUILTIN_MOD_NAME);
  113. ClientModConfiguration modconf (getClientModsLuaPath());
  114. m_mods = modconf.getMods();
  115. // Complain about mods with unsatis-
  116. // fied dependencies
  117. if (!modconf.isConsistent()) modconf.printUnsatisfiedModsError();
  118. // List mods
  119. infostream << "Client Loading mods: ";
  120. for (const ModSpec &mod : m_mods) infostream << mod.name << " ";
  121. infostream << std::endl;
  122. // Load and run "mod" scripts
  123. for (const ModSpec &mod : m_mods)
  124. {
  125. if (!string_allowed (mod.name, MODNAME_ALLOWED_CHARS))
  126. {
  127. throw ModError ("Error loading mod \"" + mod.name +
  128. "\": Mod name does not follow naming conventions: "
  129. "Only characters [a-z0-9_] are allowed.");
  130. }
  131. scanModIntoMemory (mod.name, mod.path);
  132. }
  133. // Load and run "mod" scripts
  134. for (const ModSpec &mod : m_mods)
  135. m_script->loadModFromMemory(mod.name);
  136. // Run a callback when mods are loaded
  137. m_script->on_mods_loaded();
  138. m_mods_loaded = true;
  139. }
  140. bool Client::checkBuiltinIntegrity()
  141. {
  142. // @TODO
  143. return true;
  144. }
  145. void Client::scanModSubfolder(const std::string &mod_name, const std::string &mod_path,
  146. std::string mod_subpath)
  147. {
  148. std::string full_path = mod_path + DIR_DELIM + mod_subpath;
  149. std::vector<fs::DirListNode> mod = fs::GetDirListing(full_path);
  150. for (const fs::DirListNode &j : mod) {
  151. std::string filename = j.name;
  152. if (j.dir) {
  153. scanModSubfolder(mod_name, mod_path, mod_subpath
  154. + filename + DIR_DELIM);
  155. continue;
  156. }
  157. std::replace( mod_subpath.begin(), mod_subpath.end(), DIR_DELIM_CHAR, '/');
  158. m_mod_files[mod_name + ":" + mod_subpath + filename] = full_path + filename;
  159. }
  160. }
  161. const std::string &Client::getBuiltinLuaPath()
  162. {
  163. static const std::string builtin_dir = porting::path_share + DIR_DELIM + "builtin";
  164. return builtin_dir;
  165. }
  166. const std::string &Client::getClientModsLuaPath()
  167. {
  168. static const std::string clientmods_dir = porting::path_share + DIR_DELIM + "clientmods";
  169. return clientmods_dir;
  170. }
  171. const std::vector<ModSpec>& Client::getMods() const
  172. {
  173. static std::vector<ModSpec> client_modspec_temp;
  174. return client_modspec_temp;
  175. }
  176. const ModSpec* Client::getModSpec(const std::string &modname) const
  177. {
  178. return NULL;
  179. }
  180. void Client::Stop()
  181. {
  182. m_shutdown = true;
  183. if (m_modding_enabled)
  184. m_script->on_shutdown();
  185. //request all client managed threads to stop
  186. m_mesh_update_thread.stop();
  187. // Save local server map
  188. if (m_localdb) {
  189. infostream << "Local map saving ended." << std::endl;
  190. m_localdb->endSave();
  191. }
  192. if (m_modding_enabled)
  193. delete m_script;
  194. }
  195. bool Client::isShutdown()
  196. {
  197. return m_shutdown || !m_mesh_update_thread.isRunning();
  198. }
  199. Client::~Client()
  200. {
  201. m_shutdown = true;
  202. m_con.Disconnect();
  203. deleteAuthData();
  204. m_mesh_update_thread.stop();
  205. m_mesh_update_thread.wait();
  206. while (!m_mesh_update_thread.m_queue_out.empty()) {
  207. MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_frontNoEx();
  208. delete r.mesh;
  209. }
  210. delete m_inventory_from_server;
  211. // Delete detached inventories
  212. for (auto &m_detached_inventorie : m_detached_inventories) {
  213. delete m_detached_inventorie.second;
  214. }
  215. // cleanup 3d model meshes on client shutdown
  216. while (RenderingEngine::get_mesh_cache()->getMeshCount() != 0) {
  217. scene::IAnimatedMesh *mesh = RenderingEngine::get_mesh_cache()->getMeshByIndex(0);
  218. if (mesh)
  219. RenderingEngine::get_mesh_cache()->removeMesh(mesh);
  220. }
  221. delete m_minimap;
  222. delete m_media_downloader;
  223. }
  224. void Client::connect(Address address, bool is_local_server)
  225. {
  226. initLocalMapSaving(address, m_address_name, is_local_server);
  227. m_con.SetTimeoutMs(0);
  228. m_con.Connect(address);
  229. }
  230. void Client::step(float dtime)
  231. {
  232. // Limit a bit
  233. if(dtime > 2.0)
  234. dtime = 2.0;
  235. if(m_ignore_damage_timer > dtime)
  236. m_ignore_damage_timer -= dtime;
  237. else
  238. m_ignore_damage_timer = 0.0;
  239. m_animation_time += dtime;
  240. if(m_animation_time > 60.0)
  241. m_animation_time -= 60.0;
  242. m_time_of_day_update_timer += dtime;
  243. ReceiveAll();
  244. /*
  245. Packet counter
  246. */
  247. {
  248. float &counter = m_packetcounter_timer;
  249. counter -= dtime;
  250. if(counter <= 0.0)
  251. {
  252. counter = 20.0;
  253. infostream << "Client packetcounter (" << m_packetcounter_timer
  254. << "):"<<std::endl;
  255. m_packetcounter.print(infostream);
  256. m_packetcounter.clear();
  257. }
  258. }
  259. // UGLY hack to fix 2 second startup delay caused by non existent
  260. // server client startup synchronization in local server or singleplayer mode
  261. static bool initial_step = true;
  262. if (initial_step) {
  263. initial_step = false;
  264. }
  265. else if(m_state == LC_Created) {
  266. float &counter = m_connection_reinit_timer;
  267. counter -= dtime;
  268. if(counter <= 0.0) {
  269. counter = 2.0;
  270. LocalPlayer *myplayer = m_env.getLocalPlayer();
  271. FATAL_ERROR_IF(myplayer == NULL, "Local player not found in environment.");
  272. u16 proto_version_min = g_settings->getFlag("send_pre_v25_init") ?
  273. CLIENT_PROTOCOL_VERSION_MIN_LEGACY : CLIENT_PROTOCOL_VERSION_MIN;
  274. if (proto_version_min < 25) {
  275. // Send TOSERVER_INIT_LEGACY
  276. // [0] u16 TOSERVER_INIT_LEGACY
  277. // [2] u8 SER_FMT_VER_HIGHEST_READ
  278. // [3] u8[20] player_name
  279. // [23] u8[28] password (new in some version)
  280. // [51] u16 minimum supported network protocol version (added sometime)
  281. // [53] u16 maximum supported network protocol version (added later than the previous one)
  282. char pName[PLAYERNAME_SIZE];
  283. char pPassword[PASSWORD_SIZE];
  284. memset(pName, 0, PLAYERNAME_SIZE * sizeof(char));
  285. memset(pPassword, 0, PASSWORD_SIZE * sizeof(char));
  286. std::string hashed_password = translate_password(myplayer->getName(), m_password);
  287. snprintf(pName, PLAYERNAME_SIZE, "%s", myplayer->getName());
  288. snprintf(pPassword, PASSWORD_SIZE, "%s", hashed_password.c_str());
  289. sendLegacyInit(pName, pPassword);
  290. }
  291. if (CLIENT_PROTOCOL_VERSION_MAX >= 25)
  292. sendInit(myplayer->getName());
  293. }
  294. // Not connected, return
  295. return;
  296. }
  297. /*
  298. Do stuff if connected
  299. */
  300. /*
  301. Run Map's timers and unload unused data
  302. */
  303. const float map_timer_and_unload_dtime = 5.25;
  304. if(m_map_timer_and_unload_interval.step(dtime, map_timer_and_unload_dtime)) {
  305. ScopeProfiler sp(g_profiler, "Client: map timer and unload");
  306. std::vector<v3s16> deleted_blocks;
  307. m_env.getMap().timerUpdate(map_timer_and_unload_dtime,
  308. g_settings->getFloat("client_unload_unused_data_timeout"),
  309. g_settings->getS32("client_mapblock_limit"),
  310. &deleted_blocks);
  311. /*
  312. Send info to server
  313. NOTE: This loop is intentionally iterated the way it is.
  314. */
  315. std::vector<v3s16>::iterator i = deleted_blocks.begin();
  316. std::vector<v3s16> sendlist;
  317. for(;;) {
  318. if(sendlist.size() == 255 || i == deleted_blocks.end()) {
  319. if(sendlist.empty())
  320. break;
  321. /*
  322. [0] u16 command
  323. [2] u8 count
  324. [3] v3s16 pos_0
  325. [3+6] v3s16 pos_1
  326. ...
  327. */
  328. sendDeletedBlocks(sendlist);
  329. if(i == deleted_blocks.end())
  330. break;
  331. sendlist.clear();
  332. }
  333. sendlist.push_back(*i);
  334. ++i;
  335. }
  336. }
  337. /*
  338. Send pending messages on out chat queue
  339. */
  340. if (!m_out_chat_queue.empty() && canSendChatMessage()) {
  341. sendChatMessage(m_out_chat_queue.front());
  342. m_out_chat_queue.pop();
  343. }
  344. /*
  345. Handle environment
  346. */
  347. // Control local player (0ms)
  348. LocalPlayer *player = m_env.getLocalPlayer();
  349. assert(player);
  350. player->applyControl(dtime, &m_env);
  351. // Step environment
  352. m_env.step(dtime);
  353. m_sound->step(dtime);
  354. /*
  355. Get events
  356. */
  357. while (m_env.hasClientEnvEvents()) {
  358. ClientEnvEvent envEvent = m_env.getClientEnvEvent();
  359. if (envEvent.type == CEE_PLAYER_DAMAGE) {
  360. if (m_ignore_damage_timer <= 0) {
  361. u8 damage = envEvent.player_damage.amount;
  362. if (envEvent.player_damage.send_to_server)
  363. sendDamage(damage);
  364. // Add to ClientEvent queue
  365. ClientEvent event;
  366. event.type = CE_PLAYER_DAMAGE;
  367. event.player_damage.amount = damage;
  368. m_client_event_queue.push(event);
  369. }
  370. }
  371. // Protocol v29 or greater obsoleted this event
  372. else if (envEvent.type == CEE_PLAYER_BREATH && m_proto_ver < 29) {
  373. u16 breath = envEvent.player_breath.amount;
  374. sendBreath(breath);
  375. }
  376. }
  377. /*
  378. Print some info
  379. */
  380. float &counter = m_avg_rtt_timer;
  381. counter += dtime;
  382. if(counter >= 10) {
  383. counter = 0.0;
  384. // connectedAndInitialized() is true, peer exists.
  385. float avg_rtt = getRTT();
  386. infostream << "Client: avg_rtt=" << avg_rtt << std::endl;
  387. }
  388. /*
  389. Send player position to server
  390. */
  391. {
  392. float &counter = m_playerpos_send_timer;
  393. counter += dtime;
  394. if((m_state == LC_Ready) && (counter >= m_recommended_send_interval))
  395. {
  396. counter = 0.0;
  397. sendPlayerPos();
  398. }
  399. }
  400. /*
  401. Replace updated meshes
  402. */
  403. {
  404. int num_processed_meshes = 0;
  405. while (!m_mesh_update_thread.m_queue_out.empty())
  406. {
  407. num_processed_meshes++;
  408. MinimapMapblock *minimap_mapblock = NULL;
  409. bool do_mapper_update = true;
  410. MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_frontNoEx();
  411. MapBlock *block = m_env.getMap().getBlockNoCreateNoEx(r.p);
  412. if (block) {
  413. // Delete the old mesh
  414. delete block->mesh;
  415. block->mesh = nullptr;
  416. if (r.mesh) {
  417. minimap_mapblock = r.mesh->moveMinimapMapblock();
  418. if (minimap_mapblock == NULL)
  419. do_mapper_update = false;
  420. bool is_empty = true;
  421. for (int l = 0; l < MAX_TILE_LAYERS; l++)
  422. if (r.mesh->getMesh(l)->getMeshBufferCount() != 0)
  423. is_empty = false;
  424. if (is_empty)
  425. delete r.mesh;
  426. else
  427. // Replace with the new mesh
  428. block->mesh = r.mesh;
  429. }
  430. } else {
  431. delete r.mesh;
  432. }
  433. if (m_minimap && do_mapper_update)
  434. m_minimap->addBlock(r.p, minimap_mapblock);
  435. if (r.ack_block_to_server) {
  436. /*
  437. Acknowledge block
  438. [0] u8 count
  439. [1] v3s16 pos_0
  440. */
  441. sendGotBlocks(r.p);
  442. }
  443. }
  444. if (num_processed_meshes > 0)
  445. g_profiler->graphAdd("num_processed_meshes", num_processed_meshes);
  446. }
  447. /*
  448. Load fetched media
  449. */
  450. if (m_media_downloader && m_media_downloader->isStarted()) {
  451. m_media_downloader->step(this);
  452. if (m_media_downloader->isDone()) {
  453. delete m_media_downloader;
  454. m_media_downloader = NULL;
  455. }
  456. }
  457. /*
  458. If the server didn't update the inventory in a while, revert
  459. the local inventory (so the player notices the lag problem
  460. and knows something is wrong).
  461. */
  462. if(m_inventory_from_server)
  463. {
  464. float interval = 10.0;
  465. float count_before = floor(m_inventory_from_server_age / interval);
  466. m_inventory_from_server_age += dtime;
  467. float count_after = floor(m_inventory_from_server_age / interval);
  468. if(count_after != count_before)
  469. {
  470. // Do this every <interval> seconds after TOCLIENT_INVENTORY
  471. // Reset the locally changed inventory to the authoritative inventory
  472. LocalPlayer *player = m_env.getLocalPlayer();
  473. player->inventory = *m_inventory_from_server;
  474. m_inventory_updated = true;
  475. }
  476. }
  477. /*
  478. Update positions of sounds attached to objects
  479. */
  480. {
  481. for (auto &m_sounds_to_object : m_sounds_to_objects) {
  482. int client_id = m_sounds_to_object.first;
  483. u16 object_id = m_sounds_to_object.second;
  484. ClientActiveObject *cao = m_env.getActiveObject(object_id);
  485. if (!cao)
  486. continue;
  487. m_sound->updateSoundPosition(client_id, cao->getPosition());
  488. }
  489. }
  490. /*
  491. Handle removed remotely initiated sounds
  492. */
  493. m_removed_sounds_check_timer += dtime;
  494. if(m_removed_sounds_check_timer >= 2.32) {
  495. m_removed_sounds_check_timer = 0;
  496. // Find removed sounds and clear references to them
  497. std::vector<s32> removed_server_ids;
  498. for (std::unordered_map<s32, int>::iterator i = m_sounds_server_to_client.begin();
  499. i != m_sounds_server_to_client.end();) {
  500. s32 server_id = i->first;
  501. int client_id = i->second;
  502. ++i;
  503. if(!m_sound->soundExists(client_id)) {
  504. m_sounds_server_to_client.erase(server_id);
  505. m_sounds_client_to_server.erase(client_id);
  506. m_sounds_to_objects.erase(client_id);
  507. removed_server_ids.push_back(server_id);
  508. }
  509. }
  510. // Sync to server
  511. if(!removed_server_ids.empty()) {
  512. sendRemovedSounds(removed_server_ids);
  513. }
  514. }
  515. #ifdef CSMMODSTORE // Disable client-side mod storage
  516. m_mod_storage_save_timer -= dtime;
  517. if (m_mod_storage_save_timer <= 0.0f) {
  518. verbosestream << "Saving registered mod storages." << std::endl;
  519. m_mod_storage_save_timer = g_settings->getFloat("server_map_save_interval");
  520. for (std::unordered_map<std::string, ModMetadata *>::const_iterator
  521. it = m_mod_storages.begin(); it != m_mod_storages.end(); ++it) {
  522. if (it->second->isModified()) {
  523. it->second->save(getModStoragePath());
  524. }
  525. }
  526. }
  527. #endif
  528. // Write server map
  529. if (m_localdb && m_localdb_save_interval.step(dtime,
  530. m_cache_save_interval)) {
  531. m_localdb->endSave();
  532. m_localdb->beginSave();
  533. }
  534. }
  535. bool Client::loadMedia(const std::string &data, const std::string &filename)
  536. {
  537. // Silly irrlicht's const-incorrectness
  538. Buffer<char> data_rw(data.c_str(), data.size());
  539. std::string name;
  540. const char *image_ext[] = {
  541. ".png", ".jpg", ".bmp", ".tga",
  542. ".pcx", ".ppm", ".psd", ".wal", ".rgb",
  543. NULL
  544. };
  545. name = removeStringEnd(filename, image_ext);
  546. if (!name.empty()) {
  547. verbosestream<<"Client: Attempting to load image "
  548. <<"file \""<<filename<<"\""<<std::endl;
  549. io::IFileSystem *irrfs = RenderingEngine::get_filesystem();
  550. video::IVideoDriver *vdrv = RenderingEngine::get_video_driver();
  551. // Create an irrlicht memory file
  552. io::IReadFile *rfile = irrfs->createMemoryReadFile(
  553. *data_rw, data_rw.getSize(), "_tempreadfile");
  554. FATAL_ERROR_IF(!rfile, "Could not create irrlicht memory file.");
  555. // Read image
  556. video::IImage *img = vdrv->createImageFromFile(rfile);
  557. if (!img) {
  558. errorstream<<"Client: Cannot create image from data of "
  559. <<"file \""<<filename<<"\""<<std::endl;
  560. rfile->drop();
  561. return false;
  562. }
  563. m_tsrc->insertSourceImage(filename, img);
  564. img->drop();
  565. rfile->drop();
  566. return true;
  567. }
  568. const char *sound_ext[] = {
  569. ".0.ogg", ".1.ogg", ".2.ogg", ".3.ogg", ".4.ogg",
  570. ".5.ogg", ".6.ogg", ".7.ogg", ".8.ogg", ".9.ogg",
  571. ".ogg", NULL
  572. };
  573. name = removeStringEnd(filename, sound_ext);
  574. if (!name.empty()) {
  575. verbosestream<<"Client: Attempting to load sound "
  576. <<"file \""<<filename<<"\""<<std::endl;
  577. m_sound->loadSoundData(name, data);
  578. return true;
  579. }
  580. const char *model_ext[] = {
  581. ".x", ".b3d", ".md2", ".obj",
  582. NULL
  583. };
  584. name = removeStringEnd(filename, model_ext);
  585. if (!name.empty()) {
  586. verbosestream<<"Client: Storing model into memory: "
  587. <<"\""<<filename<<"\""<<std::endl;
  588. if(m_mesh_data.count(filename))
  589. errorstream<<"Multiple models with name \""<<filename.c_str()
  590. <<"\" found; replacing previous model"<<std::endl;
  591. m_mesh_data[filename] = data;
  592. return true;
  593. }
  594. const char *translate_ext[] = {
  595. ".tr", NULL
  596. };
  597. name = removeStringEnd(filename, translate_ext);
  598. if (!name.empty()) {
  599. verbosestream << "Client: Loading translation: "
  600. << "\"" << filename << "\"" << std::endl;
  601. g_translations->loadTranslation(data);
  602. return true;
  603. }
  604. errorstream << "Client: Don't know how to load file \""
  605. << filename << "\"" << std::endl;
  606. return false;
  607. }
  608. // Virtual methods from con::PeerHandler
  609. void Client::peerAdded(con::Peer *peer)
  610. {
  611. infostream << "Client::peerAdded(): peer->id="
  612. << peer->id << std::endl;
  613. }
  614. void Client::deletingPeer(con::Peer *peer, bool timeout)
  615. {
  616. infostream << "Client::deletingPeer(): "
  617. "Server Peer is getting deleted "
  618. << "(timeout=" << timeout << ")" << std::endl;
  619. if (timeout) {
  620. m_access_denied = true;
  621. m_access_denied_reason = gettext("Connection timed out.");
  622. }
  623. }
  624. /*
  625. u16 command
  626. u16 number of files requested
  627. for each file {
  628. u16 length of name
  629. string name
  630. }
  631. */
  632. void Client::request_media(const std::vector<std::string> &file_requests)
  633. {
  634. std::ostringstream os(std::ios_base::binary);
  635. writeU16(os, TOSERVER_REQUEST_MEDIA);
  636. size_t file_requests_size = file_requests.size();
  637. FATAL_ERROR_IF(file_requests_size > 0xFFFF, "Unsupported number of file requests");
  638. // Packet dynamicly resized
  639. NetworkPacket pkt(TOSERVER_REQUEST_MEDIA, 2 + 0);
  640. pkt << (u16) (file_requests_size & 0xFFFF);
  641. for (const std::string &file_request : file_requests) {
  642. pkt << file_request;
  643. }
  644. Send(&pkt);
  645. infostream << "Client: Sending media request list to server ("
  646. << file_requests.size() << " files. packet size)" << std::endl;
  647. }
  648. void Client::initLocalMapSaving(const Address &address,
  649. const std::string &hostname,
  650. bool is_local_server)
  651. {
  652. if (!g_settings->getBool("enable_local_map_saving") || is_local_server) {
  653. return;
  654. }
  655. const std::string world_path = porting::path_user
  656. + DIR_DELIM + "worlds"
  657. + DIR_DELIM + "server_"
  658. + hostname + "_" + std::to_string(address.getPort());
  659. fs::CreateAllDirs(world_path);
  660. m_localdb = new MapDatabaseSQLite3(world_path);
  661. m_localdb->beginSave();
  662. actionstream << "Local map saving started, map will be saved at '" << world_path << "'" << std::endl;
  663. }
  664. void Client::ReceiveAll()
  665. {
  666. u64 start_ms = porting::getTimeMs();
  667. for(;;)
  668. {
  669. // Limit time even if there would be huge amounts of data to
  670. // process
  671. if(porting::getTimeMs() > start_ms + 100)
  672. break;
  673. try {
  674. Receive();
  675. g_profiler->graphAdd("client_received_packets", 1);
  676. }
  677. catch(con::NoIncomingDataException &e) {
  678. break;
  679. }
  680. catch(con::InvalidIncomingDataException &e) {
  681. infostream<<"Client::ReceiveAll(): "
  682. "InvalidIncomingDataException: what()="
  683. <<e.what()<<std::endl;
  684. }
  685. }
  686. }
  687. void Client::Receive()
  688. {
  689. NetworkPacket pkt;
  690. m_con.Receive(&pkt);
  691. ProcessData(&pkt);
  692. }
  693. inline void Client::handleCommand(NetworkPacket* pkt)
  694. {
  695. const ToClientCommandHandler& opHandle = toClientCommandTable[pkt->getCommand()];
  696. (this->*opHandle.handler)(pkt);
  697. }
  698. /*
  699. sender_peer_id given to this shall be quaranteed to be a valid peer
  700. */
  701. void Client::ProcessData(NetworkPacket *pkt)
  702. {
  703. ToClientCommand command = (ToClientCommand) pkt->getCommand();
  704. u32 sender_peer_id = pkt->getPeerId();
  705. //infostream<<"Client: received command="<<command<<std::endl;
  706. m_packetcounter.add((u16)command);
  707. /*
  708. If this check is removed, be sure to change the queue
  709. system to know the ids
  710. */
  711. if(sender_peer_id != PEER_ID_SERVER) {
  712. infostream << "Client::ProcessData(): Discarding data not "
  713. "coming from server: peer_id=" << sender_peer_id
  714. << std::endl;
  715. return;
  716. }
  717. // Command must be handled into ToClientCommandHandler
  718. if (command >= TOCLIENT_NUM_MSG_TYPES) {
  719. infostream << "Client: Ignoring unknown command "
  720. << command << std::endl;
  721. return;
  722. }
  723. /*
  724. * Those packets are handled before m_server_ser_ver is set, it's normal
  725. * But we must use the new ToClientConnectionState in the future,
  726. * as a byte mask
  727. */
  728. if(toClientCommandTable[command].state == TOCLIENT_STATE_NOT_CONNECTED) {
  729. handleCommand(pkt);
  730. return;
  731. }
  732. if(m_server_ser_ver == SER_FMT_VER_INVALID) {
  733. infostream << "Client: Server serialization"
  734. " format invalid or not initialized."
  735. " Skipping incoming command=" << command << std::endl;
  736. return;
  737. }
  738. /*
  739. Handle runtime commands
  740. */
  741. handleCommand(pkt);
  742. }
  743. void Client::Send(NetworkPacket* pkt)
  744. {
  745. m_con.Send(PEER_ID_SERVER,
  746. serverCommandFactoryTable[pkt->getCommand()].channel,
  747. pkt,
  748. serverCommandFactoryTable[pkt->getCommand()].reliable);
  749. }
  750. // Will fill up 12 + 12 + 4 + 4 + 4 bytes
  751. void writePlayerPos(LocalPlayer *myplayer, ClientMap *clientMap, NetworkPacket *pkt)
  752. {
  753. v3f pf = myplayer->getPosition() * 100;
  754. v3f sf = myplayer->getSpeed() * 100;
  755. s32 pitch = myplayer->getPitch() * 100;
  756. s32 yaw = myplayer->getYaw() * 100;
  757. u32 keyPressed = myplayer->keyPressed;
  758. // scaled by 80, so that pi can fit into a u8
  759. u8 fov = clientMap->getCameraFov() * 80;
  760. u8 wanted_range = MYMIN(255,
  761. std::ceil(clientMap->getControl().wanted_range / MAP_BLOCKSIZE));
  762. v3s32 position(pf.X, pf.Y, pf.Z);
  763. v3s32 speed(sf.X, sf.Y, sf.Z);
  764. /*
  765. Format:
  766. [0] v3s32 position*100
  767. [12] v3s32 speed*100
  768. [12+12] s32 pitch*100
  769. [12+12+4] s32 yaw*100
  770. [12+12+4+4] u32 keyPressed
  771. [12+12+4+4+4] u8 fov*80
  772. [12+12+4+4+4+1] u8 ceil(wanted_range / MAP_BLOCKSIZE)
  773. */
  774. *pkt << position << speed << pitch << yaw << keyPressed;
  775. *pkt << fov << wanted_range;
  776. }
  777. void Client::interact(u8 action, const PointedThing& pointed)
  778. {
  779. if(m_state != LC_Ready) {
  780. errorstream << "Client::interact() "
  781. "Canceled (not connected)"
  782. << std::endl;
  783. return;
  784. }
  785. LocalPlayer *myplayer = m_env.getLocalPlayer();
  786. if (myplayer == NULL)
  787. return;
  788. /*
  789. [0] u16 command
  790. [2] u8 action
  791. [3] u16 item
  792. [5] u32 length of the next item (plen)
  793. [9] serialized PointedThing
  794. [9 + plen] player position information
  795. actions:
  796. 0: start digging (from undersurface) or use
  797. 1: stop digging (all parameters ignored)
  798. 2: digging completed
  799. 3: place block or item (to abovesurface)
  800. 4: use item
  801. 5: perform secondary action of item
  802. */
  803. NetworkPacket pkt(TOSERVER_INTERACT, 1 + 2 + 0);
  804. pkt << action;
  805. pkt << (u16)getPlayerItem();
  806. std::ostringstream tmp_os(std::ios::binary);
  807. pointed.serialize(tmp_os);
  808. pkt.putLongString(tmp_os.str());
  809. writePlayerPos(myplayer, &m_env.getClientMap(), &pkt);
  810. Send(&pkt);
  811. }
  812. void Client::deleteAuthData()
  813. {
  814. if (!m_auth_data)
  815. return;
  816. switch (m_chosen_auth_mech) {
  817. case AUTH_MECHANISM_FIRST_SRP:
  818. break;
  819. case AUTH_MECHANISM_SRP:
  820. case AUTH_MECHANISM_LEGACY_PASSWORD:
  821. srp_user_delete((SRPUser *) m_auth_data);
  822. m_auth_data = NULL;
  823. break;
  824. case AUTH_MECHANISM_NONE:
  825. break;
  826. }
  827. m_chosen_auth_mech = AUTH_MECHANISM_NONE;
  828. }
  829. AuthMechanism Client::choseAuthMech(const u32 mechs)
  830. {
  831. if (mechs & AUTH_MECHANISM_SRP)
  832. return AUTH_MECHANISM_SRP;
  833. if (mechs & AUTH_MECHANISM_FIRST_SRP)
  834. return AUTH_MECHANISM_FIRST_SRP;
  835. if (mechs & AUTH_MECHANISM_LEGACY_PASSWORD)
  836. return AUTH_MECHANISM_LEGACY_PASSWORD;
  837. return AUTH_MECHANISM_NONE;
  838. }
  839. void Client::sendLegacyInit(const char* playerName, const char* playerPassword)
  840. {
  841. NetworkPacket pkt(TOSERVER_INIT_LEGACY,
  842. 1 + PLAYERNAME_SIZE + PASSWORD_SIZE + 2 + 2);
  843. u16 proto_version_min = g_settings->getFlag("send_pre_v25_init") ?
  844. CLIENT_PROTOCOL_VERSION_MIN_LEGACY : CLIENT_PROTOCOL_VERSION_MIN;
  845. pkt << (u8) SER_FMT_VER_HIGHEST_READ;
  846. pkt.putRawString(playerName,PLAYERNAME_SIZE);
  847. pkt.putRawString(playerPassword, PASSWORD_SIZE);
  848. pkt << (u16) proto_version_min << (u16) CLIENT_PROTOCOL_VERSION_MAX;
  849. Send(&pkt);
  850. }
  851. void Client::sendInit(const std::string &playerName)
  852. {
  853. NetworkPacket pkt(TOSERVER_INIT, 1 + 2 + 2 + (1 + playerName.size()));
  854. // we don't support network compression yet
  855. u16 supp_comp_modes = NETPROTO_COMPRESSION_NONE;
  856. u16 proto_version_min = g_settings->getFlag("send_pre_v25_init") ?
  857. CLIENT_PROTOCOL_VERSION_MIN_LEGACY : CLIENT_PROTOCOL_VERSION_MIN;
  858. pkt << (u8) SER_FMT_VER_HIGHEST_READ << (u16) supp_comp_modes;
  859. pkt << (u16) proto_version_min << (u16) CLIENT_PROTOCOL_VERSION_MAX;
  860. pkt << playerName;
  861. Send(&pkt);
  862. }
  863. void Client::startAuth(AuthMechanism chosen_auth_mechanism)
  864. {
  865. m_chosen_auth_mech = chosen_auth_mechanism;
  866. switch (chosen_auth_mechanism) {
  867. case AUTH_MECHANISM_FIRST_SRP: {
  868. // send srp verifier to server
  869. std::string verifier;
  870. std::string salt;
  871. generate_srp_verifier_and_salt(getPlayerName(), m_password,
  872. &verifier, &salt);
  873. NetworkPacket resp_pkt(TOSERVER_FIRST_SRP, 0);
  874. resp_pkt << salt << verifier << (u8)((m_password.empty()) ? 1 : 0);
  875. Send(&resp_pkt);
  876. break;
  877. }
  878. case AUTH_MECHANISM_SRP:
  879. case AUTH_MECHANISM_LEGACY_PASSWORD: {
  880. u8 based_on = 1;
  881. if (chosen_auth_mechanism == AUTH_MECHANISM_LEGACY_PASSWORD) {
  882. m_password = translate_password(getPlayerName(), m_password);
  883. based_on = 0;
  884. }
  885. std::string playername_u = lowercase(getPlayerName());
  886. m_auth_data = srp_user_new(SRP_SHA256, SRP_NG_2048,
  887. getPlayerName().c_str(), playername_u.c_str(),
  888. (const unsigned char *) m_password.c_str(),
  889. m_password.length(), NULL, NULL);
  890. char *bytes_A = 0;
  891. size_t len_A = 0;
  892. SRP_Result res = srp_user_start_authentication(
  893. (struct SRPUser *) m_auth_data, NULL, NULL, 0,
  894. (unsigned char **) &bytes_A, &len_A);
  895. FATAL_ERROR_IF(res != SRP_OK, "Creating local SRP user failed.");
  896. NetworkPacket resp_pkt(TOSERVER_SRP_BYTES_A, 0);
  897. resp_pkt << std::string(bytes_A, len_A) << based_on;
  898. Send(&resp_pkt);
  899. break;
  900. }
  901. case AUTH_MECHANISM_NONE:
  902. break; // not handled in this method
  903. }
  904. }
  905. void Client::sendDeletedBlocks(std::vector<v3s16> &blocks)
  906. {
  907. NetworkPacket pkt(TOSERVER_DELETEDBLOCKS, 1 + sizeof(v3s16) * blocks.size());
  908. pkt << (u8) blocks.size();
  909. for (const v3s16 &block : blocks) {
  910. pkt << block;
  911. }
  912. Send(&pkt);
  913. }
  914. void Client::sendGotBlocks(v3s16 block)
  915. {
  916. NetworkPacket pkt(TOSERVER_GOTBLOCKS, 1 + 6);
  917. pkt << (u8) 1 << block;
  918. Send(&pkt);
  919. }
  920. void Client::sendRemovedSounds(std::vector<s32> &soundList)
  921. {
  922. size_t server_ids = soundList.size();
  923. assert(server_ids <= 0xFFFF);
  924. NetworkPacket pkt(TOSERVER_REMOVED_SOUNDS, 2 + server_ids * 4);
  925. pkt << (u16) (server_ids & 0xFFFF);
  926. for (int sound_id : soundList)
  927. pkt << sound_id;
  928. Send(&pkt);
  929. }
  930. void Client::sendNodemetaFields(v3s16 p, const std::string &formname,
  931. const StringMap &fields)
  932. {
  933. size_t fields_size = fields.size();
  934. FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of nodemeta fields");
  935. NetworkPacket pkt(TOSERVER_NODEMETA_FIELDS, 0);
  936. pkt << p << formname << (u16) (fields_size & 0xFFFF);
  937. StringMap::const_iterator it;
  938. for (it = fields.begin(); it != fields.end(); ++it) {
  939. const std::string &name = it->first;
  940. const std::string &value = it->second;
  941. pkt << name;
  942. pkt.putLongString(value);
  943. }
  944. Send(&pkt);
  945. }
  946. void Client::sendInventoryFields(const std::string &formname,
  947. const StringMap &fields)
  948. {
  949. size_t fields_size = fields.size();
  950. FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of inventory fields");
  951. NetworkPacket pkt(TOSERVER_INVENTORY_FIELDS, 0);
  952. pkt << formname << (u16) (fields_size & 0xFFFF);
  953. StringMap::const_iterator it;
  954. for (it = fields.begin(); it != fields.end(); ++it) {
  955. const std::string &name = it->first;
  956. const std::string &value = it->second;
  957. pkt << name;
  958. pkt.putLongString(value);
  959. }
  960. Send(&pkt);
  961. }
  962. void Client::sendInventoryAction(InventoryAction *a)
  963. {
  964. std::ostringstream os(std::ios_base::binary);
  965. a->serialize(os);
  966. // Make data buffer
  967. std::string s = os.str();
  968. NetworkPacket pkt(TOSERVER_INVENTORY_ACTION, s.size());
  969. pkt.putRawString(s.c_str(),s.size());
  970. Send(&pkt);
  971. }
  972. bool Client::canSendChatMessage() const
  973. {
  974. u32 now = time(NULL);
  975. float time_passed = now - m_last_chat_message_sent;
  976. float virt_chat_message_allowance = m_chat_message_allowance + time_passed *
  977. (CLIENT_CHAT_MESSAGE_LIMIT_PER_10S / 8.0f);
  978. if (virt_chat_message_allowance < 1.0f)
  979. return false;
  980. return true;
  981. }
  982. void Client::sendChatMessage(const std::wstring &message)
  983. {
  984. const s16 max_queue_size = g_settings->getS16("max_out_chat_queue_size");
  985. if (canSendChatMessage()) {
  986. u32 now = time(NULL);
  987. float time_passed = now - m_last_chat_message_sent;
  988. m_last_chat_message_sent = time(NULL);
  989. m_chat_message_allowance += time_passed * (CLIENT_CHAT_MESSAGE_LIMIT_PER_10S / 8.0f);
  990. if (m_chat_message_allowance > CLIENT_CHAT_MESSAGE_LIMIT_PER_10S)
  991. m_chat_message_allowance = CLIENT_CHAT_MESSAGE_LIMIT_PER_10S;
  992. m_chat_message_allowance -= 1.0f;
  993. NetworkPacket pkt(TOSERVER_CHAT_MESSAGE, 2 + message.size() * sizeof(u16));
  994. pkt << message;
  995. Send(&pkt);
  996. } else if (m_out_chat_queue.size() < (u16) max_queue_size || max_queue_size == -1) {
  997. m_out_chat_queue.push(message);
  998. } else {
  999. infostream << "Could not queue chat message because maximum out chat queue size ("
  1000. << max_queue_size << ") is reached." << std::endl;
  1001. }
  1002. }
  1003. void Client::clearOutChatQueue()
  1004. {
  1005. m_out_chat_queue = std::queue<std::wstring>();
  1006. }
  1007. void Client::sendChangePassword(const std::string &oldpassword,
  1008. const std::string &newpassword)
  1009. {
  1010. LocalPlayer *player = m_env.getLocalPlayer();
  1011. if (player == NULL)
  1012. return;
  1013. std::string playername = player->getName();
  1014. if (m_proto_ver >= 25) {
  1015. // get into sudo mode and then send new password to server
  1016. m_password = oldpassword;
  1017. m_new_password = newpassword;
  1018. startAuth(choseAuthMech(m_sudo_auth_methods));
  1019. } else {
  1020. std::string oldpwd = translate_password(playername, oldpassword);
  1021. std::string newpwd = translate_password(playername, newpassword);
  1022. NetworkPacket pkt(TOSERVER_PASSWORD_LEGACY, 2 * PASSWORD_SIZE);
  1023. for (u8 i = 0; i < PASSWORD_SIZE; i++) {
  1024. pkt << (u8) (i < oldpwd.length() ? oldpwd[i] : 0);
  1025. }
  1026. for (u8 i = 0; i < PASSWORD_SIZE; i++) {
  1027. pkt << (u8) (i < newpwd.length() ? newpwd[i] : 0);
  1028. }
  1029. Send(&pkt);
  1030. }
  1031. }
  1032. void Client::sendDamage(u8 damage)
  1033. {
  1034. NetworkPacket pkt(TOSERVER_DAMAGE, sizeof(u8));
  1035. pkt << damage;
  1036. Send(&pkt);
  1037. }
  1038. void Client::sendBreath(u16 breath)
  1039. {
  1040. // Protocol v29 make this obsolete
  1041. if (m_proto_ver >= 29)
  1042. return;
  1043. NetworkPacket pkt(TOSERVER_BREATH, sizeof(u16));
  1044. pkt << breath;
  1045. Send(&pkt);
  1046. }
  1047. void Client::sendRespawn()
  1048. {
  1049. NetworkPacket pkt(TOSERVER_RESPAWN, 0);
  1050. Send(&pkt);
  1051. }
  1052. void Client::sendReady()
  1053. {
  1054. NetworkPacket pkt(TOSERVER_CLIENT_READY,
  1055. 1 + 1 + 1 + 1 + 2 + sizeof(char) * strlen(g_version_hash));
  1056. pkt << (u8) VERSION_MAJOR << (u8) VERSION_MINOR << (u8) VERSION_PATCH
  1057. << (u8) 0 << (u16) strlen(g_version_hash);
  1058. pkt.putRawString(g_version_hash, (u16) strlen(g_version_hash));
  1059. Send(&pkt);
  1060. }
  1061. void Client::sendPlayerPos()
  1062. {
  1063. LocalPlayer *myplayer = m_env.getLocalPlayer();
  1064. if (!myplayer)
  1065. return;
  1066. ClientMap &map = m_env.getClientMap();
  1067. u8 camera_fov = map.getCameraFov();
  1068. u8 wanted_range = map.getControl().wanted_range;
  1069. // Save bandwidth by only updating position when something changed
  1070. if(myplayer->last_position == myplayer->getPosition() &&
  1071. myplayer->last_speed == myplayer->getSpeed() &&
  1072. myplayer->last_pitch == myplayer->getPitch() &&
  1073. myplayer->last_yaw == myplayer->getYaw() &&
  1074. myplayer->last_keyPressed == myplayer->keyPressed &&
  1075. myplayer->last_camera_fov == camera_fov &&
  1076. myplayer->last_wanted_range == wanted_range)
  1077. return;
  1078. myplayer->last_position = myplayer->getPosition();
  1079. myplayer->last_speed = myplayer->getSpeed();
  1080. myplayer->last_pitch = myplayer->getPitch();
  1081. myplayer->last_yaw = myplayer->getYaw();
  1082. myplayer->last_keyPressed = myplayer->keyPressed;
  1083. myplayer->last_camera_fov = camera_fov;
  1084. myplayer->last_wanted_range = wanted_range;
  1085. NetworkPacket pkt(TOSERVER_PLAYERPOS, 12 + 12 + 4 + 4 + 4 + 1 + 1);
  1086. writePlayerPos(myplayer, &map, &pkt);
  1087. Send(&pkt);
  1088. }
  1089. void Client::sendPlayerItem(u16 item)
  1090. {
  1091. LocalPlayer *myplayer = m_env.getLocalPlayer();
  1092. if (!myplayer) return;
  1093. NetworkPacket pkt(TOSERVER_PLAYERITEM, 2);
  1094. pkt << item;
  1095. Send(&pkt);
  1096. }
  1097. void Client::removeNode(v3s16 p)
  1098. {
  1099. std::map<v3s16, MapBlock*> modified_blocks;
  1100. try {
  1101. m_env.getMap().removeNodeAndUpdate(p, modified_blocks);
  1102. }
  1103. catch(InvalidPositionException &e) {
  1104. }
  1105. for (const auto &modified_block : modified_blocks) {
  1106. addUpdateMeshTaskWithEdge(modified_block.first, false, true);
  1107. }
  1108. }
  1109. /**
  1110. * Helper function for Client Side Modding
  1111. * Flavour is applied there, this should not be used for core engine
  1112. * @param p
  1113. * @param is_valid_position
  1114. * @return
  1115. */
  1116. MapNode Client::getNode(v3s16 p, bool *is_valid_position)
  1117. {
  1118. if (checkCSMFlavourLimit(CSMFlavourLimit::CSM_FL_LOOKUP_NODES)) {
  1119. v3s16 ppos = floatToInt(m_env.getLocalPlayer()->getPosition(), BS);
  1120. if ((u32) ppos.getDistanceFrom(p) > m_csm_noderange_limit) {
  1121. *is_valid_position = false;
  1122. return {};
  1123. }
  1124. }
  1125. return m_env.getMap().getNodeNoEx(p, is_valid_position);
  1126. }
  1127. v3s16 Client::CSMClampPos(v3s16 pos)
  1128. {
  1129. return pos;
  1130. }
  1131. void Client::addNode(v3s16 p, MapNode n, bool remove_metadata)
  1132. {
  1133. //TimeTaker timer1("Client::addNode()");
  1134. std::map<v3s16, MapBlock*> modified_blocks;
  1135. try {
  1136. //TimeTaker timer3("Client::addNode(): addNodeAndUpdate");
  1137. m_env.getMap().addNodeAndUpdate(p, n, modified_blocks, remove_metadata);
  1138. }
  1139. catch(InvalidPositionException &e) {
  1140. }
  1141. for (const auto &modified_block : modified_blocks) {
  1142. addUpdateMeshTaskWithEdge(modified_block.first, false, true);
  1143. }
  1144. }
  1145. void Client::setPlayerControl(PlayerControl &control)
  1146. {
  1147. LocalPlayer *player = m_env.getLocalPlayer();
  1148. assert(player);
  1149. player->control = control;
  1150. }
  1151. void Client::selectPlayerItem(u16 item)
  1152. {
  1153. m_playeritem = item;
  1154. m_inventory_updated = true;
  1155. sendPlayerItem(item);
  1156. }
  1157. // Returns true if the inventory of the local player has been
  1158. // updated from the server. If it is true, it is set to false.
  1159. bool Client::getLocalInventoryUpdated()
  1160. {
  1161. bool updated = m_inventory_updated;
  1162. m_inventory_updated = false;
  1163. return updated;
  1164. }
  1165. // Copies the inventory of the local player to parameter
  1166. void Client::getLocalInventory(Inventory &dst)
  1167. {
  1168. LocalPlayer *player = m_env.getLocalPlayer();
  1169. assert(player);
  1170. dst = player->inventory;
  1171. }
  1172. Inventory* Client::getInventory(const InventoryLocation &loc)
  1173. {
  1174. switch(loc.type){
  1175. case InventoryLocation::UNDEFINED:
  1176. {}
  1177. break;
  1178. case InventoryLocation::CURRENT_PLAYER:
  1179. {
  1180. LocalPlayer *player = m_env.getLocalPlayer();
  1181. assert(player);
  1182. return &player->inventory;
  1183. }
  1184. break;
  1185. case InventoryLocation::PLAYER:
  1186. {
  1187. // Check if we are working with local player inventory
  1188. LocalPlayer *player = m_env.getLocalPlayer();
  1189. if (!player || strcmp(player->getName(), loc.name.c_str()) != 0)
  1190. return NULL;
  1191. return &player->inventory;
  1192. }
  1193. break;
  1194. case InventoryLocation::NODEMETA:
  1195. {
  1196. NodeMetadata *meta = m_env.getMap().getNodeMetadata(loc.p);
  1197. if(!meta)
  1198. return NULL;
  1199. return meta->getInventory();
  1200. }
  1201. break;
  1202. case InventoryLocation::DETACHED:
  1203. {
  1204. if (m_detached_inventories.count(loc.name) == 0)
  1205. return NULL;
  1206. return m_detached_inventories[loc.name];
  1207. }
  1208. break;
  1209. default:
  1210. FATAL_ERROR("Invalid inventory location type.");
  1211. break;
  1212. }
  1213. return NULL;
  1214. }
  1215. void Client::inventoryAction(InventoryAction *a)
  1216. {
  1217. /*
  1218. Send it to the server
  1219. */
  1220. sendInventoryAction(a);
  1221. /*
  1222. Predict some local inventory changes
  1223. */
  1224. a->clientApply(this, this);
  1225. // Remove it
  1226. delete a;
  1227. }
  1228. float Client::getAnimationTime()
  1229. {
  1230. return m_animation_time;
  1231. }
  1232. int Client::getCrackLevel()
  1233. {
  1234. return m_crack_level;
  1235. }
  1236. v3s16 Client::getCrackPos()
  1237. {
  1238. return m_crack_pos;
  1239. }
  1240. void Client::setCrack(int level, v3s16 pos)
  1241. {
  1242. int old_crack_level = m_crack_level;
  1243. v3s16 old_crack_pos = m_crack_pos;
  1244. m_crack_level = level;
  1245. m_crack_pos = pos;
  1246. if(old_crack_level >= 0 && (level < 0 || pos != old_crack_pos))
  1247. {
  1248. // remove old crack
  1249. addUpdateMeshTaskForNode(old_crack_pos, false, true);
  1250. }
  1251. if(level >= 0 && (old_crack_level < 0 || pos != old_crack_pos))
  1252. {
  1253. // add new crack
  1254. addUpdateMeshTaskForNode(pos, false, true);
  1255. }
  1256. }
  1257. u16 Client::getHP()
  1258. {
  1259. LocalPlayer *player = m_env.getLocalPlayer();
  1260. assert(player);
  1261. return player->hp;
  1262. }
  1263. bool Client::getChatMessage(std::wstring &res)
  1264. {
  1265. if (m_chat_queue.empty())
  1266. return false;
  1267. ChatMessage *chatMessage = m_chat_queue.front();
  1268. m_chat_queue.pop();
  1269. res = L"";
  1270. switch (chatMessage->type) {
  1271. case CHATMESSAGE_TYPE_RAW:
  1272. case CHATMESSAGE_TYPE_ANNOUNCE:
  1273. case CHATMESSAGE_TYPE_SYSTEM:
  1274. res = chatMessage->message;
  1275. break;
  1276. case CHATMESSAGE_TYPE_NORMAL: {
  1277. if (!chatMessage->sender.empty())
  1278. res = L"<" + chatMessage->sender + L"> " + chatMessage->message;
  1279. else
  1280. res = chatMessage->message;
  1281. break;
  1282. }
  1283. default:
  1284. break;
  1285. }
  1286. delete chatMessage;
  1287. return true;
  1288. }
  1289. void Client::typeChatMessage(const std::wstring &message)
  1290. {
  1291. // Discard empty line
  1292. if (message.empty())
  1293. return;
  1294. // If message was consumed by script API, don't send it to server
  1295. if (m_modding_enabled && m_script->on_sending_message(wide_to_utf8(message)))
  1296. return;
  1297. // Send to others
  1298. sendChatMessage(message);
  1299. // Show locally
  1300. if (message[0] != L'/') {
  1301. // compatibility code
  1302. if (m_proto_ver < 29) {
  1303. LocalPlayer *player = m_env.getLocalPlayer();
  1304. assert(player);
  1305. std::wstring name = narrow_to_wide(player->getName());
  1306. pushToChatQueue(new ChatMessage(CHATMESSAGE_TYPE_NORMAL, message, name));
  1307. }
  1308. }
  1309. }
  1310. void Client::addUpdateMeshTask(v3s16 p, bool ack_to_server, bool urgent)
  1311. {
  1312. // Check if the block exists to begin with. In the case when a non-existing
  1313. // neighbor is automatically added, it may not. In that case we don't want
  1314. // to tell the mesh update thread about it.
  1315. MapBlock *b = m_env.getMap().getBlockNoCreateNoEx(p);
  1316. if (b == NULL)
  1317. return;
  1318. m_mesh_update_thread.updateBlock(&m_env.getMap(), p, ack_to_server, urgent);
  1319. }
  1320. void Client::addUpdateMeshTaskWithEdge(v3s16 blockpos, bool ack_to_server, bool urgent)
  1321. {
  1322. try{
  1323. addUpdateMeshTask(blockpos, ack_to_server, urgent);
  1324. }
  1325. catch(InvalidPositionException &e){}
  1326. // Leading edge
  1327. for (int i=0;i<6;i++)
  1328. {
  1329. try{
  1330. v3s16 p = blockpos + g_6dirs[i];
  1331. addUpdateMeshTask(p, false, urgent);
  1332. }
  1333. catch(InvalidPositionException &e){}
  1334. }
  1335. }
  1336. void Client::addUpdateMeshTaskForNode(v3s16 nodepos, bool ack_to_server, bool urgent)
  1337. {
  1338. {
  1339. v3s16 p = nodepos;
  1340. infostream<<"Client::addUpdateMeshTaskForNode(): "
  1341. <<"("<<p.X<<","<<p.Y<<","<<p.Z<<")"
  1342. <<std::endl;
  1343. }
  1344. v3s16 blockpos = getNodeBlockPos(nodepos);
  1345. v3s16 blockpos_relative = blockpos * MAP_BLOCKSIZE;
  1346. try{
  1347. addUpdateMeshTask(blockpos, ack_to_server, urgent);
  1348. }
  1349. catch(InvalidPositionException &e) {}
  1350. // Leading edge
  1351. if(nodepos.X == blockpos_relative.X){
  1352. try{
  1353. v3s16 p = blockpos + v3s16(-1,0,0);
  1354. addUpdateMeshTask(p, false, urgent);
  1355. }
  1356. catch(InvalidPositionException &e){}
  1357. }
  1358. if(nodepos.Y == blockpos_relative.Y){
  1359. try{
  1360. v3s16 p = blockpos + v3s16(0,-1,0);
  1361. addUpdateMeshTask(p, false, urgent);
  1362. }
  1363. catch(InvalidPositionException &e){}
  1364. }
  1365. if(nodepos.Z == blockpos_relative.Z){
  1366. try{
  1367. v3s16 p = blockpos + v3s16(0,0,-1);
  1368. addUpdateMeshTask(p, false, urgent);
  1369. }
  1370. catch(InvalidPositionException &e){}
  1371. }
  1372. }
  1373. ClientEvent Client::getClientEvent()
  1374. {
  1375. FATAL_ERROR_IF(m_client_event_queue.empty(),
  1376. "Cannot getClientEvent, queue is empty.");
  1377. ClientEvent event = m_client_event_queue.front();
  1378. m_client_event_queue.pop();
  1379. return event;
  1380. }
  1381. float Client::mediaReceiveProgress()
  1382. {
  1383. if (m_media_downloader)
  1384. return m_media_downloader->getProgress();
  1385. return 1.0; // downloader only exists when not yet done
  1386. }
  1387. typedef struct TextureUpdateArgs {
  1388. gui::IGUIEnvironment *guienv;
  1389. u64 last_time_ms;
  1390. u16 last_percent;
  1391. const wchar_t* text_base;
  1392. ITextureSource *tsrc;
  1393. } TextureUpdateArgs;
  1394. void texture_update_progress(void *args, u32 progress, u32 max_progress)
  1395. {
  1396. TextureUpdateArgs* targs = (TextureUpdateArgs*) args;
  1397. u16 cur_percent = ceil(progress / (double) max_progress * 100.);
  1398. // update the loading menu -- if neccessary
  1399. bool do_draw = false;
  1400. u64 time_ms = targs->last_time_ms;
  1401. if (cur_percent != targs->last_percent) {
  1402. targs->last_percent = cur_percent;
  1403. time_ms = porting::getTimeMs();
  1404. // only draw when the user will notice something:
  1405. do_draw = (time_ms - targs->last_time_ms > 100);
  1406. }
  1407. if (do_draw) {
  1408. targs->last_time_ms = time_ms;
  1409. std::basic_stringstream<wchar_t> strm;
  1410. strm << targs->text_base << " " << targs->last_percent << "%...";
  1411. RenderingEngine::draw_load_screen(strm.str(), targs->guienv, targs->tsrc, 0,
  1412. 72 + (u16) ((18. / 100.) * (double) targs->last_percent), true);
  1413. }
  1414. }
  1415. void Client::afterContentReceived()
  1416. {
  1417. infostream<<"Client::afterContentReceived() started"<<std::endl;
  1418. assert(m_itemdef_received); // pre-condition
  1419. assert(m_nodedef_received); // pre-condition
  1420. assert(mediaReceived()); // pre-condition
  1421. const wchar_t* text = wgettext("Loading textures...");
  1422. // Clear cached pre-scaled 2D GUI images, as this cache
  1423. // might have images with the same name but different
  1424. // content from previous sessions.
  1425. guiScalingCacheClear();
  1426. // Rebuild inherited images and recreate textures
  1427. infostream<<"- Rebuilding images and textures"<<std::endl;
  1428. RenderingEngine::draw_load_screen(text, guienv, m_tsrc, 0, 70);
  1429. m_tsrc->rebuildImagesAndTextures();
  1430. delete[] text;
  1431. // Rebuild shaders
  1432. infostream<<"- Rebuilding shaders"<<std::endl;
  1433. text = wgettext("Rebuilding shaders...");
  1434. RenderingEngine::draw_load_screen(text, guienv, m_tsrc, 0, 71);
  1435. m_shsrc->rebuildShaders();
  1436. delete[] text;
  1437. // Update node aliases
  1438. infostream<<"- Updating node aliases"<<std::endl;
  1439. text = wgettext("Initializing nodes...");
  1440. RenderingEngine::draw_load_screen(text, guienv, m_tsrc, 0, 72);
  1441. m_nodedef->updateAliases(m_itemdef);
  1442. std::string texture_path = g_settings->get("texture_path");
  1443. if (!texture_path.empty() && fs::IsDir(texture_path))
  1444. m_nodedef->applyTextureOverrides(texture_path + DIR_DELIM + "override.txt");
  1445. m_nodedef->setNodeRegistrationStatus(true);
  1446. m_nodedef->runNodeResolveCallbacks();
  1447. delete[] text;
  1448. // Update node textures and assign shaders to each tile
  1449. infostream<<"- Updating node textures"<<std::endl;
  1450. TextureUpdateArgs tu_args;
  1451. tu_args.guienv = guienv;
  1452. tu_args.last_time_ms = porting::getTimeMs();
  1453. tu_args.last_percent = 0;
  1454. tu_args.text_base = wgettext("Initializing nodes");
  1455. tu_args.tsrc = m_tsrc;
  1456. m_nodedef->updateTextures(this, texture_update_progress, &tu_args);
  1457. delete[] tu_args.text_base;
  1458. // Start mesh update thread after setting up content definitions
  1459. infostream<<"- Starting mesh update thread"<<std::endl;
  1460. m_mesh_update_thread.start();
  1461. m_state = LC_Ready;
  1462. sendReady();
  1463. if (g_settings->getBool("enable_client_modding")) {
  1464. m_script->on_client_ready(m_env.getLocalPlayer());
  1465. }
  1466. text = wgettext("Done!");
  1467. RenderingEngine::draw_load_screen(text, guienv, m_tsrc, 0, 100);
  1468. infostream<<"Client::afterContentReceived() done"<<std::endl;
  1469. delete[] text;
  1470. }
  1471. float Client::getRTT()
  1472. {
  1473. return m_con.getPeerStat(PEER_ID_SERVER,con::AVG_RTT);
  1474. }
  1475. float Client::getCurRate()
  1476. {
  1477. return (m_con.getLocalStat(con::CUR_INC_RATE) +
  1478. m_con.getLocalStat(con::CUR_DL_RATE));
  1479. }
  1480. void Client::makeScreenshot()
  1481. {
  1482. irr::video::IVideoDriver *driver = RenderingEngine::get_video_driver();
  1483. irr::video::IImage* const raw_image = driver->createScreenShot();
  1484. if (!raw_image)
  1485. return;
  1486. time_t t = time(NULL);
  1487. struct tm *tm = localtime(&t);
  1488. char timetstamp_c[64];
  1489. strftime(timetstamp_c, sizeof(timetstamp_c), "%Y%m%d_%H%M%S", tm);
  1490. std::string filename_base = g_settings->get("screenshot_path")
  1491. + DIR_DELIM
  1492. + std::string("screenshot_")
  1493. + std::string(timetstamp_c);
  1494. std::string filename_ext = "." + g_settings->get("screenshot_format");
  1495. std::string filename;
  1496. u32 quality = (u32)g_settings->getS32("screenshot_quality");
  1497. quality = MYMIN(MYMAX(quality, 0), 100) / 100.0 * 255;
  1498. // Try to find a unique filename
  1499. unsigned serial = 0;
  1500. while (serial < SCREENSHOT_MAX_SERIAL_TRIES) {
  1501. filename = filename_base + (serial > 0 ? ("_" + itos(serial)) : "") + filename_ext;
  1502. std::ifstream tmp(filename.c_str());
  1503. if (!tmp.good())
  1504. break; // File did not apparently exist, we'll go with it
  1505. serial++;
  1506. }
  1507. if (serial == SCREENSHOT_MAX_SERIAL_TRIES) {
  1508. infostream << "Could not find suitable filename for screenshot" << std::endl;
  1509. } else {
  1510. irr::video::IImage* const image =
  1511. driver->createImage(video::ECF_R8G8B8, raw_image->getDimension());
  1512. if (image) {
  1513. raw_image->copyTo(image);
  1514. std::ostringstream sstr;
  1515. if (driver->writeImageToFile(image, filename.c_str(), quality)) {
  1516. sstr << "Saved screenshot to '" << filename << "'";
  1517. } else {
  1518. sstr << "Failed to save screenshot '" << filename << "'";
  1519. }
  1520. pushToChatQueue(new ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
  1521. narrow_to_wide(sstr.str())));
  1522. infostream << sstr.str() << std::endl;
  1523. image->drop();
  1524. }
  1525. }
  1526. raw_image->drop();
  1527. }
  1528. bool Client::shouldShowMinimap() const
  1529. {
  1530. return !m_minimap_disabled_by_server;
  1531. }
  1532. void Client::showGameChat(const bool show)
  1533. {
  1534. m_game_ui_flags->show_chat = show;
  1535. }
  1536. void Client::showGameHud(const bool show)
  1537. {
  1538. m_game_ui_flags->show_hud = show;
  1539. }
  1540. void Client::showMinimap(const bool show)
  1541. {
  1542. m_game_ui_flags->show_minimap = show;
  1543. }
  1544. void Client::showProfiler(const bool show)
  1545. {
  1546. m_game_ui_flags->show_profiler_graph = show;
  1547. }
  1548. void Client::showGameFog(const bool show)
  1549. {
  1550. m_game_ui_flags->force_fog_off = !show;
  1551. }
  1552. void Client::showGameDebug(const bool show)
  1553. {
  1554. m_game_ui_flags->show_debug = show;
  1555. }
  1556. // IGameDef interface
  1557. // Under envlock
  1558. IItemDefManager* Client::getItemDefManager()
  1559. {
  1560. return m_itemdef;
  1561. }
  1562. INodeDefManager* Client::getNodeDefManager()
  1563. {
  1564. return m_nodedef;
  1565. }
  1566. ICraftDefManager* Client::getCraftDefManager()
  1567. {
  1568. return NULL;
  1569. //return m_craftdef;
  1570. }
  1571. ITextureSource* Client::getTextureSource()
  1572. {
  1573. return m_tsrc;
  1574. }
  1575. IShaderSource* Client::getShaderSource()
  1576. {
  1577. return m_shsrc;
  1578. }
  1579. u16 Client::allocateUnknownNodeId(const std::string &name)
  1580. {
  1581. errorstream << "Client::allocateUnknownNodeId(): "
  1582. << "Client cannot allocate node IDs" << std::endl;
  1583. FATAL_ERROR("Client allocated unknown node");
  1584. return CONTENT_IGNORE;
  1585. }
  1586. ISoundManager* Client::getSoundManager()
  1587. {
  1588. return m_sound;
  1589. }
  1590. MtEventManager* Client::getEventManager()
  1591. {
  1592. return m_event;
  1593. }
  1594. ParticleManager* Client::getParticleManager()
  1595. {
  1596. return &m_particle_manager;
  1597. }
  1598. scene::IAnimatedMesh* Client::getMesh(const std::string &filename, bool cache)
  1599. {
  1600. StringMap::const_iterator it = m_mesh_data.find(filename);
  1601. if (it == m_mesh_data.end()) {
  1602. errorstream << "Client::getMesh(): Mesh not found: \"" << filename
  1603. << "\"" << std::endl;
  1604. return NULL;
  1605. }
  1606. const std::string &data = it->second;
  1607. // Create the mesh, remove it from cache and return it
  1608. // This allows unique vertex colors and other properties for each instance
  1609. Buffer<char> data_rw(data.c_str(), data.size()); // Const-incorrect Irrlicht
  1610. io::IReadFile *rfile = RenderingEngine::get_filesystem()->createMemoryReadFile(
  1611. *data_rw, data_rw.getSize(), filename.c_str());
  1612. FATAL_ERROR_IF(!rfile, "Could not create/open RAM file");
  1613. scene::IAnimatedMesh *mesh = RenderingEngine::get_scene_manager()->getMesh(rfile);
  1614. rfile->drop();
  1615. mesh->grab();
  1616. if (!cache)
  1617. RenderingEngine::get_mesh_cache()->removeMesh(mesh);
  1618. return mesh;
  1619. }
  1620. const std::string* Client::getModFile(const std::string &filename)
  1621. {
  1622. StringMap::const_iterator it = m_mod_files.find(filename);
  1623. if (it == m_mod_files.end()) {
  1624. errorstream << "Client::getModFile(): File not found: \"" << filename
  1625. << "\"" << std::endl;
  1626. return NULL;
  1627. }
  1628. return &it->second;
  1629. }
  1630. bool Client::registerModStorage(ModMetadata *storage)
  1631. {
  1632. if (m_mod_storages.find(storage->getModName()) != m_mod_storages.end()) {
  1633. errorstream << "Unable to register same mod storage twice. Storage name: "
  1634. << storage->getModName() << std::endl;
  1635. return false;
  1636. }
  1637. m_mod_storages[storage->getModName()] = storage;
  1638. return true;
  1639. }
  1640. void Client::unregisterModStorage(const std::string &name)
  1641. {
  1642. std::unordered_map<std::string, ModMetadata *>::const_iterator it =
  1643. m_mod_storages.find(name);
  1644. if (it != m_mod_storages.end()) {
  1645. // Save unconditionaly on unregistration
  1646. it->second->save(getModStoragePath());
  1647. m_mod_storages.erase(name);
  1648. }
  1649. }
  1650. std::string Client::getModStoragePath() const
  1651. {
  1652. return porting::path_user + DIR_DELIM + "client" + DIR_DELIM + "mod_storage";
  1653. }