3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24 #include <IFileSystem.h>
26 #include "network/clientopcodes.h"
27 #include "network/connection.h"
28 #include "network/networkpacket.h"
29 #include "threading/mutex_auto_lock.h"
30 #include "client/clientevent.h"
31 #include "client/renderingengine.h"
32 #include "client/tile.h"
33 #include "util/auth.h"
34 #include "util/directiontables.h"
35 #include "util/pointedthing.h"
36 #include "util/serialize.h"
37 #include "util/string.h"
40 #include "mapblock_mesh.h"
43 #include "modchannels.h"
48 #include "clientmap.h"
49 #include "clientmedia.h"
51 #include "database/database-sqlite3.h"
52 #include "serialization.h"
53 #include "guiscalingfilter.h"
54 #include "script/scripting_client.h"
56 #include "chatmessage.h"
57 #include "translation.h"
59 extern gui::IGUIEnvironment* guienv;
66 const char *playername,
67 const std::string &password,
68 const std::string &address_name,
69 MapDrawControl &control,
70 IWritableTextureSource *tsrc,
71 IWritableShaderSource *shsrc,
72 IWritableItemDefManager *itemdef,
73 IWritableNodeDefManager *nodedef,
75 MtEventManager *event,
77 GameUIFlags *game_ui_flags
85 m_mesh_update_thread(this),
87 new ClientMap(this, control, 666),
90 m_particle_manager(&m_env),
91 m_con(new con::Connection(PROTOCOL_ID, 512, CONNECTION_TIMEOUT, ipv6, this)),
92 m_address_name(address_name),
93 m_server_ser_ver(SER_FMT_VER_INVALID),
94 m_last_chat_message_sent(time(NULL)),
96 m_chosen_auth_mech(AUTH_MECHANISM_NONE),
97 m_media_downloader(new ClientMediaDownloader()),
99 m_game_ui_flags(game_ui_flags),
100 m_modchannel_mgr(new ModChannelMgr())
103 m_env.setLocalPlayer(new LocalPlayer(this, playername));
105 if (g_settings->getBool("enable_minimap")) {
106 m_minimap = new Minimap(this);
108 m_cache_save_interval = g_settings->getU16("server_map_save_interval");
110 m_modding_enabled = g_settings->getBool("enable_client_modding");
111 m_script = new ClientScripting(this);
112 m_env.setScript(m_script);
113 m_script->setEnv(&m_env);
116 void Client::loadMods()
119 scanModIntoMemory(BUILTIN_MOD_NAME, getBuiltinLuaPath());
121 // If modding is not enabled, don't load mods, just builtin
122 if (!m_modding_enabled) {
125 ClientModConfiguration modconf(getClientModsLuaPath());
126 m_mods = modconf.getMods();
127 std::vector<ModSpec> unsatisfied_mods = modconf.getUnsatisfiedMods();
128 // complain about mods with unsatisfied dependencies
129 if (!modconf.isConsistent()) {
130 modconf.printUnsatisfiedModsError();
134 infostream << "Client Loading mods: ";
135 for (const ModSpec &mod : m_mods)
136 infostream << mod.name << " ";
137 infostream << std::endl;
139 // Load and run "mod" scripts
140 for (const ModSpec &mod : m_mods) {
141 if (!string_allowed(mod.name, MODNAME_ALLOWED_CHARS)) {
142 throw ModError("Error loading mod \"" + mod.name +
143 "\": Mod name does not follow naming conventions: "
144 "Only characters [a-z0-9_] are allowed.");
146 scanModIntoMemory(mod.name, mod.path);
150 void Client::scanModSubfolder(const std::string &mod_name, const std::string &mod_path,
151 std::string mod_subpath)
153 std::string full_path = mod_path + DIR_DELIM + mod_subpath;
154 std::vector<fs::DirListNode> mod = fs::GetDirListing(full_path);
155 for (const fs::DirListNode &j : mod) {
156 std::string filename = j.name;
158 scanModSubfolder(mod_name, mod_path, mod_subpath
159 + filename + DIR_DELIM);
162 std::replace( mod_subpath.begin(), mod_subpath.end(), DIR_DELIM_CHAR, '/');
163 m_mod_files[mod_name + ":" + mod_subpath + filename] = full_path + filename;
167 void Client::initMods()
169 m_script->loadModFromMemory(BUILTIN_MOD_NAME);
171 // If modding is not enabled, don't load mods, just builtin
172 if (!m_modding_enabled) {
176 // Load and run "mod" scripts
177 for (const ModSpec &mod : m_mods)
178 m_script->loadModFromMemory(mod.name);
181 const std::string &Client::getBuiltinLuaPath()
183 static const std::string builtin_dir = porting::path_share + DIR_DELIM + "builtin";
187 const std::string &Client::getClientModsLuaPath()
189 static const std::string clientmods_dir = porting::path_share + DIR_DELIM + "clientmods";
190 return clientmods_dir;
193 const std::vector<ModSpec>& Client::getMods() const
195 static std::vector<ModSpec> client_modspec_temp;
196 return client_modspec_temp;
199 const ModSpec* Client::getModSpec(const std::string &modname) const
207 // Don't disable this part when modding is disabled, it's used in builtin
208 m_script->on_shutdown();
209 //request all client managed threads to stop
210 m_mesh_update_thread.stop();
211 // Save local server map
213 infostream << "Local map saving ended." << std::endl;
214 m_localdb->endSave();
220 bool Client::isShutdown()
222 return m_shutdown || !m_mesh_update_thread.isRunning();
230 m_mesh_update_thread.stop();
231 m_mesh_update_thread.wait();
232 while (!m_mesh_update_thread.m_queue_out.empty()) {
233 MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_frontNoEx();
238 delete m_inventory_from_server;
240 // Delete detached inventories
241 for (auto &m_detached_inventorie : m_detached_inventories) {
242 delete m_detached_inventorie.second;
245 // cleanup 3d model meshes on client shutdown
246 while (RenderingEngine::get_mesh_cache()->getMeshCount() != 0) {
247 scene::IAnimatedMesh *mesh = RenderingEngine::get_mesh_cache()->getMeshByIndex(0);
250 RenderingEngine::get_mesh_cache()->removeMesh(mesh);
256 void Client::connect(Address address, bool is_local_server)
258 initLocalMapSaving(address, m_address_name, is_local_server);
260 m_con->SetTimeoutMs(0);
261 m_con->Connect(address);
264 void Client::step(float dtime)
270 if(m_ignore_damage_timer > dtime)
271 m_ignore_damage_timer -= dtime;
273 m_ignore_damage_timer = 0.0;
275 m_animation_time += dtime;
276 if(m_animation_time > 60.0)
277 m_animation_time -= 60.0;
279 m_time_of_day_update_timer += dtime;
287 float &counter = m_packetcounter_timer;
293 infostream << "Client packetcounter (" << m_packetcounter_timer
295 m_packetcounter.print(infostream);
296 m_packetcounter.clear();
300 // UGLY hack to fix 2 second startup delay caused by non existent
301 // server client startup synchronization in local server or singleplayer mode
302 static bool initial_step = true;
304 initial_step = false;
306 else if(m_state == LC_Created) {
307 float &counter = m_connection_reinit_timer;
312 LocalPlayer *myplayer = m_env.getLocalPlayer();
313 FATAL_ERROR_IF(myplayer == NULL, "Local player not found in environment.");
315 sendInit(myplayer->getName());
318 // Not connected, return
323 Do stuff if connected
327 Run Map's timers and unload unused data
329 const float map_timer_and_unload_dtime = 5.25;
330 if(m_map_timer_and_unload_interval.step(dtime, map_timer_and_unload_dtime)) {
331 ScopeProfiler sp(g_profiler, "Client: map timer and unload");
332 std::vector<v3s16> deleted_blocks;
333 m_env.getMap().timerUpdate(map_timer_and_unload_dtime,
334 g_settings->getFloat("client_unload_unused_data_timeout"),
335 g_settings->getS32("client_mapblock_limit"),
340 NOTE: This loop is intentionally iterated the way it is.
343 std::vector<v3s16>::iterator i = deleted_blocks.begin();
344 std::vector<v3s16> sendlist;
346 if(sendlist.size() == 255 || i == deleted_blocks.end()) {
357 sendDeletedBlocks(sendlist);
359 if(i == deleted_blocks.end())
365 sendlist.push_back(*i);
371 Send pending messages on out chat queue
373 if (!m_out_chat_queue.empty() && canSendChatMessage()) {
374 sendChatMessage(m_out_chat_queue.front());
375 m_out_chat_queue.pop();
381 // Control local player (0ms)
382 LocalPlayer *player = m_env.getLocalPlayer();
384 player->applyControl(dtime, &m_env);
388 m_sound->step(dtime);
393 while (m_env.hasClientEnvEvents()) {
394 ClientEnvEvent envEvent = m_env.getClientEnvEvent();
396 if (envEvent.type == CEE_PLAYER_DAMAGE) {
397 if (m_ignore_damage_timer <= 0) {
398 u8 damage = envEvent.player_damage.amount;
400 if (envEvent.player_damage.send_to_server)
403 // Add to ClientEvent queue
404 ClientEvent *event = new ClientEvent();
405 event->type = CE_PLAYER_DAMAGE;
406 event->player_damage.amount = damage;
407 m_client_event_queue.push(event);
415 float &counter = m_avg_rtt_timer;
419 // connectedAndInitialized() is true, peer exists.
420 float avg_rtt = getRTT();
421 infostream << "Client: avg_rtt=" << avg_rtt << std::endl;
425 Send player position to server
428 float &counter = m_playerpos_send_timer;
430 if((m_state == LC_Ready) && (counter >= m_recommended_send_interval))
438 Replace updated meshes
441 int num_processed_meshes = 0;
442 while (!m_mesh_update_thread.m_queue_out.empty())
444 num_processed_meshes++;
446 MinimapMapblock *minimap_mapblock = NULL;
447 bool do_mapper_update = true;
449 MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_frontNoEx();
450 MapBlock *block = m_env.getMap().getBlockNoCreateNoEx(r.p);
452 // Delete the old mesh
454 block->mesh = nullptr;
457 minimap_mapblock = r.mesh->moveMinimapMapblock();
458 if (minimap_mapblock == NULL)
459 do_mapper_update = false;
461 bool is_empty = true;
462 for (int l = 0; l < MAX_TILE_LAYERS; l++)
463 if (r.mesh->getMesh(l)->getMeshBufferCount() != 0)
469 // Replace with the new mesh
470 block->mesh = r.mesh;
476 if (m_minimap && do_mapper_update)
477 m_minimap->addBlock(r.p, minimap_mapblock);
479 if (r.ack_block_to_server) {
489 if (num_processed_meshes > 0)
490 g_profiler->graphAdd("num_processed_meshes", num_processed_meshes);
496 if (m_media_downloader && m_media_downloader->isStarted()) {
497 m_media_downloader->step(this);
498 if (m_media_downloader->isDone()) {
499 delete m_media_downloader;
500 m_media_downloader = NULL;
505 If the server didn't update the inventory in a while, revert
506 the local inventory (so the player notices the lag problem
507 and knows something is wrong).
509 if(m_inventory_from_server)
511 float interval = 10.0;
512 float count_before = floor(m_inventory_from_server_age / interval);
514 m_inventory_from_server_age += dtime;
516 float count_after = floor(m_inventory_from_server_age / interval);
518 if(count_after != count_before)
520 // Do this every <interval> seconds after TOCLIENT_INVENTORY
521 // Reset the locally changed inventory to the authoritative inventory
522 LocalPlayer *player = m_env.getLocalPlayer();
523 player->inventory = *m_inventory_from_server;
524 m_inventory_updated = true;
529 Update positions of sounds attached to objects
532 for (auto &m_sounds_to_object : m_sounds_to_objects) {
533 int client_id = m_sounds_to_object.first;
534 u16 object_id = m_sounds_to_object.second;
535 ClientActiveObject *cao = m_env.getActiveObject(object_id);
538 m_sound->updateSoundPosition(client_id, cao->getPosition());
543 Handle removed remotely initiated sounds
545 m_removed_sounds_check_timer += dtime;
546 if(m_removed_sounds_check_timer >= 2.32) {
547 m_removed_sounds_check_timer = 0;
548 // Find removed sounds and clear references to them
549 std::vector<s32> removed_server_ids;
550 for (std::unordered_map<s32, int>::iterator i = m_sounds_server_to_client.begin();
551 i != m_sounds_server_to_client.end();) {
552 s32 server_id = i->first;
553 int client_id = i->second;
555 if(!m_sound->soundExists(client_id)) {
556 m_sounds_server_to_client.erase(server_id);
557 m_sounds_client_to_server.erase(client_id);
558 m_sounds_to_objects.erase(client_id);
559 removed_server_ids.push_back(server_id);
564 if(!removed_server_ids.empty()) {
565 sendRemovedSounds(removed_server_ids);
569 m_mod_storage_save_timer -= dtime;
570 if (m_mod_storage_save_timer <= 0.0f) {
571 verbosestream << "Saving registered mod storages." << std::endl;
572 m_mod_storage_save_timer = g_settings->getFloat("server_map_save_interval");
573 for (std::unordered_map<std::string, ModMetadata *>::const_iterator
574 it = m_mod_storages.begin(); it != m_mod_storages.end(); ++it) {
575 if (it->second->isModified()) {
576 it->second->save(getModStoragePath());
582 if (m_localdb && m_localdb_save_interval.step(dtime,
583 m_cache_save_interval)) {
584 m_localdb->endSave();
585 m_localdb->beginSave();
589 bool Client::loadMedia(const std::string &data, const std::string &filename)
591 // Silly irrlicht's const-incorrectness
592 Buffer<char> data_rw(data.c_str(), data.size());
596 const char *image_ext[] = {
597 ".png", ".jpg", ".bmp", ".tga",
598 ".pcx", ".ppm", ".psd", ".wal", ".rgb",
601 name = removeStringEnd(filename, image_ext);
603 verbosestream<<"Client: Attempting to load image "
604 <<"file \""<<filename<<"\""<<std::endl;
606 io::IFileSystem *irrfs = RenderingEngine::get_filesystem();
607 video::IVideoDriver *vdrv = RenderingEngine::get_video_driver();
609 // Create an irrlicht memory file
610 io::IReadFile *rfile = irrfs->createMemoryReadFile(
611 *data_rw, data_rw.getSize(), "_tempreadfile");
613 FATAL_ERROR_IF(!rfile, "Could not create irrlicht memory file.");
616 video::IImage *img = vdrv->createImageFromFile(rfile);
618 errorstream<<"Client: Cannot create image from data of "
619 <<"file \""<<filename<<"\""<<std::endl;
624 m_tsrc->insertSourceImage(filename, img);
630 const char *sound_ext[] = {
631 ".0.ogg", ".1.ogg", ".2.ogg", ".3.ogg", ".4.ogg",
632 ".5.ogg", ".6.ogg", ".7.ogg", ".8.ogg", ".9.ogg",
635 name = removeStringEnd(filename, sound_ext);
637 verbosestream<<"Client: Attempting to load sound "
638 <<"file \""<<filename<<"\""<<std::endl;
639 m_sound->loadSoundData(name, data);
643 const char *model_ext[] = {
644 ".x", ".b3d", ".md2", ".obj",
648 name = removeStringEnd(filename, model_ext);
650 verbosestream<<"Client: Storing model into memory: "
651 <<"\""<<filename<<"\""<<std::endl;
652 if(m_mesh_data.count(filename))
653 errorstream<<"Multiple models with name \""<<filename.c_str()
654 <<"\" found; replacing previous model"<<std::endl;
655 m_mesh_data[filename] = data;
659 const char *translate_ext[] = {
662 name = removeStringEnd(filename, translate_ext);
664 verbosestream << "Client: Loading translation: "
665 << "\"" << filename << "\"" << std::endl;
666 g_translations->loadTranslation(data);
670 errorstream << "Client: Don't know how to load file \""
671 << filename << "\"" << std::endl;
675 // Virtual methods from con::PeerHandler
676 void Client::peerAdded(con::Peer *peer)
678 infostream << "Client::peerAdded(): peer->id="
679 << peer->id << std::endl;
681 void Client::deletingPeer(con::Peer *peer, bool timeout)
683 infostream << "Client::deletingPeer(): "
684 "Server Peer is getting deleted "
685 << "(timeout=" << timeout << ")" << std::endl;
688 m_access_denied = true;
689 m_access_denied_reason = gettext("Connection timed out.");
695 u16 number of files requested
701 void Client::request_media(const std::vector<std::string> &file_requests)
703 std::ostringstream os(std::ios_base::binary);
704 writeU16(os, TOSERVER_REQUEST_MEDIA);
705 size_t file_requests_size = file_requests.size();
707 FATAL_ERROR_IF(file_requests_size > 0xFFFF, "Unsupported number of file requests");
709 // Packet dynamicly resized
710 NetworkPacket pkt(TOSERVER_REQUEST_MEDIA, 2 + 0);
712 pkt << (u16) (file_requests_size & 0xFFFF);
714 for (const std::string &file_request : file_requests) {
720 infostream << "Client: Sending media request list to server ("
721 << file_requests.size() << " files. packet size)" << std::endl;
724 void Client::initLocalMapSaving(const Address &address,
725 const std::string &hostname,
726 bool is_local_server)
728 if (!g_settings->getBool("enable_local_map_saving") || is_local_server) {
732 const std::string world_path = porting::path_user
733 + DIR_DELIM + "worlds"
734 + DIR_DELIM + "server_"
735 + hostname + "_" + std::to_string(address.getPort());
737 fs::CreateAllDirs(world_path);
739 m_localdb = new MapDatabaseSQLite3(world_path);
740 m_localdb->beginSave();
741 actionstream << "Local map saving started, map will be saved at '" << world_path << "'" << std::endl;
744 void Client::ReceiveAll()
746 u64 start_ms = porting::getTimeMs();
749 // Limit time even if there would be huge amounts of data to
751 if(porting::getTimeMs() > start_ms + 100)
756 g_profiler->graphAdd("client_received_packets", 1);
758 catch(con::NoIncomingDataException &e) {
761 catch(con::InvalidIncomingDataException &e) {
762 infostream<<"Client::ReceiveAll(): "
763 "InvalidIncomingDataException: what()="
764 <<e.what()<<std::endl;
769 void Client::Receive()
772 m_con->Receive(&pkt);
776 inline void Client::handleCommand(NetworkPacket* pkt)
778 const ToClientCommandHandler& opHandle = toClientCommandTable[pkt->getCommand()];
779 (this->*opHandle.handler)(pkt);
783 sender_peer_id given to this shall be quaranteed to be a valid peer
785 void Client::ProcessData(NetworkPacket *pkt)
787 ToClientCommand command = (ToClientCommand) pkt->getCommand();
788 u32 sender_peer_id = pkt->getPeerId();
790 //infostream<<"Client: received command="<<command<<std::endl;
791 m_packetcounter.add((u16)command);
794 If this check is removed, be sure to change the queue
795 system to know the ids
797 if(sender_peer_id != PEER_ID_SERVER) {
798 infostream << "Client::ProcessData(): Discarding data not "
799 "coming from server: peer_id=" << sender_peer_id
804 // Command must be handled into ToClientCommandHandler
805 if (command >= TOCLIENT_NUM_MSG_TYPES) {
806 infostream << "Client: Ignoring unknown command "
807 << command << std::endl;
812 * Those packets are handled before m_server_ser_ver is set, it's normal
813 * But we must use the new ToClientConnectionState in the future,
816 if(toClientCommandTable[command].state == TOCLIENT_STATE_NOT_CONNECTED) {
821 if(m_server_ser_ver == SER_FMT_VER_INVALID) {
822 infostream << "Client: Server serialization"
823 " format invalid or not initialized."
824 " Skipping incoming command=" << command << std::endl;
829 Handle runtime commands
835 void Client::Send(NetworkPacket* pkt)
837 m_con->Send(PEER_ID_SERVER,
838 serverCommandFactoryTable[pkt->getCommand()].channel,
840 serverCommandFactoryTable[pkt->getCommand()].reliable);
843 // Will fill up 12 + 12 + 4 + 4 + 4 bytes
844 void writePlayerPos(LocalPlayer *myplayer, ClientMap *clientMap, NetworkPacket *pkt)
846 v3f pf = myplayer->getPosition() * 100;
847 v3f sf = myplayer->getSpeed() * 100;
848 s32 pitch = myplayer->getPitch() * 100;
849 s32 yaw = myplayer->getYaw() * 100;
850 u32 keyPressed = myplayer->keyPressed;
851 // scaled by 80, so that pi can fit into a u8
852 u8 fov = clientMap->getCameraFov() * 80;
853 u8 wanted_range = MYMIN(255,
854 std::ceil(clientMap->getControl().wanted_range / MAP_BLOCKSIZE));
856 v3s32 position(pf.X, pf.Y, pf.Z);
857 v3s32 speed(sf.X, sf.Y, sf.Z);
861 [0] v3s32 position*100
863 [12+12] s32 pitch*100
864 [12+12+4] s32 yaw*100
865 [12+12+4+4] u32 keyPressed
866 [12+12+4+4+4] u8 fov*80
867 [12+12+4+4+4+1] u8 ceil(wanted_range / MAP_BLOCKSIZE)
869 *pkt << position << speed << pitch << yaw << keyPressed;
870 *pkt << fov << wanted_range;
873 void Client::interact(u8 action, const PointedThing& pointed)
875 if(m_state != LC_Ready) {
876 errorstream << "Client::interact() "
877 "Canceled (not connected)"
882 LocalPlayer *myplayer = m_env.getLocalPlayer();
883 if (myplayer == NULL)
890 [5] u32 length of the next item (plen)
891 [9] serialized PointedThing
892 [9 + plen] player position information
894 0: start digging (from undersurface) or use
895 1: stop digging (all parameters ignored)
897 3: place block or item (to abovesurface)
899 5: perform secondary action of item
902 NetworkPacket pkt(TOSERVER_INTERACT, 1 + 2 + 0);
905 pkt << (u16)getPlayerItem();
907 std::ostringstream tmp_os(std::ios::binary);
908 pointed.serialize(tmp_os);
910 pkt.putLongString(tmp_os.str());
912 writePlayerPos(myplayer, &m_env.getClientMap(), &pkt);
917 void Client::deleteAuthData()
922 switch (m_chosen_auth_mech) {
923 case AUTH_MECHANISM_FIRST_SRP:
925 case AUTH_MECHANISM_SRP:
926 case AUTH_MECHANISM_LEGACY_PASSWORD:
927 srp_user_delete((SRPUser *) m_auth_data);
930 case AUTH_MECHANISM_NONE:
933 m_chosen_auth_mech = AUTH_MECHANISM_NONE;
937 AuthMechanism Client::choseAuthMech(const u32 mechs)
939 if (mechs & AUTH_MECHANISM_SRP)
940 return AUTH_MECHANISM_SRP;
942 if (mechs & AUTH_MECHANISM_FIRST_SRP)
943 return AUTH_MECHANISM_FIRST_SRP;
945 if (mechs & AUTH_MECHANISM_LEGACY_PASSWORD)
946 return AUTH_MECHANISM_LEGACY_PASSWORD;
948 return AUTH_MECHANISM_NONE;
951 void Client::sendInit(const std::string &playerName)
953 NetworkPacket pkt(TOSERVER_INIT, 1 + 2 + 2 + (1 + playerName.size()));
955 // we don't support network compression yet
956 u16 supp_comp_modes = NETPROTO_COMPRESSION_NONE;
958 pkt << (u8) SER_FMT_VER_HIGHEST_READ << (u16) supp_comp_modes;
959 pkt << (u16) CLIENT_PROTOCOL_VERSION_MIN << (u16) CLIENT_PROTOCOL_VERSION_MAX;
965 void Client::startAuth(AuthMechanism chosen_auth_mechanism)
967 m_chosen_auth_mech = chosen_auth_mechanism;
969 switch (chosen_auth_mechanism) {
970 case AUTH_MECHANISM_FIRST_SRP: {
971 // send srp verifier to server
972 std::string verifier;
974 generate_srp_verifier_and_salt(getPlayerName(), m_password,
977 NetworkPacket resp_pkt(TOSERVER_FIRST_SRP, 0);
978 resp_pkt << salt << verifier << (u8)((m_password.empty()) ? 1 : 0);
983 case AUTH_MECHANISM_SRP:
984 case AUTH_MECHANISM_LEGACY_PASSWORD: {
987 if (chosen_auth_mechanism == AUTH_MECHANISM_LEGACY_PASSWORD) {
988 m_password = translate_password(getPlayerName(), m_password);
992 std::string playername_u = lowercase(getPlayerName());
993 m_auth_data = srp_user_new(SRP_SHA256, SRP_NG_2048,
994 getPlayerName().c_str(), playername_u.c_str(),
995 (const unsigned char *) m_password.c_str(),
996 m_password.length(), NULL, NULL);
999 SRP_Result res = srp_user_start_authentication(
1000 (struct SRPUser *) m_auth_data, NULL, NULL, 0,
1001 (unsigned char **) &bytes_A, &len_A);
1002 FATAL_ERROR_IF(res != SRP_OK, "Creating local SRP user failed.");
1004 NetworkPacket resp_pkt(TOSERVER_SRP_BYTES_A, 0);
1005 resp_pkt << std::string(bytes_A, len_A) << based_on;
1009 case AUTH_MECHANISM_NONE:
1010 break; // not handled in this method
1014 void Client::sendDeletedBlocks(std::vector<v3s16> &blocks)
1016 NetworkPacket pkt(TOSERVER_DELETEDBLOCKS, 1 + sizeof(v3s16) * blocks.size());
1018 pkt << (u8) blocks.size();
1020 for (const v3s16 &block : blocks) {
1027 void Client::sendGotBlocks(v3s16 block)
1029 NetworkPacket pkt(TOSERVER_GOTBLOCKS, 1 + 6);
1030 pkt << (u8) 1 << block;
1034 void Client::sendRemovedSounds(std::vector<s32> &soundList)
1036 size_t server_ids = soundList.size();
1037 assert(server_ids <= 0xFFFF);
1039 NetworkPacket pkt(TOSERVER_REMOVED_SOUNDS, 2 + server_ids * 4);
1041 pkt << (u16) (server_ids & 0xFFFF);
1043 for (int sound_id : soundList)
1049 void Client::sendNodemetaFields(v3s16 p, const std::string &formname,
1050 const StringMap &fields)
1052 size_t fields_size = fields.size();
1054 FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of nodemeta fields");
1056 NetworkPacket pkt(TOSERVER_NODEMETA_FIELDS, 0);
1058 pkt << p << formname << (u16) (fields_size & 0xFFFF);
1060 StringMap::const_iterator it;
1061 for (it = fields.begin(); it != fields.end(); ++it) {
1062 const std::string &name = it->first;
1063 const std::string &value = it->second;
1065 pkt.putLongString(value);
1071 void Client::sendInventoryFields(const std::string &formname,
1072 const StringMap &fields)
1074 size_t fields_size = fields.size();
1075 FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of inventory fields");
1077 NetworkPacket pkt(TOSERVER_INVENTORY_FIELDS, 0);
1078 pkt << formname << (u16) (fields_size & 0xFFFF);
1080 StringMap::const_iterator it;
1081 for (it = fields.begin(); it != fields.end(); ++it) {
1082 const std::string &name = it->first;
1083 const std::string &value = it->second;
1085 pkt.putLongString(value);
1091 void Client::sendInventoryAction(InventoryAction *a)
1093 std::ostringstream os(std::ios_base::binary);
1098 std::string s = os.str();
1100 NetworkPacket pkt(TOSERVER_INVENTORY_ACTION, s.size());
1101 pkt.putRawString(s.c_str(),s.size());
1106 bool Client::canSendChatMessage() const
1108 u32 now = time(NULL);
1109 float time_passed = now - m_last_chat_message_sent;
1111 float virt_chat_message_allowance = m_chat_message_allowance + time_passed *
1112 (CLIENT_CHAT_MESSAGE_LIMIT_PER_10S / 8.0f);
1114 if (virt_chat_message_allowance < 1.0f)
1120 void Client::sendChatMessage(const std::wstring &message)
1122 const s16 max_queue_size = g_settings->getS16("max_out_chat_queue_size");
1123 if (canSendChatMessage()) {
1124 u32 now = time(NULL);
1125 float time_passed = now - m_last_chat_message_sent;
1126 m_last_chat_message_sent = time(NULL);
1128 m_chat_message_allowance += time_passed * (CLIENT_CHAT_MESSAGE_LIMIT_PER_10S / 8.0f);
1129 if (m_chat_message_allowance > CLIENT_CHAT_MESSAGE_LIMIT_PER_10S)
1130 m_chat_message_allowance = CLIENT_CHAT_MESSAGE_LIMIT_PER_10S;
1132 m_chat_message_allowance -= 1.0f;
1134 NetworkPacket pkt(TOSERVER_CHAT_MESSAGE, 2 + message.size() * sizeof(u16));
1139 } else if (m_out_chat_queue.size() < (u16) max_queue_size || max_queue_size == -1) {
1140 m_out_chat_queue.push(message);
1142 infostream << "Could not queue chat message because maximum out chat queue size ("
1143 << max_queue_size << ") is reached." << std::endl;
1147 void Client::clearOutChatQueue()
1149 m_out_chat_queue = std::queue<std::wstring>();
1152 void Client::sendChangePassword(const std::string &oldpassword,
1153 const std::string &newpassword)
1155 LocalPlayer *player = m_env.getLocalPlayer();
1159 // get into sudo mode and then send new password to server
1160 m_password = oldpassword;
1161 m_new_password = newpassword;
1162 startAuth(choseAuthMech(m_sudo_auth_methods));
1166 void Client::sendDamage(u8 damage)
1168 NetworkPacket pkt(TOSERVER_DAMAGE, sizeof(u8));
1173 void Client::sendRespawn()
1175 NetworkPacket pkt(TOSERVER_RESPAWN, 0);
1179 void Client::sendReady()
1181 NetworkPacket pkt(TOSERVER_CLIENT_READY,
1182 1 + 1 + 1 + 1 + 2 + sizeof(char) * strlen(g_version_hash));
1184 pkt << (u8) VERSION_MAJOR << (u8) VERSION_MINOR << (u8) VERSION_PATCH
1185 << (u8) 0 << (u16) strlen(g_version_hash);
1187 pkt.putRawString(g_version_hash, (u16) strlen(g_version_hash));
1191 void Client::sendPlayerPos()
1193 LocalPlayer *myplayer = m_env.getLocalPlayer();
1197 ClientMap &map = m_env.getClientMap();
1199 u8 camera_fov = map.getCameraFov();
1200 u8 wanted_range = map.getControl().wanted_range;
1202 // Save bandwidth by only updating position when something changed
1203 if(myplayer->last_position == myplayer->getPosition() &&
1204 myplayer->last_speed == myplayer->getSpeed() &&
1205 myplayer->last_pitch == myplayer->getPitch() &&
1206 myplayer->last_yaw == myplayer->getYaw() &&
1207 myplayer->last_keyPressed == myplayer->keyPressed &&
1208 myplayer->last_camera_fov == camera_fov &&
1209 myplayer->last_wanted_range == wanted_range)
1212 myplayer->last_position = myplayer->getPosition();
1213 myplayer->last_speed = myplayer->getSpeed();
1214 myplayer->last_pitch = myplayer->getPitch();
1215 myplayer->last_yaw = myplayer->getYaw();
1216 myplayer->last_keyPressed = myplayer->keyPressed;
1217 myplayer->last_camera_fov = camera_fov;
1218 myplayer->last_wanted_range = wanted_range;
1220 NetworkPacket pkt(TOSERVER_PLAYERPOS, 12 + 12 + 4 + 4 + 4 + 1 + 1);
1222 writePlayerPos(myplayer, &map, &pkt);
1227 void Client::sendPlayerItem(u16 item)
1229 LocalPlayer *myplayer = m_env.getLocalPlayer();
1233 NetworkPacket pkt(TOSERVER_PLAYERITEM, 2);
1240 void Client::removeNode(v3s16 p)
1242 std::map<v3s16, MapBlock*> modified_blocks;
1245 m_env.getMap().removeNodeAndUpdate(p, modified_blocks);
1247 catch(InvalidPositionException &e) {
1250 for (const auto &modified_block : modified_blocks) {
1251 addUpdateMeshTaskWithEdge(modified_block.first, false, true);
1256 * Helper function for Client Side Modding
1257 * Flavour is applied there, this should not be used for core engine
1259 * @param is_valid_position
1262 MapNode Client::getNode(v3s16 p, bool *is_valid_position)
1264 if (checkCSMFlavourLimit(CSMFlavourLimit::CSM_FL_LOOKUP_NODES)) {
1265 v3s16 ppos = floatToInt(m_env.getLocalPlayer()->getPosition(), BS);
1266 if ((u32) ppos.getDistanceFrom(p) > m_csm_noderange_limit) {
1267 *is_valid_position = false;
1271 return m_env.getMap().getNodeNoEx(p, is_valid_position);
1274 void Client::addNode(v3s16 p, MapNode n, bool remove_metadata)
1276 //TimeTaker timer1("Client::addNode()");
1278 std::map<v3s16, MapBlock*> modified_blocks;
1281 //TimeTaker timer3("Client::addNode(): addNodeAndUpdate");
1282 m_env.getMap().addNodeAndUpdate(p, n, modified_blocks, remove_metadata);
1284 catch(InvalidPositionException &e) {
1287 for (const auto &modified_block : modified_blocks) {
1288 addUpdateMeshTaskWithEdge(modified_block.first, false, true);
1292 void Client::setPlayerControl(PlayerControl &control)
1294 LocalPlayer *player = m_env.getLocalPlayer();
1296 player->control = control;
1299 void Client::selectPlayerItem(u16 item)
1301 m_playeritem = item;
1302 m_inventory_updated = true;
1303 sendPlayerItem(item);
1306 // Returns true if the inventory of the local player has been
1307 // updated from the server. If it is true, it is set to false.
1308 bool Client::getLocalInventoryUpdated()
1310 bool updated = m_inventory_updated;
1311 m_inventory_updated = false;
1315 // Copies the inventory of the local player to parameter
1316 void Client::getLocalInventory(Inventory &dst)
1318 LocalPlayer *player = m_env.getLocalPlayer();
1320 dst = player->inventory;
1323 Inventory* Client::getInventory(const InventoryLocation &loc)
1326 case InventoryLocation::UNDEFINED:
1329 case InventoryLocation::CURRENT_PLAYER:
1331 LocalPlayer *player = m_env.getLocalPlayer();
1333 return &player->inventory;
1336 case InventoryLocation::PLAYER:
1338 // Check if we are working with local player inventory
1339 LocalPlayer *player = m_env.getLocalPlayer();
1340 if (!player || strcmp(player->getName(), loc.name.c_str()) != 0)
1342 return &player->inventory;
1345 case InventoryLocation::NODEMETA:
1347 NodeMetadata *meta = m_env.getMap().getNodeMetadata(loc.p);
1350 return meta->getInventory();
1353 case InventoryLocation::DETACHED:
1355 if (m_detached_inventories.count(loc.name) == 0)
1357 return m_detached_inventories[loc.name];
1361 FATAL_ERROR("Invalid inventory location type.");
1367 void Client::inventoryAction(InventoryAction *a)
1370 Send it to the server
1372 sendInventoryAction(a);
1375 Predict some local inventory changes
1377 a->clientApply(this, this);
1383 float Client::getAnimationTime()
1385 return m_animation_time;
1388 int Client::getCrackLevel()
1390 return m_crack_level;
1393 v3s16 Client::getCrackPos()
1398 void Client::setCrack(int level, v3s16 pos)
1400 int old_crack_level = m_crack_level;
1401 v3s16 old_crack_pos = m_crack_pos;
1403 m_crack_level = level;
1406 if(old_crack_level >= 0 && (level < 0 || pos != old_crack_pos))
1409 addUpdateMeshTaskForNode(old_crack_pos, false, true);
1411 if(level >= 0 && (old_crack_level < 0 || pos != old_crack_pos))
1414 addUpdateMeshTaskForNode(pos, false, true);
1420 LocalPlayer *player = m_env.getLocalPlayer();
1425 bool Client::getChatMessage(std::wstring &res)
1427 if (m_chat_queue.empty())
1430 ChatMessage *chatMessage = m_chat_queue.front();
1435 switch (chatMessage->type) {
1436 case CHATMESSAGE_TYPE_RAW:
1437 case CHATMESSAGE_TYPE_ANNOUNCE:
1438 case CHATMESSAGE_TYPE_SYSTEM:
1439 res = chatMessage->message;
1441 case CHATMESSAGE_TYPE_NORMAL: {
1442 if (!chatMessage->sender.empty())
1443 res = L"<" + chatMessage->sender + L"> " + chatMessage->message;
1445 res = chatMessage->message;
1456 void Client::typeChatMessage(const std::wstring &message)
1458 // Discard empty line
1459 if (message.empty())
1462 // If message was ate by script API, don't send it to server
1463 if (m_script->on_sending_message(wide_to_utf8(message))) {
1468 sendChatMessage(message);
1471 if (message[0] != L'/') {
1472 // compatibility code
1473 if (m_proto_ver < 29) {
1474 LocalPlayer *player = m_env.getLocalPlayer();
1476 std::wstring name = narrow_to_wide(player->getName());
1477 pushToChatQueue(new ChatMessage(CHATMESSAGE_TYPE_NORMAL, message, name));
1482 void Client::addUpdateMeshTask(v3s16 p, bool ack_to_server, bool urgent)
1484 // Check if the block exists to begin with. In the case when a non-existing
1485 // neighbor is automatically added, it may not. In that case we don't want
1486 // to tell the mesh update thread about it.
1487 MapBlock *b = m_env.getMap().getBlockNoCreateNoEx(p);
1491 m_mesh_update_thread.updateBlock(&m_env.getMap(), p, ack_to_server, urgent);
1494 void Client::addUpdateMeshTaskWithEdge(v3s16 blockpos, bool ack_to_server, bool urgent)
1497 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1499 catch(InvalidPositionException &e){}
1502 for (int i=0;i<6;i++)
1505 v3s16 p = blockpos + g_6dirs[i];
1506 addUpdateMeshTask(p, false, urgent);
1508 catch(InvalidPositionException &e){}
1512 void Client::addUpdateMeshTaskForNode(v3s16 nodepos, bool ack_to_server, bool urgent)
1516 infostream<<"Client::addUpdateMeshTaskForNode(): "
1517 <<"("<<p.X<<","<<p.Y<<","<<p.Z<<")"
1521 v3s16 blockpos = getNodeBlockPos(nodepos);
1522 v3s16 blockpos_relative = blockpos * MAP_BLOCKSIZE;
1525 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1527 catch(InvalidPositionException &e) {}
1530 if(nodepos.X == blockpos_relative.X){
1532 v3s16 p = blockpos + v3s16(-1,0,0);
1533 addUpdateMeshTask(p, false, urgent);
1535 catch(InvalidPositionException &e){}
1538 if(nodepos.Y == blockpos_relative.Y){
1540 v3s16 p = blockpos + v3s16(0,-1,0);
1541 addUpdateMeshTask(p, false, urgent);
1543 catch(InvalidPositionException &e){}
1546 if(nodepos.Z == blockpos_relative.Z){
1548 v3s16 p = blockpos + v3s16(0,0,-1);
1549 addUpdateMeshTask(p, false, urgent);
1551 catch(InvalidPositionException &e){}
1555 ClientEvent *Client::getClientEvent()
1557 FATAL_ERROR_IF(m_client_event_queue.empty(),
1558 "Cannot getClientEvent, queue is empty.");
1560 ClientEvent *event = m_client_event_queue.front();
1561 m_client_event_queue.pop();
1565 bool Client::connectedToServer()
1567 return m_con->Connected();
1570 const Address Client::getServerAddress()
1572 return m_con->GetPeerAddress(PEER_ID_SERVER);
1575 float Client::mediaReceiveProgress()
1577 if (m_media_downloader)
1578 return m_media_downloader->getProgress();
1580 return 1.0; // downloader only exists when not yet done
1583 typedef struct TextureUpdateArgs {
1584 gui::IGUIEnvironment *guienv;
1587 const wchar_t* text_base;
1588 ITextureSource *tsrc;
1589 } TextureUpdateArgs;
1591 void texture_update_progress(void *args, u32 progress, u32 max_progress)
1593 TextureUpdateArgs* targs = (TextureUpdateArgs*) args;
1594 u16 cur_percent = ceil(progress / (double) max_progress * 100.);
1596 // update the loading menu -- if neccessary
1597 bool do_draw = false;
1598 u64 time_ms = targs->last_time_ms;
1599 if (cur_percent != targs->last_percent) {
1600 targs->last_percent = cur_percent;
1601 time_ms = porting::getTimeMs();
1602 // only draw when the user will notice something:
1603 do_draw = (time_ms - targs->last_time_ms > 100);
1607 targs->last_time_ms = time_ms;
1608 std::basic_stringstream<wchar_t> strm;
1609 strm << targs->text_base << " " << targs->last_percent << "%...";
1610 RenderingEngine::draw_load_screen(strm.str(), targs->guienv, targs->tsrc, 0,
1611 72 + (u16) ((18. / 100.) * (double) targs->last_percent), true);
1615 void Client::afterContentReceived()
1617 infostream<<"Client::afterContentReceived() started"<<std::endl;
1618 assert(m_itemdef_received); // pre-condition
1619 assert(m_nodedef_received); // pre-condition
1620 assert(mediaReceived()); // pre-condition
1622 const wchar_t* text = wgettext("Loading textures...");
1624 // Clear cached pre-scaled 2D GUI images, as this cache
1625 // might have images with the same name but different
1626 // content from previous sessions.
1627 guiScalingCacheClear();
1629 // Rebuild inherited images and recreate textures
1630 infostream<<"- Rebuilding images and textures"<<std::endl;
1631 RenderingEngine::draw_load_screen(text, guienv, m_tsrc, 0, 70);
1632 m_tsrc->rebuildImagesAndTextures();
1636 infostream<<"- Rebuilding shaders"<<std::endl;
1637 text = wgettext("Rebuilding shaders...");
1638 RenderingEngine::draw_load_screen(text, guienv, m_tsrc, 0, 71);
1639 m_shsrc->rebuildShaders();
1642 // Update node aliases
1643 infostream<<"- Updating node aliases"<<std::endl;
1644 text = wgettext("Initializing nodes...");
1645 RenderingEngine::draw_load_screen(text, guienv, m_tsrc, 0, 72);
1646 m_nodedef->updateAliases(m_itemdef);
1647 for (const auto &path : getTextureDirs())
1648 m_nodedef->applyTextureOverrides(path + DIR_DELIM + "override.txt");
1649 m_nodedef->setNodeRegistrationStatus(true);
1650 m_nodedef->runNodeResolveCallbacks();
1653 // Update node textures and assign shaders to each tile
1654 infostream<<"- Updating node textures"<<std::endl;
1655 TextureUpdateArgs tu_args;
1656 tu_args.guienv = guienv;
1657 tu_args.last_time_ms = porting::getTimeMs();
1658 tu_args.last_percent = 0;
1659 tu_args.text_base = wgettext("Initializing nodes");
1660 tu_args.tsrc = m_tsrc;
1661 m_nodedef->updateTextures(this, texture_update_progress, &tu_args);
1662 delete[] tu_args.text_base;
1664 // Start mesh update thread after setting up content definitions
1665 infostream<<"- Starting mesh update thread"<<std::endl;
1666 m_mesh_update_thread.start();
1671 if (g_settings->getBool("enable_client_modding")) {
1672 m_script->on_client_ready(m_env.getLocalPlayer());
1673 m_script->on_connect();
1676 text = wgettext("Done!");
1677 RenderingEngine::draw_load_screen(text, guienv, m_tsrc, 0, 100);
1678 infostream<<"Client::afterContentReceived() done"<<std::endl;
1682 float Client::getRTT()
1684 return m_con->getPeerStat(PEER_ID_SERVER,con::AVG_RTT);
1687 float Client::getCurRate()
1689 return (m_con->getLocalStat(con::CUR_INC_RATE) +
1690 m_con->getLocalStat(con::CUR_DL_RATE));
1693 void Client::makeScreenshot()
1695 irr::video::IVideoDriver *driver = RenderingEngine::get_video_driver();
1696 irr::video::IImage* const raw_image = driver->createScreenShot();
1701 time_t t = time(NULL);
1702 struct tm *tm = localtime(&t);
1704 char timetstamp_c[64];
1705 strftime(timetstamp_c, sizeof(timetstamp_c), "%Y%m%d_%H%M%S", tm);
1707 std::string filename_base = g_settings->get("screenshot_path")
1709 + std::string("screenshot_")
1710 + std::string(timetstamp_c);
1711 std::string filename_ext = "." + g_settings->get("screenshot_format");
1712 std::string filename;
1714 u32 quality = (u32)g_settings->getS32("screenshot_quality");
1715 quality = MYMIN(MYMAX(quality, 0), 100) / 100.0 * 255;
1717 // Try to find a unique filename
1718 unsigned serial = 0;
1720 while (serial < SCREENSHOT_MAX_SERIAL_TRIES) {
1721 filename = filename_base + (serial > 0 ? ("_" + itos(serial)) : "") + filename_ext;
1722 std::ifstream tmp(filename.c_str());
1724 break; // File did not apparently exist, we'll go with it
1728 if (serial == SCREENSHOT_MAX_SERIAL_TRIES) {
1729 infostream << "Could not find suitable filename for screenshot" << std::endl;
1731 irr::video::IImage* const image =
1732 driver->createImage(video::ECF_R8G8B8, raw_image->getDimension());
1735 raw_image->copyTo(image);
1737 std::ostringstream sstr;
1738 if (driver->writeImageToFile(image, filename.c_str(), quality)) {
1739 sstr << "Saved screenshot to '" << filename << "'";
1741 sstr << "Failed to save screenshot '" << filename << "'";
1743 pushToChatQueue(new ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
1744 narrow_to_wide(sstr.str())));
1745 infostream << sstr.str() << std::endl;
1753 bool Client::shouldShowMinimap() const
1755 return !m_minimap_disabled_by_server;
1758 void Client::pushToEventQueue(ClientEvent *event)
1760 m_client_event_queue.push(event);
1763 void Client::showGameChat(const bool show)
1765 m_game_ui_flags->show_chat = show;
1768 void Client::showGameHud(const bool show)
1770 m_game_ui_flags->show_hud = show;
1773 void Client::showMinimap(const bool show)
1775 m_game_ui_flags->show_minimap = show;
1778 void Client::showProfiler(const bool show)
1780 m_game_ui_flags->show_profiler_graph = show;
1783 void Client::showGameFog(const bool show)
1785 m_game_ui_flags->force_fog_off = !show;
1788 void Client::showGameDebug(const bool show)
1790 m_game_ui_flags->show_debug = show;
1793 // IGameDef interface
1795 IItemDefManager* Client::getItemDefManager()
1799 INodeDefManager* Client::getNodeDefManager()
1803 ICraftDefManager* Client::getCraftDefManager()
1806 //return m_craftdef;
1808 ITextureSource* Client::getTextureSource()
1812 IShaderSource* Client::getShaderSource()
1817 u16 Client::allocateUnknownNodeId(const std::string &name)
1819 errorstream << "Client::allocateUnknownNodeId(): "
1820 << "Client cannot allocate node IDs" << std::endl;
1821 FATAL_ERROR("Client allocated unknown node");
1823 return CONTENT_IGNORE;
1825 ISoundManager* Client::getSoundManager()
1829 MtEventManager* Client::getEventManager()
1834 ParticleManager* Client::getParticleManager()
1836 return &m_particle_manager;
1839 scene::IAnimatedMesh* Client::getMesh(const std::string &filename, bool cache)
1841 StringMap::const_iterator it = m_mesh_data.find(filename);
1842 if (it == m_mesh_data.end()) {
1843 errorstream << "Client::getMesh(): Mesh not found: \"" << filename
1844 << "\"" << std::endl;
1847 const std::string &data = it->second;
1849 // Create the mesh, remove it from cache and return it
1850 // This allows unique vertex colors and other properties for each instance
1851 Buffer<char> data_rw(data.c_str(), data.size()); // Const-incorrect Irrlicht
1852 io::IReadFile *rfile = RenderingEngine::get_filesystem()->createMemoryReadFile(
1853 *data_rw, data_rw.getSize(), filename.c_str());
1854 FATAL_ERROR_IF(!rfile, "Could not create/open RAM file");
1856 scene::IAnimatedMesh *mesh = RenderingEngine::get_scene_manager()->getMesh(rfile);
1860 RenderingEngine::get_mesh_cache()->removeMesh(mesh);
1864 const std::string* Client::getModFile(const std::string &filename)
1866 StringMap::const_iterator it = m_mod_files.find(filename);
1867 if (it == m_mod_files.end()) {
1868 errorstream << "Client::getModFile(): File not found: \"" << filename
1869 << "\"" << std::endl;
1875 bool Client::registerModStorage(ModMetadata *storage)
1877 if (m_mod_storages.find(storage->getModName()) != m_mod_storages.end()) {
1878 errorstream << "Unable to register same mod storage twice. Storage name: "
1879 << storage->getModName() << std::endl;
1883 m_mod_storages[storage->getModName()] = storage;
1887 void Client::unregisterModStorage(const std::string &name)
1889 std::unordered_map<std::string, ModMetadata *>::const_iterator it =
1890 m_mod_storages.find(name);
1891 if (it != m_mod_storages.end()) {
1892 // Save unconditionaly on unregistration
1893 it->second->save(getModStoragePath());
1894 m_mod_storages.erase(name);
1898 std::string Client::getModStoragePath() const
1900 return porting::path_user + DIR_DELIM + "client" + DIR_DELIM + "mod_storage";
1907 bool Client::joinModChannel(const std::string &channel)
1909 if (m_modchannel_mgr->channelRegistered(channel))
1912 NetworkPacket pkt(TOSERVER_MODCHANNEL_JOIN, 2 + channel.size());
1916 m_modchannel_mgr->joinChannel(channel, 0);
1920 bool Client::leaveModChannel(const std::string &channel)
1922 if (!m_modchannel_mgr->channelRegistered(channel))
1925 NetworkPacket pkt(TOSERVER_MODCHANNEL_LEAVE, 2 + channel.size());
1929 m_modchannel_mgr->leaveChannel(channel, 0);
1933 bool Client::sendModChannelMessage(const std::string &channel, const std::string &message)
1935 if (!m_modchannel_mgr->canWriteOnChannel(channel))
1938 if (message.size() > STRING_MAX_LEN) {
1939 warningstream << "ModChannel message too long, dropping before sending "
1940 << " (" << message.size() << " > " << STRING_MAX_LEN << ", channel: "
1941 << channel << ")" << std::endl;
1945 // @TODO: do some client rate limiting
1946 NetworkPacket pkt(TOSERVER_MODCHANNEL_MSG, 2 + channel.size() + 2 + message.size());
1947 pkt << channel << message;
1952 ModChannel* Client::getModChannel(const std::string &channel)
1954 return m_modchannel_mgr->getModChannel(channel);