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/gameui.h"
32 #include "client/renderingengine.h"
33 #include "client/sound.h"
34 #include "client/tile.h"
35 #include "util/auth.h"
36 #include "util/directiontables.h"
37 #include "util/pointedthing.h"
38 #include "util/serialize.h"
39 #include "util/string.h"
42 #include "mapblock_mesh.h"
45 #include "modchannels.h"
46 #include "content/mods.h"
50 #include "clientmap.h"
51 #include "clientmedia.h"
53 #include "database/database-sqlite3.h"
54 #include "serialization.h"
55 #include "guiscalingfilter.h"
56 #include "script/scripting_client.h"
58 #include "chatmessage.h"
59 #include "translation.h"
61 extern gui::IGUIEnvironment* guienv;
67 u32 PacketCounter::sum() const
70 for (const auto &it : m_packets)
75 void PacketCounter::print(std::ostream &o) const
77 for (const auto &it : m_packets) {
78 auto name = it.first >= TOCLIENT_NUM_MSG_TYPES ? "?"
79 : toClientCommandTable[it.first].name;
80 o << "cmd " << it.first << " (" << name << ") count "
81 << it.second << std::endl;
90 const char *playername,
91 const std::string &password,
92 const std::string &address_name,
93 MapDrawControl &control,
94 IWritableTextureSource *tsrc,
95 IWritableShaderSource *shsrc,
96 IWritableItemDefManager *itemdef,
97 NodeDefManager *nodedef,
99 MtEventManager *event,
100 RenderingEngine *rendering_engine,
110 m_rendering_engine(rendering_engine),
111 m_mesh_update_thread(this),
113 new ClientMap(this, rendering_engine, control, 666),
116 m_particle_manager(&m_env),
117 m_con(new con::Connection(PROTOCOL_ID, 512, CONNECTION_TIMEOUT, ipv6, this)),
118 m_address_name(address_name),
119 m_server_ser_ver(SER_FMT_VER_INVALID),
120 m_last_chat_message_sent(time(NULL)),
121 m_password(password),
122 m_chosen_auth_mech(AUTH_MECHANISM_NONE),
123 m_media_downloader(new ClientMediaDownloader()),
126 m_modchannel_mgr(new ModChannelMgr())
129 m_env.setLocalPlayer(new LocalPlayer(this, playername));
131 if (g_settings->getBool("enable_minimap")) {
132 m_minimap = new Minimap(this);
135 m_cache_save_interval = g_settings->getU16("server_map_save_interval");
138 void Client::loadMods()
140 // Don't load mods twice.
141 // If client scripting is disabled by the client, don't load builtin or
142 // client-provided mods.
143 if (m_mods_loaded || !g_settings->getBool("enable_client_modding"))
146 // If client scripting is disabled by the server, don't load builtin or
147 // client-provided mods.
148 // TODO Delete this code block when server-sent CSM and verifying of builtin are
150 if (checkCSMRestrictionFlag(CSMRestrictionFlags::CSM_RF_LOAD_CLIENT_MODS)) {
151 warningstream << "Client-provided mod loading is disabled by server." <<
156 m_script = new ClientScripting(this);
157 m_env.setScript(m_script);
158 m_script->setEnv(&m_env);
161 scanModIntoMemory(BUILTIN_MOD_NAME, getBuiltinLuaPath());
162 m_script->loadModFromMemory(BUILTIN_MOD_NAME);
164 ClientModConfiguration modconf(getClientModsLuaPath());
165 m_mods = modconf.getMods();
166 // complain about mods with unsatisfied dependencies
167 if (!modconf.isConsistent()) {
168 modconf.printUnsatisfiedModsError();
173 infostream << "Client loading mods: ";
174 for (const ModSpec &mod : m_mods)
175 infostream << mod.name << " ";
176 infostream << std::endl;
178 // Load "mod" scripts
179 for (const ModSpec &mod : m_mods) {
180 if (!string_allowed(mod.name, MODNAME_ALLOWED_CHARS)) {
181 throw ModError("Error loading mod \"" + mod.name +
182 "\": Mod name does not follow naming conventions: "
183 "Only characters [a-z0-9_] are allowed.");
185 scanModIntoMemory(mod.name, mod.path);
189 for (const ModSpec &mod : m_mods)
190 m_script->loadModFromMemory(mod.name);
192 // Mods are done loading. Unlock callbacks
193 m_mods_loaded = true;
195 // Run a callback when mods are loaded
196 m_script->on_mods_loaded();
198 // Create objects if they're ready
199 if (m_state == LC_Ready)
200 m_script->on_client_ready(m_env.getLocalPlayer());
202 m_script->on_camera_ready(m_camera);
204 m_script->on_minimap_ready(m_minimap);
207 void Client::scanModSubfolder(const std::string &mod_name, const std::string &mod_path,
208 std::string mod_subpath)
210 std::string full_path = mod_path + DIR_DELIM + mod_subpath;
211 std::vector<fs::DirListNode> mod = fs::GetDirListing(full_path);
212 for (const fs::DirListNode &j : mod) {
213 if (j.name[0] == '.')
217 scanModSubfolder(mod_name, mod_path, mod_subpath + j.name + DIR_DELIM);
220 std::replace(mod_subpath.begin(), mod_subpath.end(), DIR_DELIM_CHAR, '/');
222 std::string real_path = full_path + j.name;
223 std::string vfs_path = mod_name + ":" + mod_subpath + j.name;
224 infostream << "Client::scanModSubfolder(): Loading \"" << real_path
225 << "\" as \"" << vfs_path << "\"." << std::endl;
227 std::string contents;
228 if (!fs::ReadFile(real_path, contents)) {
229 errorstream << "Client::scanModSubfolder(): Can't read file \""
230 << real_path << "\"." << std::endl;
234 m_mod_vfs.emplace(vfs_path, contents);
238 const std::string &Client::getBuiltinLuaPath()
240 static const std::string builtin_dir = porting::path_share + DIR_DELIM + "builtin";
244 const std::string &Client::getClientModsLuaPath()
246 static const std::string clientmods_dir = porting::path_share + DIR_DELIM + "clientmods";
247 return clientmods_dir;
250 const std::vector<ModSpec>& Client::getMods() const
252 static std::vector<ModSpec> client_modspec_temp;
253 return client_modspec_temp;
256 const ModSpec* Client::getModSpec(const std::string &modname) const
265 m_script->on_shutdown();
266 //request all client managed threads to stop
267 m_mesh_update_thread.stop();
268 // Save local server map
270 infostream << "Local map saving ended." << std::endl;
271 m_localdb->endSave();
278 bool Client::isShutdown()
280 return m_shutdown || !m_mesh_update_thread.isRunning();
290 m_mesh_update_thread.stop();
291 m_mesh_update_thread.wait();
292 while (!m_mesh_update_thread.m_queue_out.empty()) {
293 MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_frontNoEx();
298 delete m_inventory_from_server;
300 // Delete detached inventories
301 for (auto &m_detached_inventorie : m_detached_inventories) {
302 delete m_detached_inventorie.second;
305 // cleanup 3d model meshes on client shutdown
306 m_rendering_engine->cleanupMeshCache();
311 delete m_media_downloader;
314 void Client::connect(Address address, bool is_local_server)
316 initLocalMapSaving(address, m_address_name, is_local_server);
318 // Since we use TryReceive() a timeout here would be ineffective anyway
319 m_con->SetTimeoutMs(0);
320 m_con->Connect(address);
323 void Client::step(float dtime)
329 m_animation_time += dtime;
330 if(m_animation_time > 60.0)
331 m_animation_time -= 60.0;
333 m_time_of_day_update_timer += dtime;
341 float &counter = m_packetcounter_timer;
346 u32 sum = m_packetcounter.sum();
347 float avg = sum / counter;
349 infostream << "Client packetcounter (" << counter << "s): "
350 << "sum=" << sum << " avg=" << avg << "/s" << std::endl;
351 m_packetcounter.print(infostream);
352 m_packetcounter.clear();
356 // UGLY hack to fix 2 second startup delay caused by non existent
357 // server client startup synchronization in local server or singleplayer mode
358 static bool initial_step = true;
360 initial_step = false;
362 else if(m_state == LC_Created) {
363 if (m_is_registration_confirmation_state) {
364 // Waiting confirmation
367 float &counter = m_connection_reinit_timer;
372 LocalPlayer *myplayer = m_env.getLocalPlayer();
373 FATAL_ERROR_IF(myplayer == NULL, "Local player not found in environment.");
375 sendInit(myplayer->getName());
378 // Not connected, return
383 Do stuff if connected
387 Run Map's timers and unload unused data
389 const float map_timer_and_unload_dtime = 5.25;
390 if(m_map_timer_and_unload_interval.step(dtime, map_timer_and_unload_dtime)) {
391 std::vector<v3s16> deleted_blocks;
392 m_env.getMap().timerUpdate(map_timer_and_unload_dtime,
393 g_settings->getFloat("client_unload_unused_data_timeout"),
394 g_settings->getS32("client_mapblock_limit"),
399 NOTE: This loop is intentionally iterated the way it is.
402 std::vector<v3s16>::iterator i = deleted_blocks.begin();
403 std::vector<v3s16> sendlist;
405 if(sendlist.size() == 255 || i == deleted_blocks.end()) {
416 sendDeletedBlocks(sendlist);
418 if(i == deleted_blocks.end())
424 sendlist.push_back(*i);
430 Send pending messages on out chat queue
432 if (!m_out_chat_queue.empty() && canSendChatMessage()) {
433 sendChatMessage(m_out_chat_queue.front());
434 m_out_chat_queue.pop();
440 LocalPlayer *player = m_env.getLocalPlayer();
442 // Step environment (also handles player controls)
444 m_sound->step(dtime);
449 while (m_env.hasClientEnvEvents()) {
450 ClientEnvEvent envEvent = m_env.getClientEnvEvent();
452 if (envEvent.type == CEE_PLAYER_DAMAGE) {
453 u16 damage = envEvent.player_damage.amount;
455 if (envEvent.player_damage.send_to_server)
458 // Add to ClientEvent queue
459 ClientEvent *event = new ClientEvent();
460 event->type = CE_PLAYER_DAMAGE;
461 event->player_damage.amount = damage;
462 m_client_event_queue.push(event);
469 float &counter = m_avg_rtt_timer;
473 // connectedAndInitialized() is true, peer exists.
474 float avg_rtt = getRTT();
475 infostream << "Client: avg_rtt=" << avg_rtt << std::endl;
479 Send player position to server
482 float &counter = m_playerpos_send_timer;
484 if((m_state == LC_Ready) && (counter >= m_recommended_send_interval))
492 Replace updated meshes
495 int num_processed_meshes = 0;
496 std::vector<v3s16> blocks_to_ack;
497 while (!m_mesh_update_thread.m_queue_out.empty())
499 num_processed_meshes++;
501 MinimapMapblock *minimap_mapblock = NULL;
502 bool do_mapper_update = true;
504 MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_frontNoEx();
505 MapBlock *block = m_env.getMap().getBlockNoCreateNoEx(r.p);
507 // Delete the old mesh
509 block->mesh = nullptr;
512 minimap_mapblock = r.mesh->moveMinimapMapblock();
513 if (minimap_mapblock == NULL)
514 do_mapper_update = false;
516 bool is_empty = true;
517 for (int l = 0; l < MAX_TILE_LAYERS; l++)
518 if (r.mesh->getMesh(l)->getMeshBufferCount() != 0)
524 // Replace with the new mesh
525 block->mesh = r.mesh;
531 if (m_minimap && do_mapper_update)
532 m_minimap->addBlock(r.p, minimap_mapblock);
534 if (r.ack_block_to_server) {
535 if (blocks_to_ack.size() == 255) {
536 sendGotBlocks(blocks_to_ack);
537 blocks_to_ack.clear();
540 blocks_to_ack.emplace_back(r.p);
543 if (blocks_to_ack.size() > 0) {
544 // Acknowledge block(s)
545 sendGotBlocks(blocks_to_ack);
548 if (num_processed_meshes > 0)
549 g_profiler->graphAdd("num_processed_meshes", num_processed_meshes);
555 if (m_media_downloader && m_media_downloader->isStarted()) {
556 m_media_downloader->step(this);
557 if (m_media_downloader->isDone()) {
558 delete m_media_downloader;
559 m_media_downloader = NULL;
564 If the server didn't update the inventory in a while, revert
565 the local inventory (so the player notices the lag problem
566 and knows something is wrong).
568 if (m_inventory_from_server) {
569 float interval = 10.0f;
570 float count_before = std::floor(m_inventory_from_server_age / interval);
572 m_inventory_from_server_age += dtime;
574 float count_after = std::floor(m_inventory_from_server_age / interval);
576 if (count_after != count_before) {
577 // Do this every <interval> seconds after TOCLIENT_INVENTORY
578 // Reset the locally changed inventory to the authoritative inventory
579 player->inventory = *m_inventory_from_server;
580 m_update_wielded_item = true;
585 Update positions of sounds attached to objects
588 for (auto &m_sounds_to_object : m_sounds_to_objects) {
589 int client_id = m_sounds_to_object.first;
590 u16 object_id = m_sounds_to_object.second;
591 ClientActiveObject *cao = m_env.getActiveObject(object_id);
594 m_sound->updateSoundPosition(client_id, cao->getPosition());
599 Handle removed remotely initiated sounds
601 m_removed_sounds_check_timer += dtime;
602 if(m_removed_sounds_check_timer >= 2.32) {
603 m_removed_sounds_check_timer = 0;
604 // Find removed sounds and clear references to them
605 std::vector<s32> removed_server_ids;
606 for (std::unordered_map<s32, int>::iterator i = m_sounds_server_to_client.begin();
607 i != m_sounds_server_to_client.end();) {
608 s32 server_id = i->first;
609 int client_id = i->second;
611 if(!m_sound->soundExists(client_id)) {
612 m_sounds_server_to_client.erase(server_id);
613 m_sounds_client_to_server.erase(client_id);
614 m_sounds_to_objects.erase(client_id);
615 removed_server_ids.push_back(server_id);
620 if(!removed_server_ids.empty()) {
621 sendRemovedSounds(removed_server_ids);
625 m_mod_storage_save_timer -= dtime;
626 if (m_mod_storage_save_timer <= 0.0f) {
627 m_mod_storage_save_timer = g_settings->getFloat("server_map_save_interval");
629 for (std::unordered_map<std::string, ModMetadata *>::const_iterator
630 it = m_mod_storages.begin(); it != m_mod_storages.end(); ++it) {
631 if (it->second->isModified()) {
632 it->second->save(getModStoragePath());
637 infostream << "Saved " << n << " modified mod storages." << std::endl;
641 if (m_localdb && m_localdb_save_interval.step(dtime,
642 m_cache_save_interval)) {
643 m_localdb->endSave();
644 m_localdb->beginSave();
648 bool Client::loadMedia(const std::string &data, const std::string &filename,
649 bool from_media_push)
653 const char *image_ext[] = {
654 ".png", ".jpg", ".bmp", ".tga",
655 ".pcx", ".ppm", ".psd", ".wal", ".rgb",
658 name = removeStringEnd(filename, image_ext);
660 TRACESTREAM(<< "Client: Attempting to load image "
661 << "file \"" << filename << "\"" << std::endl);
663 io::IFileSystem *irrfs = m_rendering_engine->get_filesystem();
664 video::IVideoDriver *vdrv = m_rendering_engine->get_video_driver();
666 io::IReadFile *rfile = irrfs->createMemoryReadFile(
667 data.c_str(), data.size(), "_tempreadfile");
669 FATAL_ERROR_IF(!rfile, "Could not create irrlicht memory file.");
672 video::IImage *img = vdrv->createImageFromFile(rfile);
674 errorstream<<"Client: Cannot create image from data of "
675 <<"file \""<<filename<<"\""<<std::endl;
680 m_tsrc->insertSourceImage(filename, img);
686 const char *sound_ext[] = {
687 ".0.ogg", ".1.ogg", ".2.ogg", ".3.ogg", ".4.ogg",
688 ".5.ogg", ".6.ogg", ".7.ogg", ".8.ogg", ".9.ogg",
691 name = removeStringEnd(filename, sound_ext);
693 TRACESTREAM(<< "Client: Attempting to load sound "
694 << "file \"" << filename << "\"" << std::endl);
695 return m_sound->loadSoundData(name, data);
698 const char *model_ext[] = {
699 ".x", ".b3d", ".md2", ".obj",
702 name = removeStringEnd(filename, model_ext);
704 verbosestream<<"Client: Storing model into memory: "
705 <<"\""<<filename<<"\""<<std::endl;
706 if(m_mesh_data.count(filename))
707 errorstream<<"Multiple models with name \""<<filename.c_str()
708 <<"\" found; replacing previous model"<<std::endl;
709 m_mesh_data[filename] = data;
713 const char *translate_ext[] = {
716 name = removeStringEnd(filename, translate_ext);
720 TRACESTREAM(<< "Client: Loading translation: "
721 << "\"" << filename << "\"" << std::endl);
722 g_client_translations->loadTranslation(data);
726 errorstream << "Client: Don't know how to load file \""
727 << filename << "\"" << std::endl;
731 // Virtual methods from con::PeerHandler
732 void Client::peerAdded(con::Peer *peer)
734 infostream << "Client::peerAdded(): peer->id="
735 << peer->id << std::endl;
737 void Client::deletingPeer(con::Peer *peer, bool timeout)
739 infostream << "Client::deletingPeer(): "
740 "Server Peer is getting deleted "
741 << "(timeout=" << timeout << ")" << std::endl;
744 m_access_denied = true;
745 m_access_denied_reason = gettext("Connection timed out.");
751 u16 number of files requested
757 void Client::request_media(const std::vector<std::string> &file_requests)
759 std::ostringstream os(std::ios_base::binary);
760 writeU16(os, TOSERVER_REQUEST_MEDIA);
761 size_t file_requests_size = file_requests.size();
763 FATAL_ERROR_IF(file_requests_size > 0xFFFF, "Unsupported number of file requests");
765 // Packet dynamicly resized
766 NetworkPacket pkt(TOSERVER_REQUEST_MEDIA, 2 + 0);
768 pkt << (u16) (file_requests_size & 0xFFFF);
770 for (const std::string &file_request : file_requests) {
776 infostream << "Client: Sending media request list to server ("
777 << file_requests.size() << " files. packet size)" << std::endl;
780 void Client::initLocalMapSaving(const Address &address,
781 const std::string &hostname,
782 bool is_local_server)
784 if (!g_settings->getBool("enable_local_map_saving") || is_local_server) {
788 std::string world_path;
789 #define set_world_path(hostname) \
790 world_path = porting::path_user \
791 + DIR_DELIM + "worlds" \
792 + DIR_DELIM + "server_" \
793 + hostname + "_" + std::to_string(address.getPort());
795 set_world_path(hostname);
796 if (!fs::IsDir(world_path)) {
797 std::string hostname_escaped = hostname;
798 str_replace(hostname_escaped, ':', '_');
799 set_world_path(hostname_escaped);
801 #undef set_world_path
802 fs::CreateAllDirs(world_path);
804 m_localdb = new MapDatabaseSQLite3(world_path);
805 m_localdb->beginSave();
806 actionstream << "Local map saving started, map will be saved at '" << world_path << "'" << std::endl;
809 void Client::ReceiveAll()
812 u64 start_ms = porting::getTimeMs();
813 const u64 budget = 100;
815 // Limit time even if there would be huge amounts of data to
817 if (porting::getTimeMs() > start_ms + budget) {
818 infostream << "Client::ReceiveAll(): "
819 "Packet processing budget exceeded." << std::endl;
825 if (!m_con->TryReceive(&pkt))
828 } catch (const con::InvalidIncomingDataException &e) {
829 infostream << "Client::ReceiveAll(): "
830 "InvalidIncomingDataException: what()="
831 << e.what() << std::endl;
836 inline void Client::handleCommand(NetworkPacket* pkt)
838 const ToClientCommandHandler& opHandle = toClientCommandTable[pkt->getCommand()];
839 (this->*opHandle.handler)(pkt);
843 sender_peer_id given to this shall be quaranteed to be a valid peer
845 void Client::ProcessData(NetworkPacket *pkt)
847 ToClientCommand command = (ToClientCommand) pkt->getCommand();
848 u32 sender_peer_id = pkt->getPeerId();
850 //infostream<<"Client: received command="<<command<<std::endl;
851 m_packetcounter.add((u16)command);
852 g_profiler->graphAdd("client_received_packets", 1);
855 If this check is removed, be sure to change the queue
856 system to know the ids
858 if(sender_peer_id != PEER_ID_SERVER) {
859 infostream << "Client::ProcessData(): Discarding data not "
860 "coming from server: peer_id=" << sender_peer_id
865 // Command must be handled into ToClientCommandHandler
866 if (command >= TOCLIENT_NUM_MSG_TYPES) {
867 infostream << "Client: Ignoring unknown command "
868 << command << std::endl;
873 * Those packets are handled before m_server_ser_ver is set, it's normal
874 * But we must use the new ToClientConnectionState in the future,
877 if(toClientCommandTable[command].state == TOCLIENT_STATE_NOT_CONNECTED) {
882 if(m_server_ser_ver == SER_FMT_VER_INVALID) {
883 infostream << "Client: Server serialization"
884 " format invalid or not initialized."
885 " Skipping incoming command=" << command << std::endl;
890 Handle runtime commands
896 void Client::Send(NetworkPacket* pkt)
898 m_con->Send(PEER_ID_SERVER,
899 serverCommandFactoryTable[pkt->getCommand()].channel,
901 serverCommandFactoryTable[pkt->getCommand()].reliable);
904 // Will fill up 12 + 12 + 4 + 4 + 4 bytes
905 void writePlayerPos(LocalPlayer *myplayer, ClientMap *clientMap, NetworkPacket *pkt)
907 v3f pf = myplayer->getPosition() * 100;
908 v3f sf = myplayer->getSpeed() * 100;
909 s32 pitch = myplayer->getPitch() * 100;
910 s32 yaw = myplayer->getYaw() * 100;
911 u32 keyPressed = myplayer->keyPressed;
912 // scaled by 80, so that pi can fit into a u8
913 u8 fov = clientMap->getCameraFov() * 80;
914 u8 wanted_range = MYMIN(255,
915 std::ceil(clientMap->getControl().wanted_range / MAP_BLOCKSIZE));
917 v3s32 position(pf.X, pf.Y, pf.Z);
918 v3s32 speed(sf.X, sf.Y, sf.Z);
922 [0] v3s32 position*100
924 [12+12] s32 pitch*100
925 [12+12+4] s32 yaw*100
926 [12+12+4+4] u32 keyPressed
927 [12+12+4+4+4] u8 fov*80
928 [12+12+4+4+4+1] u8 ceil(wanted_range / MAP_BLOCKSIZE)
930 *pkt << position << speed << pitch << yaw << keyPressed;
931 *pkt << fov << wanted_range;
934 void Client::interact(InteractAction action, const PointedThing& pointed)
936 if(m_state != LC_Ready) {
937 errorstream << "Client::interact() "
938 "Canceled (not connected)"
943 LocalPlayer *myplayer = m_env.getLocalPlayer();
944 if (myplayer == NULL)
951 [5] u32 length of the next item (plen)
952 [9] serialized PointedThing
953 [9 + plen] player position information
956 NetworkPacket pkt(TOSERVER_INTERACT, 1 + 2 + 0);
959 pkt << myplayer->getWieldIndex();
961 std::ostringstream tmp_os(std::ios::binary);
962 pointed.serialize(tmp_os);
964 pkt.putLongString(tmp_os.str());
966 writePlayerPos(myplayer, &m_env.getClientMap(), &pkt);
971 void Client::deleteAuthData()
976 switch (m_chosen_auth_mech) {
977 case AUTH_MECHANISM_FIRST_SRP:
979 case AUTH_MECHANISM_SRP:
980 case AUTH_MECHANISM_LEGACY_PASSWORD:
981 srp_user_delete((SRPUser *) m_auth_data);
984 case AUTH_MECHANISM_NONE:
987 m_chosen_auth_mech = AUTH_MECHANISM_NONE;
991 AuthMechanism Client::choseAuthMech(const u32 mechs)
993 if (mechs & AUTH_MECHANISM_SRP)
994 return AUTH_MECHANISM_SRP;
996 if (mechs & AUTH_MECHANISM_FIRST_SRP)
997 return AUTH_MECHANISM_FIRST_SRP;
999 if (mechs & AUTH_MECHANISM_LEGACY_PASSWORD)
1000 return AUTH_MECHANISM_LEGACY_PASSWORD;
1002 return AUTH_MECHANISM_NONE;
1005 void Client::sendInit(const std::string &playerName)
1007 NetworkPacket pkt(TOSERVER_INIT, 1 + 2 + 2 + (1 + playerName.size()));
1009 // we don't support network compression yet
1010 u16 supp_comp_modes = NETPROTO_COMPRESSION_NONE;
1012 pkt << (u8) SER_FMT_VER_HIGHEST_READ << (u16) supp_comp_modes;
1013 pkt << (u16) CLIENT_PROTOCOL_VERSION_MIN << (u16) CLIENT_PROTOCOL_VERSION_MAX;
1019 void Client::promptConfirmRegistration(AuthMechanism chosen_auth_mechanism)
1021 m_chosen_auth_mech = chosen_auth_mechanism;
1022 m_is_registration_confirmation_state = true;
1025 void Client::confirmRegistration()
1027 m_is_registration_confirmation_state = false;
1028 startAuth(m_chosen_auth_mech);
1031 void Client::startAuth(AuthMechanism chosen_auth_mechanism)
1033 m_chosen_auth_mech = chosen_auth_mechanism;
1035 switch (chosen_auth_mechanism) {
1036 case AUTH_MECHANISM_FIRST_SRP: {
1037 // send srp verifier to server
1038 std::string verifier;
1040 generate_srp_verifier_and_salt(getPlayerName(), m_password,
1043 NetworkPacket resp_pkt(TOSERVER_FIRST_SRP, 0);
1044 resp_pkt << salt << verifier << (u8)((m_password.empty()) ? 1 : 0);
1049 case AUTH_MECHANISM_SRP:
1050 case AUTH_MECHANISM_LEGACY_PASSWORD: {
1053 if (chosen_auth_mechanism == AUTH_MECHANISM_LEGACY_PASSWORD) {
1054 m_password = translate_password(getPlayerName(), m_password);
1058 std::string playername_u = lowercase(getPlayerName());
1059 m_auth_data = srp_user_new(SRP_SHA256, SRP_NG_2048,
1060 getPlayerName().c_str(), playername_u.c_str(),
1061 (const unsigned char *) m_password.c_str(),
1062 m_password.length(), NULL, NULL);
1065 SRP_Result res = srp_user_start_authentication(
1066 (struct SRPUser *) m_auth_data, NULL, NULL, 0,
1067 (unsigned char **) &bytes_A, &len_A);
1068 FATAL_ERROR_IF(res != SRP_OK, "Creating local SRP user failed.");
1070 NetworkPacket resp_pkt(TOSERVER_SRP_BYTES_A, 0);
1071 resp_pkt << std::string(bytes_A, len_A) << based_on;
1075 case AUTH_MECHANISM_NONE:
1076 break; // not handled in this method
1080 void Client::sendDeletedBlocks(std::vector<v3s16> &blocks)
1082 NetworkPacket pkt(TOSERVER_DELETEDBLOCKS, 1 + sizeof(v3s16) * blocks.size());
1084 pkt << (u8) blocks.size();
1086 for (const v3s16 &block : blocks) {
1093 void Client::sendGotBlocks(const std::vector<v3s16> &blocks)
1095 NetworkPacket pkt(TOSERVER_GOTBLOCKS, 1 + 6 * blocks.size());
1096 pkt << (u8) blocks.size();
1097 for (const v3s16 &block : blocks)
1103 void Client::sendRemovedSounds(std::vector<s32> &soundList)
1105 size_t server_ids = soundList.size();
1106 assert(server_ids <= 0xFFFF);
1108 NetworkPacket pkt(TOSERVER_REMOVED_SOUNDS, 2 + server_ids * 4);
1110 pkt << (u16) (server_ids & 0xFFFF);
1112 for (s32 sound_id : soundList)
1118 void Client::sendNodemetaFields(v3s16 p, const std::string &formname,
1119 const StringMap &fields)
1121 size_t fields_size = fields.size();
1123 FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of nodemeta fields");
1125 NetworkPacket pkt(TOSERVER_NODEMETA_FIELDS, 0);
1127 pkt << p << formname << (u16) (fields_size & 0xFFFF);
1129 StringMap::const_iterator it;
1130 for (it = fields.begin(); it != fields.end(); ++it) {
1131 const std::string &name = it->first;
1132 const std::string &value = it->second;
1134 pkt.putLongString(value);
1140 void Client::sendInventoryFields(const std::string &formname,
1141 const StringMap &fields)
1143 size_t fields_size = fields.size();
1144 FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of inventory fields");
1146 NetworkPacket pkt(TOSERVER_INVENTORY_FIELDS, 0);
1147 pkt << formname << (u16) (fields_size & 0xFFFF);
1149 StringMap::const_iterator it;
1150 for (it = fields.begin(); it != fields.end(); ++it) {
1151 const std::string &name = it->first;
1152 const std::string &value = it->second;
1154 pkt.putLongString(value);
1160 void Client::sendInventoryAction(InventoryAction *a)
1162 std::ostringstream os(std::ios_base::binary);
1167 std::string s = os.str();
1169 NetworkPacket pkt(TOSERVER_INVENTORY_ACTION, s.size());
1170 pkt.putRawString(s.c_str(),s.size());
1175 bool Client::canSendChatMessage() const
1177 u32 now = time(NULL);
1178 float time_passed = now - m_last_chat_message_sent;
1180 float virt_chat_message_allowance = m_chat_message_allowance + time_passed *
1181 (CLIENT_CHAT_MESSAGE_LIMIT_PER_10S / 8.0f);
1183 if (virt_chat_message_allowance < 1.0f)
1189 void Client::sendChatMessage(const std::wstring &message)
1191 const s16 max_queue_size = g_settings->getS16("max_out_chat_queue_size");
1192 if (canSendChatMessage()) {
1193 u32 now = time(NULL);
1194 float time_passed = now - m_last_chat_message_sent;
1195 m_last_chat_message_sent = now;
1197 m_chat_message_allowance += time_passed * (CLIENT_CHAT_MESSAGE_LIMIT_PER_10S / 8.0f);
1198 if (m_chat_message_allowance > CLIENT_CHAT_MESSAGE_LIMIT_PER_10S)
1199 m_chat_message_allowance = CLIENT_CHAT_MESSAGE_LIMIT_PER_10S;
1201 m_chat_message_allowance -= 1.0f;
1203 NetworkPacket pkt(TOSERVER_CHAT_MESSAGE, 2 + message.size() * sizeof(u16));
1208 } else if (m_out_chat_queue.size() < (u16) max_queue_size || max_queue_size == -1) {
1209 m_out_chat_queue.push(message);
1211 infostream << "Could not queue chat message because maximum out chat queue size ("
1212 << max_queue_size << ") is reached." << std::endl;
1216 void Client::clearOutChatQueue()
1218 m_out_chat_queue = std::queue<std::wstring>();
1221 void Client::sendChangePassword(const std::string &oldpassword,
1222 const std::string &newpassword)
1224 LocalPlayer *player = m_env.getLocalPlayer();
1228 // get into sudo mode and then send new password to server
1229 m_password = oldpassword;
1230 m_new_password = newpassword;
1231 startAuth(choseAuthMech(m_sudo_auth_methods));
1235 void Client::sendDamage(u16 damage)
1237 NetworkPacket pkt(TOSERVER_DAMAGE, sizeof(u16));
1242 void Client::sendRespawn()
1244 NetworkPacket pkt(TOSERVER_RESPAWN, 0);
1248 void Client::sendReady()
1250 NetworkPacket pkt(TOSERVER_CLIENT_READY,
1251 1 + 1 + 1 + 1 + 2 + sizeof(char) * strlen(g_version_hash) + 2);
1253 pkt << (u8) VERSION_MAJOR << (u8) VERSION_MINOR << (u8) VERSION_PATCH
1254 << (u8) 0 << (u16) strlen(g_version_hash);
1256 pkt.putRawString(g_version_hash, (u16) strlen(g_version_hash));
1257 pkt << (u16)FORMSPEC_API_VERSION;
1261 void Client::sendPlayerPos()
1263 LocalPlayer *player = m_env.getLocalPlayer();
1267 ClientMap &map = m_env.getClientMap();
1268 u8 camera_fov = map.getCameraFov();
1269 u8 wanted_range = map.getControl().wanted_range;
1271 // Save bandwidth by only updating position when
1272 // player is not dead and something changed
1274 if (m_activeobjects_received && player->isDead())
1278 player->last_position == player->getPosition() &&
1279 player->last_speed == player->getSpeed() &&
1280 player->last_pitch == player->getPitch() &&
1281 player->last_yaw == player->getYaw() &&
1282 player->last_keyPressed == player->keyPressed &&
1283 player->last_camera_fov == camera_fov &&
1284 player->last_wanted_range == wanted_range)
1287 player->last_position = player->getPosition();
1288 player->last_speed = player->getSpeed();
1289 player->last_pitch = player->getPitch();
1290 player->last_yaw = player->getYaw();
1291 player->last_keyPressed = player->keyPressed;
1292 player->last_camera_fov = camera_fov;
1293 player->last_wanted_range = wanted_range;
1295 NetworkPacket pkt(TOSERVER_PLAYERPOS, 12 + 12 + 4 + 4 + 4 + 1 + 1);
1297 writePlayerPos(player, &map, &pkt);
1302 void Client::removeNode(v3s16 p)
1304 std::map<v3s16, MapBlock*> modified_blocks;
1307 m_env.getMap().removeNodeAndUpdate(p, modified_blocks);
1309 catch(InvalidPositionException &e) {
1312 for (const auto &modified_block : modified_blocks) {
1313 addUpdateMeshTaskWithEdge(modified_block.first, false, true);
1318 * Helper function for Client Side Modding
1319 * CSM restrictions are applied there, this should not be used for core engine
1321 * @param is_valid_position
1324 MapNode Client::CSMGetNode(v3s16 p, bool *is_valid_position)
1326 if (checkCSMRestrictionFlag(CSMRestrictionFlags::CSM_RF_LOOKUP_NODES)) {
1327 v3s16 ppos = floatToInt(m_env.getLocalPlayer()->getPosition(), BS);
1328 if ((u32) ppos.getDistanceFrom(p) > m_csm_restriction_noderange) {
1329 *is_valid_position = false;
1333 return m_env.getMap().getNode(p, is_valid_position);
1336 int Client::CSMClampRadius(v3s16 pos, int radius)
1338 if (!checkCSMRestrictionFlag(CSMRestrictionFlags::CSM_RF_LOOKUP_NODES))
1340 // This is approximate and will cause some allowed nodes to be excluded
1341 v3s16 ppos = floatToInt(m_env.getLocalPlayer()->getPosition(), BS);
1342 u32 distance = ppos.getDistanceFrom(pos);
1343 if (distance >= m_csm_restriction_noderange)
1345 return std::min<int>(radius, m_csm_restriction_noderange - distance);
1348 v3s16 Client::CSMClampPos(v3s16 pos)
1350 if (!checkCSMRestrictionFlag(CSMRestrictionFlags::CSM_RF_LOOKUP_NODES))
1352 v3s16 ppos = floatToInt(m_env.getLocalPlayer()->getPosition(), BS);
1353 const int range = m_csm_restriction_noderange;
1355 core::clamp<int>(pos.X, (int)ppos.X - range, (int)ppos.X + range),
1356 core::clamp<int>(pos.Y, (int)ppos.Y - range, (int)ppos.Y + range),
1357 core::clamp<int>(pos.Z, (int)ppos.Z - range, (int)ppos.Z + range)
1361 void Client::addNode(v3s16 p, MapNode n, bool remove_metadata)
1363 //TimeTaker timer1("Client::addNode()");
1365 std::map<v3s16, MapBlock*> modified_blocks;
1368 //TimeTaker timer3("Client::addNode(): addNodeAndUpdate");
1369 m_env.getMap().addNodeAndUpdate(p, n, modified_blocks, remove_metadata);
1371 catch(InvalidPositionException &e) {
1374 for (const auto &modified_block : modified_blocks) {
1375 addUpdateMeshTaskWithEdge(modified_block.first, false, true);
1379 void Client::setPlayerControl(PlayerControl &control)
1381 LocalPlayer *player = m_env.getLocalPlayer();
1383 player->control = control;
1386 void Client::setPlayerItem(u16 item)
1388 m_env.getLocalPlayer()->setWieldIndex(item);
1389 m_update_wielded_item = true;
1391 NetworkPacket pkt(TOSERVER_PLAYERITEM, 2);
1396 // Returns true once after the inventory of the local player
1397 // has been updated from the server.
1398 bool Client::updateWieldedItem()
1400 if (!m_update_wielded_item)
1403 m_update_wielded_item = false;
1405 LocalPlayer *player = m_env.getLocalPlayer();
1407 if (auto *list = player->inventory.getList("main"))
1408 list->setModified(false);
1409 if (auto *list = player->inventory.getList("hand"))
1410 list->setModified(false);
1415 scene::ISceneManager* Client::getSceneManager()
1417 return m_rendering_engine->get_scene_manager();
1420 Inventory* Client::getInventory(const InventoryLocation &loc)
1423 case InventoryLocation::UNDEFINED:
1426 case InventoryLocation::CURRENT_PLAYER:
1428 LocalPlayer *player = m_env.getLocalPlayer();
1430 return &player->inventory;
1433 case InventoryLocation::PLAYER:
1435 // Check if we are working with local player inventory
1436 LocalPlayer *player = m_env.getLocalPlayer();
1437 if (!player || strcmp(player->getName(), loc.name.c_str()) != 0)
1439 return &player->inventory;
1442 case InventoryLocation::NODEMETA:
1444 NodeMetadata *meta = m_env.getMap().getNodeMetadata(loc.p);
1447 return meta->getInventory();
1450 case InventoryLocation::DETACHED:
1452 if (m_detached_inventories.count(loc.name) == 0)
1454 return m_detached_inventories[loc.name];
1458 FATAL_ERROR("Invalid inventory location type.");
1464 void Client::inventoryAction(InventoryAction *a)
1467 Send it to the server
1469 sendInventoryAction(a);
1472 Predict some local inventory changes
1474 a->clientApply(this, this);
1480 float Client::getAnimationTime()
1482 return m_animation_time;
1485 int Client::getCrackLevel()
1487 return m_crack_level;
1490 v3s16 Client::getCrackPos()
1495 void Client::setCrack(int level, v3s16 pos)
1497 int old_crack_level = m_crack_level;
1498 v3s16 old_crack_pos = m_crack_pos;
1500 m_crack_level = level;
1503 if(old_crack_level >= 0 && (level < 0 || pos != old_crack_pos))
1506 addUpdateMeshTaskForNode(old_crack_pos, false, true);
1508 if(level >= 0 && (old_crack_level < 0 || pos != old_crack_pos))
1511 addUpdateMeshTaskForNode(pos, false, true);
1517 LocalPlayer *player = m_env.getLocalPlayer();
1522 bool Client::getChatMessage(std::wstring &res)
1524 if (m_chat_queue.empty())
1527 ChatMessage *chatMessage = m_chat_queue.front();
1532 switch (chatMessage->type) {
1533 case CHATMESSAGE_TYPE_RAW:
1534 case CHATMESSAGE_TYPE_ANNOUNCE:
1535 case CHATMESSAGE_TYPE_SYSTEM:
1536 res = chatMessage->message;
1538 case CHATMESSAGE_TYPE_NORMAL: {
1539 if (!chatMessage->sender.empty())
1540 res = L"<" + chatMessage->sender + L"> " + chatMessage->message;
1542 res = chatMessage->message;
1553 void Client::typeChatMessage(const std::wstring &message)
1555 // Discard empty line
1556 if (message.empty())
1559 // If message was consumed by script API, don't send it to server
1560 if (m_mods_loaded && m_script->on_sending_message(wide_to_utf8(message)))
1564 sendChatMessage(message);
1567 void Client::addUpdateMeshTask(v3s16 p, bool ack_to_server, bool urgent)
1569 // Check if the block exists to begin with. In the case when a non-existing
1570 // neighbor is automatically added, it may not. In that case we don't want
1571 // to tell the mesh update thread about it.
1572 MapBlock *b = m_env.getMap().getBlockNoCreateNoEx(p);
1576 m_mesh_update_thread.updateBlock(&m_env.getMap(), p, ack_to_server, urgent);
1579 void Client::addUpdateMeshTaskWithEdge(v3s16 blockpos, bool ack_to_server, bool urgent)
1582 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1584 catch(InvalidPositionException &e){}
1587 for (int i=0;i<6;i++)
1590 v3s16 p = blockpos + g_6dirs[i];
1591 addUpdateMeshTask(p, false, urgent);
1593 catch(InvalidPositionException &e){}
1597 void Client::addUpdateMeshTaskForNode(v3s16 nodepos, bool ack_to_server, bool urgent)
1601 infostream<<"Client::addUpdateMeshTaskForNode(): "
1602 <<"("<<p.X<<","<<p.Y<<","<<p.Z<<")"
1606 v3s16 blockpos = getNodeBlockPos(nodepos);
1607 v3s16 blockpos_relative = blockpos * MAP_BLOCKSIZE;
1610 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1612 catch(InvalidPositionException &e) {}
1615 if(nodepos.X == blockpos_relative.X){
1617 v3s16 p = blockpos + v3s16(-1,0,0);
1618 addUpdateMeshTask(p, false, urgent);
1620 catch(InvalidPositionException &e){}
1623 if(nodepos.Y == blockpos_relative.Y){
1625 v3s16 p = blockpos + v3s16(0,-1,0);
1626 addUpdateMeshTask(p, false, urgent);
1628 catch(InvalidPositionException &e){}
1631 if(nodepos.Z == blockpos_relative.Z){
1633 v3s16 p = blockpos + v3s16(0,0,-1);
1634 addUpdateMeshTask(p, false, urgent);
1636 catch(InvalidPositionException &e){}
1640 ClientEvent *Client::getClientEvent()
1642 FATAL_ERROR_IF(m_client_event_queue.empty(),
1643 "Cannot getClientEvent, queue is empty.");
1645 ClientEvent *event = m_client_event_queue.front();
1646 m_client_event_queue.pop();
1650 const Address Client::getServerAddress()
1652 return m_con->GetPeerAddress(PEER_ID_SERVER);
1655 float Client::mediaReceiveProgress()
1657 if (m_media_downloader)
1658 return m_media_downloader->getProgress();
1660 return 1.0; // downloader only exists when not yet done
1663 typedef struct TextureUpdateArgs {
1664 gui::IGUIEnvironment *guienv;
1667 const wchar_t* text_base;
1668 ITextureSource *tsrc;
1669 } TextureUpdateArgs;
1671 void Client::showUpdateProgressTexture(void *args, u32 progress, u32 max_progress)
1673 TextureUpdateArgs* targs = (TextureUpdateArgs*) args;
1674 u16 cur_percent = ceil(progress / (double) max_progress * 100.);
1676 // update the loading menu -- if neccessary
1677 bool do_draw = false;
1678 u64 time_ms = targs->last_time_ms;
1679 if (cur_percent != targs->last_percent) {
1680 targs->last_percent = cur_percent;
1681 time_ms = porting::getTimeMs();
1682 // only draw when the user will notice something:
1683 do_draw = (time_ms - targs->last_time_ms > 100);
1687 targs->last_time_ms = time_ms;
1688 std::basic_stringstream<wchar_t> strm;
1689 strm << targs->text_base << " " << targs->last_percent << "%...";
1690 m_rendering_engine->draw_load_screen(strm.str(), targs->guienv, targs->tsrc, 0,
1691 72 + (u16) ((18. / 100.) * (double) targs->last_percent), true);
1695 void Client::afterContentReceived()
1697 infostream<<"Client::afterContentReceived() started"<<std::endl;
1698 assert(m_itemdef_received); // pre-condition
1699 assert(m_nodedef_received); // pre-condition
1700 assert(mediaReceived()); // pre-condition
1702 const wchar_t* text = wgettext("Loading textures...");
1704 // Clear cached pre-scaled 2D GUI images, as this cache
1705 // might have images with the same name but different
1706 // content from previous sessions.
1707 guiScalingCacheClear();
1709 // Rebuild inherited images and recreate textures
1710 infostream<<"- Rebuilding images and textures"<<std::endl;
1711 m_rendering_engine->draw_load_screen(text, guienv, m_tsrc, 0, 70);
1712 m_tsrc->rebuildImagesAndTextures();
1716 infostream<<"- Rebuilding shaders"<<std::endl;
1717 text = wgettext("Rebuilding shaders...");
1718 m_rendering_engine->draw_load_screen(text, guienv, m_tsrc, 0, 71);
1719 m_shsrc->rebuildShaders();
1722 // Update node aliases
1723 infostream<<"- Updating node aliases"<<std::endl;
1724 text = wgettext("Initializing nodes...");
1725 m_rendering_engine->draw_load_screen(text, guienv, m_tsrc, 0, 72);
1726 m_nodedef->updateAliases(m_itemdef);
1727 for (const auto &path : getTextureDirs()) {
1728 TextureOverrideSource override_source(path + DIR_DELIM + "override.txt");
1729 m_nodedef->applyTextureOverrides(override_source.getNodeTileOverrides());
1730 m_itemdef->applyTextureOverrides(override_source.getItemTextureOverrides());
1732 m_nodedef->setNodeRegistrationStatus(true);
1733 m_nodedef->runNodeResolveCallbacks();
1736 // Update node textures and assign shaders to each tile
1737 infostream<<"- Updating node textures"<<std::endl;
1738 TextureUpdateArgs tu_args;
1739 tu_args.guienv = guienv;
1740 tu_args.last_time_ms = porting::getTimeMs();
1741 tu_args.last_percent = 0;
1742 tu_args.text_base = wgettext("Initializing nodes");
1743 tu_args.tsrc = m_tsrc;
1744 m_nodedef->updateTextures(this, &tu_args);
1745 delete[] tu_args.text_base;
1747 // Start mesh update thread after setting up content definitions
1748 infostream<<"- Starting mesh update thread"<<std::endl;
1749 m_mesh_update_thread.start();
1755 m_script->on_client_ready(m_env.getLocalPlayer());
1757 text = wgettext("Done!");
1758 m_rendering_engine->draw_load_screen(text, guienv, m_tsrc, 0, 100);
1759 infostream<<"Client::afterContentReceived() done"<<std::endl;
1763 float Client::getRTT()
1765 return m_con->getPeerStat(PEER_ID_SERVER,con::AVG_RTT);
1768 float Client::getCurRate()
1770 return (m_con->getLocalStat(con::CUR_INC_RATE) +
1771 m_con->getLocalStat(con::CUR_DL_RATE));
1774 void Client::makeScreenshot()
1776 irr::video::IVideoDriver *driver = m_rendering_engine->get_video_driver();
1777 irr::video::IImage* const raw_image = driver->createScreenShot();
1782 time_t t = time(NULL);
1783 struct tm *tm = localtime(&t);
1785 char timetstamp_c[64];
1786 strftime(timetstamp_c, sizeof(timetstamp_c), "%Y%m%d_%H%M%S", tm);
1788 std::string screenshot_dir;
1790 if (fs::IsPathAbsolute(g_settings->get("screenshot_path")))
1791 screenshot_dir = g_settings->get("screenshot_path");
1793 screenshot_dir = porting::path_user + DIR_DELIM + g_settings->get("screenshot_path");
1795 std::string filename_base = screenshot_dir
1797 + std::string("screenshot_")
1798 + std::string(timetstamp_c);
1799 std::string filename_ext = "." + g_settings->get("screenshot_format");
1800 std::string filename;
1802 // Create the directory if it doesn't already exist.
1803 // Otherwise, saving the screenshot would fail.
1804 fs::CreateDir(screenshot_dir);
1806 u32 quality = (u32)g_settings->getS32("screenshot_quality");
1807 quality = MYMIN(MYMAX(quality, 0), 100) / 100.0 * 255;
1809 // Try to find a unique filename
1810 unsigned serial = 0;
1812 while (serial < SCREENSHOT_MAX_SERIAL_TRIES) {
1813 filename = filename_base + (serial > 0 ? ("_" + itos(serial)) : "") + filename_ext;
1814 std::ifstream tmp(filename.c_str());
1816 break; // File did not apparently exist, we'll go with it
1820 if (serial == SCREENSHOT_MAX_SERIAL_TRIES) {
1821 infostream << "Could not find suitable filename for screenshot" << std::endl;
1823 irr::video::IImage* const image =
1824 driver->createImage(video::ECF_R8G8B8, raw_image->getDimension());
1827 raw_image->copyTo(image);
1829 std::ostringstream sstr;
1830 if (driver->writeImageToFile(image, filename.c_str(), quality)) {
1831 sstr << "Saved screenshot to '" << filename << "'";
1833 sstr << "Failed to save screenshot '" << filename << "'";
1835 pushToChatQueue(new ChatMessage(CHATMESSAGE_TYPE_SYSTEM,
1836 utf8_to_wide(sstr.str())));
1837 infostream << sstr.str() << std::endl;
1845 bool Client::shouldShowMinimap() const
1847 return !m_minimap_disabled_by_server;
1850 void Client::pushToEventQueue(ClientEvent *event)
1852 m_client_event_queue.push(event);
1855 void Client::showMinimap(const bool show)
1857 m_game_ui->showMinimap(show);
1860 // IGameDef interface
1862 IItemDefManager* Client::getItemDefManager()
1866 const NodeDefManager* Client::getNodeDefManager()
1870 ICraftDefManager* Client::getCraftDefManager()
1873 //return m_craftdef;
1875 ITextureSource* Client::getTextureSource()
1879 IWritableShaderSource* Client::getShaderSource()
1884 u16 Client::allocateUnknownNodeId(const std::string &name)
1886 errorstream << "Client::allocateUnknownNodeId(): "
1887 << "Client cannot allocate node IDs" << std::endl;
1888 FATAL_ERROR("Client allocated unknown node");
1890 return CONTENT_IGNORE;
1892 ISoundManager* Client::getSoundManager()
1896 MtEventManager* Client::getEventManager()
1901 ParticleManager* Client::getParticleManager()
1903 return &m_particle_manager;
1906 scene::IAnimatedMesh* Client::getMesh(const std::string &filename, bool cache)
1908 StringMap::const_iterator it = m_mesh_data.find(filename);
1909 if (it == m_mesh_data.end()) {
1910 errorstream << "Client::getMesh(): Mesh not found: \"" << filename
1911 << "\"" << std::endl;
1914 const std::string &data = it->second;
1916 // Create the mesh, remove it from cache and return it
1917 // This allows unique vertex colors and other properties for each instance
1918 io::IReadFile *rfile = m_rendering_engine->get_filesystem()->createMemoryReadFile(
1919 data.c_str(), data.size(), filename.c_str());
1920 FATAL_ERROR_IF(!rfile, "Could not create/open RAM file");
1922 scene::IAnimatedMesh *mesh = m_rendering_engine->get_scene_manager()->getMesh(rfile);
1928 m_rendering_engine->removeMesh(mesh);
1932 const std::string* Client::getModFile(std::string filename)
1934 // strip dir delimiter from beginning of path
1935 auto pos = filename.find_first_of(':');
1936 if (pos == std::string::npos)
1939 auto pos2 = filename.find_first_not_of('/', pos);
1941 filename.erase(pos, pos2 - pos);
1943 StringMap::const_iterator it = m_mod_vfs.find(filename);
1944 if (it == m_mod_vfs.end())
1949 bool Client::registerModStorage(ModMetadata *storage)
1951 if (m_mod_storages.find(storage->getModName()) != m_mod_storages.end()) {
1952 errorstream << "Unable to register same mod storage twice. Storage name: "
1953 << storage->getModName() << std::endl;
1957 m_mod_storages[storage->getModName()] = storage;
1961 void Client::unregisterModStorage(const std::string &name)
1963 std::unordered_map<std::string, ModMetadata *>::const_iterator it =
1964 m_mod_storages.find(name);
1965 if (it != m_mod_storages.end()) {
1966 // Save unconditionaly on unregistration
1967 it->second->save(getModStoragePath());
1968 m_mod_storages.erase(name);
1972 std::string Client::getModStoragePath() const
1974 return porting::path_user + DIR_DELIM + "client" + DIR_DELIM + "mod_storage";
1981 bool Client::joinModChannel(const std::string &channel)
1983 if (m_modchannel_mgr->channelRegistered(channel))
1986 NetworkPacket pkt(TOSERVER_MODCHANNEL_JOIN, 2 + channel.size());
1990 m_modchannel_mgr->joinChannel(channel, 0);
1994 bool Client::leaveModChannel(const std::string &channel)
1996 if (!m_modchannel_mgr->channelRegistered(channel))
1999 NetworkPacket pkt(TOSERVER_MODCHANNEL_LEAVE, 2 + channel.size());
2003 m_modchannel_mgr->leaveChannel(channel, 0);
2007 bool Client::sendModChannelMessage(const std::string &channel, const std::string &message)
2009 if (!m_modchannel_mgr->canWriteOnChannel(channel))
2012 if (message.size() > STRING_MAX_LEN) {
2013 warningstream << "ModChannel message too long, dropping before sending "
2014 << " (" << message.size() << " > " << STRING_MAX_LEN << ", channel: "
2015 << channel << ")" << std::endl;
2019 // @TODO: do some client rate limiting
2020 NetworkPacket pkt(TOSERVER_MODCHANNEL_MSG, 2 + channel.size() + 2 + message.size());
2021 pkt << channel << message;
2026 ModChannel* Client::getModChannel(const std::string &channel)
2028 return m_modchannel_mgr->getModChannel(channel);