client.cpp 48 KB

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