client.cpp 51 KB

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