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>
25 #include "threading/mutex_auto_lock.h"
26 #include "util/auth.h"
27 #include "util/directiontables.h"
28 #include "util/pointedthing.h"
29 #include "util/serialize.h"
30 #include "util/string.h"
33 #include "network/clientopcodes.h"
35 #include "mapblock_mesh.h"
41 #include "clientmap.h"
42 #include "clientmedia.h"
44 #include "drawscene.h"
45 #include "database-sqlite3.h"
46 #include "serialization.h"
47 #include "guiscalingfilter.h"
48 #include "script/scripting_client.h"
51 extern gui::IGUIEnvironment* guienv;
58 IrrlichtDevice *device,
59 const char *playername,
60 const std::string &password,
61 const std::string &address_name,
62 MapDrawControl &control,
63 IWritableTextureSource *tsrc,
64 IWritableShaderSource *shsrc,
65 IWritableItemDefManager *itemdef,
66 IWritableNodeDefManager *nodedef,
68 MtEventManager *event,
70 GameUIFlags *game_ui_flags
78 m_mesh_update_thread(this),
80 new ClientMap(this, control,
81 device->getSceneManager()->getRootSceneNode(),
82 device->getSceneManager(), 666),
83 device->getSceneManager(),
86 m_particle_manager(&m_env),
87 m_con(PROTOCOL_ID, 512, CONNECTION_TIMEOUT, ipv6, this),
88 m_address_name(address_name),
90 m_server_ser_ver(SER_FMT_VER_INVALID),
91 m_last_chat_message_sent(time(NULL)),
93 m_chosen_auth_mech(AUTH_MECHANISM_NONE),
94 m_media_downloader(new ClientMediaDownloader()),
96 m_game_ui_flags(game_ui_flags)
99 m_env.setLocalPlayer(new LocalPlayer(this, playername));
101 if (g_settings->getBool("enable_minimap")) {
102 m_minimap = new Minimap(device, this);
104 m_cache_save_interval = g_settings->getU16("server_map_save_interval");
106 m_modding_enabled = g_settings->getBool("enable_client_modding");
107 m_script = new ClientScripting(this);
108 m_env.setScript(m_script);
109 m_script->setEnv(&m_env);
112 void Client::initMods()
114 m_script->loadMod(getBuiltinLuaPath() + DIR_DELIM "init.lua", BUILTIN_MOD_NAME);
116 // If modding is not enabled, don't load mods, just builtin
117 if (!m_modding_enabled) {
121 ClientModConfiguration modconf(getClientModsLuaPath());
122 std::vector<ModSpec> mods = modconf.getMods();
123 std::vector<ModSpec> unsatisfied_mods = modconf.getUnsatisfiedMods();
124 // complain about mods with unsatisfied dependencies
125 if (!modconf.isConsistent()) {
126 modconf.printUnsatisfiedModsError();
130 infostream << "Client Loading mods: ";
131 for (std::vector<ModSpec>::const_iterator i = mods.begin();
132 i != mods.end(); ++i) {
133 infostream << (*i).name << " ";
136 infostream << std::endl;
137 // Load and run "mod" scripts
138 for (std::vector<ModSpec>::const_iterator it = mods.begin();
139 it != mods.end(); ++it) {
140 const ModSpec &mod = *it;
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 std::string script_path = mod.path + DIR_DELIM + "init.lua";
147 infostream << " [" << padStringRight(mod.name, 12) << "] [\""
148 << script_path << "\"]" << std::endl;
149 m_script->loadMod(script_path, mod.name);
153 const std::string &Client::getBuiltinLuaPath()
155 static const std::string builtin_dir = porting::path_share + DIR_DELIM + "builtin";
159 const std::string &Client::getClientModsLuaPath()
161 static const std::string clientmods_dir = porting::path_share + DIR_DELIM + "clientmods";
162 return clientmods_dir;
165 const std::vector<ModSpec>& Client::getMods() const
167 static std::vector<ModSpec> client_modspec_temp;
168 return client_modspec_temp;
171 const ModSpec* Client::getModSpec(const std::string &modname) const
179 // Don't disable this part when modding is disabled, it's used in builtin
180 m_script->on_shutdown();
181 //request all client managed threads to stop
182 m_mesh_update_thread.stop();
183 // Save local server map
185 infostream << "Local map saving ended." << std::endl;
186 m_localdb->endSave();
192 bool Client::isShutdown()
194 return m_shutdown || !m_mesh_update_thread.isRunning();
202 m_mesh_update_thread.stop();
203 m_mesh_update_thread.wait();
204 while (!m_mesh_update_thread.m_queue_out.empty()) {
205 MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_frontNoEx();
210 delete m_inventory_from_server;
212 // Delete detached inventories
213 for (std::unordered_map<std::string, Inventory*>::iterator
214 i = m_detached_inventories.begin();
215 i != m_detached_inventories.end(); ++i) {
219 // cleanup 3d model meshes on client shutdown
220 while (m_device->getSceneManager()->getMeshCache()->getMeshCount() != 0) {
221 scene::IAnimatedMesh *mesh =
222 m_device->getSceneManager()->getMeshCache()->getMeshByIndex(0);
225 m_device->getSceneManager()->getMeshCache()->removeMesh(mesh);
231 void Client::connect(Address address, bool is_local_server)
233 DSTACK(FUNCTION_NAME);
235 initLocalMapSaving(address, m_address_name, is_local_server);
237 m_con.SetTimeoutMs(0);
238 m_con.Connect(address);
241 void Client::step(float dtime)
243 DSTACK(FUNCTION_NAME);
249 if(m_ignore_damage_timer > dtime)
250 m_ignore_damage_timer -= dtime;
252 m_ignore_damage_timer = 0.0;
254 m_animation_time += dtime;
255 if(m_animation_time > 60.0)
256 m_animation_time -= 60.0;
258 m_time_of_day_update_timer += dtime;
266 float &counter = m_packetcounter_timer;
272 infostream << "Client packetcounter (" << m_packetcounter_timer
274 m_packetcounter.print(infostream);
275 m_packetcounter.clear();
279 // UGLY hack to fix 2 second startup delay caused by non existent
280 // server client startup synchronization in local server or singleplayer mode
281 static bool initial_step = true;
283 initial_step = false;
285 else if(m_state == LC_Created) {
286 float &counter = m_connection_reinit_timer;
291 LocalPlayer *myplayer = m_env.getLocalPlayer();
292 FATAL_ERROR_IF(myplayer == NULL, "Local player not found in environment.");
294 u16 proto_version_min = g_settings->getFlag("send_pre_v25_init") ?
295 CLIENT_PROTOCOL_VERSION_MIN_LEGACY : CLIENT_PROTOCOL_VERSION_MIN;
297 if (proto_version_min < 25) {
298 // Send TOSERVER_INIT_LEGACY
299 // [0] u16 TOSERVER_INIT_LEGACY
300 // [2] u8 SER_FMT_VER_HIGHEST_READ
301 // [3] u8[20] player_name
302 // [23] u8[28] password (new in some version)
303 // [51] u16 minimum supported network protocol version (added sometime)
304 // [53] u16 maximum supported network protocol version (added later than the previous one)
306 char pName[PLAYERNAME_SIZE];
307 char pPassword[PASSWORD_SIZE];
308 memset(pName, 0, PLAYERNAME_SIZE * sizeof(char));
309 memset(pPassword, 0, PASSWORD_SIZE * sizeof(char));
311 std::string hashed_password = translate_password(myplayer->getName(), m_password);
312 snprintf(pName, PLAYERNAME_SIZE, "%s", myplayer->getName());
313 snprintf(pPassword, PASSWORD_SIZE, "%s", hashed_password.c_str());
315 sendLegacyInit(pName, pPassword);
317 if (CLIENT_PROTOCOL_VERSION_MAX >= 25)
318 sendInit(myplayer->getName());
321 // Not connected, return
326 Do stuff if connected
330 Run Map's timers and unload unused data
332 const float map_timer_and_unload_dtime = 5.25;
333 if(m_map_timer_and_unload_interval.step(dtime, map_timer_and_unload_dtime)) {
334 ScopeProfiler sp(g_profiler, "Client: map timer and unload");
335 std::vector<v3s16> deleted_blocks;
336 m_env.getMap().timerUpdate(map_timer_and_unload_dtime,
337 g_settings->getFloat("client_unload_unused_data_timeout"),
338 g_settings->getS32("client_mapblock_limit"),
343 NOTE: This loop is intentionally iterated the way it is.
346 std::vector<v3s16>::iterator i = deleted_blocks.begin();
347 std::vector<v3s16> sendlist;
349 if(sendlist.size() == 255 || i == deleted_blocks.end()) {
360 sendDeletedBlocks(sendlist);
362 if(i == deleted_blocks.end())
368 sendlist.push_back(*i);
374 Send pending messages on out chat queue
376 if (!m_out_chat_queue.empty() && canSendChatMessage()) {
377 sendChatMessage(m_out_chat_queue.front());
378 m_out_chat_queue.pop();
384 // Control local player (0ms)
385 LocalPlayer *player = m_env.getLocalPlayer();
387 player->applyControl(dtime);
391 m_sound->step(dtime);
396 while (m_env.hasClientEnvEvents()) {
397 ClientEnvEvent envEvent = m_env.getClientEnvEvent();
399 if (envEvent.type == CEE_PLAYER_DAMAGE) {
400 if (m_ignore_damage_timer <= 0) {
401 u8 damage = envEvent.player_damage.amount;
403 if (envEvent.player_damage.send_to_server)
406 // Add to ClientEvent queue
408 event.type = CE_PLAYER_DAMAGE;
409 event.player_damage.amount = damage;
410 m_client_event_queue.push(event);
413 // Protocol v29 or greater obsoleted this event
414 else if (envEvent.type == CEE_PLAYER_BREATH && m_proto_ver < 29) {
415 u16 breath = envEvent.player_breath.amount;
423 float &counter = m_avg_rtt_timer;
427 // connectedAndInitialized() is true, peer exists.
428 float avg_rtt = getRTT();
429 infostream << "Client: avg_rtt=" << avg_rtt << std::endl;
433 Send player position to server
436 float &counter = m_playerpos_send_timer;
438 if((m_state == LC_Ready) && (counter >= m_recommended_send_interval))
446 Replace updated meshes
449 int num_processed_meshes = 0;
450 while (!m_mesh_update_thread.m_queue_out.empty())
452 num_processed_meshes++;
454 MinimapMapblock *minimap_mapblock = NULL;
455 bool do_mapper_update = true;
457 MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_frontNoEx();
458 MapBlock *block = m_env.getMap().getBlockNoCreateNoEx(r.p);
460 // Delete the old mesh
462 block->mesh = nullptr;
465 minimap_mapblock = r.mesh->moveMinimapMapblock();
466 if (minimap_mapblock == NULL)
467 do_mapper_update = false;
469 bool is_empty = true;
470 for (int l = 0; l < MAX_TILE_LAYERS; l++)
471 if (r.mesh->getMesh(l)->getMeshBufferCount() != 0)
477 // Replace with the new mesh
478 block->mesh = r.mesh;
484 if (m_minimap && do_mapper_update)
485 m_minimap->addBlock(r.p, minimap_mapblock);
487 if (r.ack_block_to_server) {
497 if (num_processed_meshes > 0)
498 g_profiler->graphAdd("num_processed_meshes", num_processed_meshes);
504 if (m_media_downloader && m_media_downloader->isStarted()) {
505 m_media_downloader->step(this);
506 if (m_media_downloader->isDone()) {
507 delete m_media_downloader;
508 m_media_downloader = NULL;
513 If the server didn't update the inventory in a while, revert
514 the local inventory (so the player notices the lag problem
515 and knows something is wrong).
517 if(m_inventory_from_server)
519 float interval = 10.0;
520 float count_before = floor(m_inventory_from_server_age / interval);
522 m_inventory_from_server_age += dtime;
524 float count_after = floor(m_inventory_from_server_age / interval);
526 if(count_after != count_before)
528 // Do this every <interval> seconds after TOCLIENT_INVENTORY
529 // Reset the locally changed inventory to the authoritative inventory
530 LocalPlayer *player = m_env.getLocalPlayer();
531 player->inventory = *m_inventory_from_server;
532 m_inventory_updated = true;
537 Update positions of sounds attached to objects
540 for(std::unordered_map<int, u16>::iterator i = m_sounds_to_objects.begin();
541 i != m_sounds_to_objects.end(); ++i) {
542 int client_id = i->first;
543 u16 object_id = i->second;
544 ClientActiveObject *cao = m_env.getActiveObject(object_id);
547 v3f pos = cao->getPosition();
548 m_sound->updateSoundPosition(client_id, pos);
553 Handle removed remotely initiated sounds
555 m_removed_sounds_check_timer += dtime;
556 if(m_removed_sounds_check_timer >= 2.32) {
557 m_removed_sounds_check_timer = 0;
558 // Find removed sounds and clear references to them
559 std::vector<s32> removed_server_ids;
560 for (std::unordered_map<s32, int>::iterator i = m_sounds_server_to_client.begin();
561 i != m_sounds_server_to_client.end();) {
562 s32 server_id = i->first;
563 int client_id = i->second;
565 if(!m_sound->soundExists(client_id)) {
566 m_sounds_server_to_client.erase(server_id);
567 m_sounds_client_to_server.erase(client_id);
568 m_sounds_to_objects.erase(client_id);
569 removed_server_ids.push_back(server_id);
574 if(!removed_server_ids.empty()) {
575 sendRemovedSounds(removed_server_ids);
579 m_mod_storage_save_timer -= dtime;
580 if (m_mod_storage_save_timer <= 0.0f) {
581 verbosestream << "Saving registered mod storages." << std::endl;
582 m_mod_storage_save_timer = g_settings->getFloat("server_map_save_interval");
583 for (std::unordered_map<std::string, ModMetadata *>::const_iterator
584 it = m_mod_storages.begin(); it != m_mod_storages.end(); ++it) {
585 if (it->second->isModified()) {
586 it->second->save(getModStoragePath());
592 if (m_localdb && m_localdb_save_interval.step(dtime,
593 m_cache_save_interval)) {
594 m_localdb->endSave();
595 m_localdb->beginSave();
599 bool Client::loadMedia(const std::string &data, const std::string &filename)
601 // Silly irrlicht's const-incorrectness
602 Buffer<char> data_rw(data.c_str(), data.size());
606 const char *image_ext[] = {
607 ".png", ".jpg", ".bmp", ".tga",
608 ".pcx", ".ppm", ".psd", ".wal", ".rgb",
611 name = removeStringEnd(filename, image_ext);
614 verbosestream<<"Client: Attempting to load image "
615 <<"file \""<<filename<<"\""<<std::endl;
617 io::IFileSystem *irrfs = m_device->getFileSystem();
618 video::IVideoDriver *vdrv = m_device->getVideoDriver();
620 // Create an irrlicht memory file
621 io::IReadFile *rfile = irrfs->createMemoryReadFile(
622 *data_rw, data_rw.getSize(), "_tempreadfile");
624 FATAL_ERROR_IF(!rfile, "Could not create irrlicht memory file.");
627 video::IImage *img = vdrv->createImageFromFile(rfile);
629 errorstream<<"Client: Cannot create image from data of "
630 <<"file \""<<filename<<"\""<<std::endl;
635 m_tsrc->insertSourceImage(filename, img);
642 const char *sound_ext[] = {
643 ".0.ogg", ".1.ogg", ".2.ogg", ".3.ogg", ".4.ogg",
644 ".5.ogg", ".6.ogg", ".7.ogg", ".8.ogg", ".9.ogg",
647 name = removeStringEnd(filename, sound_ext);
650 verbosestream<<"Client: Attempting to load sound "
651 <<"file \""<<filename<<"\""<<std::endl;
652 m_sound->loadSoundData(name, data);
656 const char *model_ext[] = {
657 ".x", ".b3d", ".md2", ".obj",
660 name = removeStringEnd(filename, model_ext);
663 verbosestream<<"Client: Storing model into memory: "
664 <<"\""<<filename<<"\""<<std::endl;
665 if(m_mesh_data.count(filename))
666 errorstream<<"Multiple models with name \""<<filename.c_str()
667 <<"\" found; replacing previous model"<<std::endl;
668 m_mesh_data[filename] = data;
672 errorstream<<"Client: Don't know how to load file \""
673 <<filename<<"\""<<std::endl;
677 // Virtual methods from con::PeerHandler
678 void Client::peerAdded(con::Peer *peer)
680 infostream << "Client::peerAdded(): peer->id="
681 << peer->id << std::endl;
683 void Client::deletingPeer(con::Peer *peer, bool timeout)
685 infostream << "Client::deletingPeer(): "
686 "Server Peer is getting deleted "
687 << "(timeout=" << timeout << ")" << std::endl;
690 m_access_denied = true;
691 m_access_denied_reason = gettext("Connection timed out.");
697 u16 number of files requested
703 void Client::request_media(const std::vector<std::string> &file_requests)
705 std::ostringstream os(std::ios_base::binary);
706 writeU16(os, TOSERVER_REQUEST_MEDIA);
707 size_t file_requests_size = file_requests.size();
709 FATAL_ERROR_IF(file_requests_size > 0xFFFF, "Unsupported number of file requests");
711 // Packet dynamicly resized
712 NetworkPacket pkt(TOSERVER_REQUEST_MEDIA, 2 + 0);
714 pkt << (u16) (file_requests_size & 0xFFFF);
716 for(std::vector<std::string>::const_iterator i = file_requests.begin();
717 i != file_requests.end(); ++i) {
723 infostream << "Client: Sending media request list to server ("
724 << file_requests.size() << " files. packet size)" << std::endl;
727 void Client::initLocalMapSaving(const Address &address,
728 const std::string &hostname,
729 bool is_local_server)
731 if (!g_settings->getBool("enable_local_map_saving") || is_local_server) {
735 const std::string world_path = porting::path_user
736 + DIR_DELIM + "worlds"
737 + DIR_DELIM + "server_"
738 + hostname + "_" + std::to_string(address.getPort());
740 fs::CreateAllDirs(world_path);
742 m_localdb = new MapDatabaseSQLite3(world_path);
743 m_localdb->beginSave();
744 actionstream << "Local map saving started, map will be saved at '" << world_path << "'" << std::endl;
747 void Client::ReceiveAll()
749 DSTACK(FUNCTION_NAME);
750 u64 start_ms = porting::getTimeMs();
753 // Limit time even if there would be huge amounts of data to
755 if(porting::getTimeMs() > start_ms + 100)
760 g_profiler->graphAdd("client_received_packets", 1);
762 catch(con::NoIncomingDataException &e) {
765 catch(con::InvalidIncomingDataException &e) {
766 infostream<<"Client::ReceiveAll(): "
767 "InvalidIncomingDataException: what()="
768 <<e.what()<<std::endl;
773 void Client::Receive()
775 DSTACK(FUNCTION_NAME);
781 inline void Client::handleCommand(NetworkPacket* pkt)
783 const ToClientCommandHandler& opHandle = toClientCommandTable[pkt->getCommand()];
784 (this->*opHandle.handler)(pkt);
788 sender_peer_id given to this shall be quaranteed to be a valid peer
790 void Client::ProcessData(NetworkPacket *pkt)
792 DSTACK(FUNCTION_NAME);
794 ToClientCommand command = (ToClientCommand) pkt->getCommand();
795 u32 sender_peer_id = pkt->getPeerId();
797 //infostream<<"Client: received command="<<command<<std::endl;
798 m_packetcounter.add((u16)command);
801 If this check is removed, be sure to change the queue
802 system to know the ids
804 if(sender_peer_id != PEER_ID_SERVER) {
805 infostream << "Client::ProcessData(): Discarding data not "
806 "coming from server: peer_id=" << sender_peer_id
811 // Command must be handled into ToClientCommandHandler
812 if (command >= TOCLIENT_NUM_MSG_TYPES) {
813 infostream << "Client: Ignoring unknown command "
814 << command << std::endl;
819 * Those packets are handled before m_server_ser_ver is set, it's normal
820 * But we must use the new ToClientConnectionState in the future,
823 if(toClientCommandTable[command].state == TOCLIENT_STATE_NOT_CONNECTED) {
828 if(m_server_ser_ver == SER_FMT_VER_INVALID) {
829 infostream << "Client: Server serialization"
830 " format invalid or not initialized."
831 " Skipping incoming command=" << command << std::endl;
836 Handle runtime commands
842 void Client::Send(NetworkPacket* pkt)
844 m_con.Send(PEER_ID_SERVER,
845 serverCommandFactoryTable[pkt->getCommand()].channel,
847 serverCommandFactoryTable[pkt->getCommand()].reliable);
850 // Will fill up 12 + 12 + 4 + 4 + 4 bytes
851 void writePlayerPos(LocalPlayer *myplayer, ClientMap *clientMap, NetworkPacket *pkt)
853 v3f pf = myplayer->getPosition() * 100;
854 v3f sf = myplayer->getSpeed() * 100;
855 s32 pitch = myplayer->getPitch() * 100;
856 s32 yaw = myplayer->getYaw() * 100;
857 u32 keyPressed = myplayer->keyPressed;
858 // scaled by 80, so that pi can fit into a u8
859 u8 fov = clientMap->getCameraFov() * 80;
860 u8 wanted_range = MYMIN(255,
861 std::ceil(clientMap->getControl().wanted_range / MAP_BLOCKSIZE));
863 v3s32 position(pf.X, pf.Y, pf.Z);
864 v3s32 speed(sf.X, sf.Y, sf.Z);
868 [0] v3s32 position*100
870 [12+12] s32 pitch*100
871 [12+12+4] s32 yaw*100
872 [12+12+4+4] u32 keyPressed
873 [12+12+4+4+4] u8 fov*80
874 [12+12+4+4+4+1] u8 ceil(wanted_range / MAP_BLOCKSIZE)
876 *pkt << position << speed << pitch << yaw << keyPressed;
877 *pkt << fov << wanted_range;
880 void Client::interact(u8 action, const PointedThing& pointed)
882 if(m_state != LC_Ready) {
883 errorstream << "Client::interact() "
884 "Canceled (not connected)"
889 LocalPlayer *myplayer = m_env.getLocalPlayer();
890 if (myplayer == NULL)
897 [5] u32 length of the next item (plen)
898 [9] serialized PointedThing
899 [9 + plen] player position information
901 0: start digging (from undersurface) or use
902 1: stop digging (all parameters ignored)
904 3: place block or item (to abovesurface)
906 5: perform secondary action of item
909 NetworkPacket pkt(TOSERVER_INTERACT, 1 + 2 + 0);
912 pkt << (u16)getPlayerItem();
914 std::ostringstream tmp_os(std::ios::binary);
915 pointed.serialize(tmp_os);
917 pkt.putLongString(tmp_os.str());
919 writePlayerPos(myplayer, &m_env.getClientMap(), &pkt);
924 void Client::deleteAuthData()
929 switch (m_chosen_auth_mech) {
930 case AUTH_MECHANISM_FIRST_SRP:
932 case AUTH_MECHANISM_SRP:
933 case AUTH_MECHANISM_LEGACY_PASSWORD:
934 srp_user_delete((SRPUser *) m_auth_data);
937 case AUTH_MECHANISM_NONE:
940 m_chosen_auth_mech = AUTH_MECHANISM_NONE;
944 AuthMechanism Client::choseAuthMech(const u32 mechs)
946 if (mechs & AUTH_MECHANISM_SRP)
947 return AUTH_MECHANISM_SRP;
949 if (mechs & AUTH_MECHANISM_FIRST_SRP)
950 return AUTH_MECHANISM_FIRST_SRP;
952 if (mechs & AUTH_MECHANISM_LEGACY_PASSWORD)
953 return AUTH_MECHANISM_LEGACY_PASSWORD;
955 return AUTH_MECHANISM_NONE;
958 void Client::sendLegacyInit(const char* playerName, const char* playerPassword)
960 NetworkPacket pkt(TOSERVER_INIT_LEGACY,
961 1 + PLAYERNAME_SIZE + PASSWORD_SIZE + 2 + 2);
963 u16 proto_version_min = g_settings->getFlag("send_pre_v25_init") ?
964 CLIENT_PROTOCOL_VERSION_MIN_LEGACY : CLIENT_PROTOCOL_VERSION_MIN;
966 pkt << (u8) SER_FMT_VER_HIGHEST_READ;
967 pkt.putRawString(playerName,PLAYERNAME_SIZE);
968 pkt.putRawString(playerPassword, PASSWORD_SIZE);
969 pkt << (u16) proto_version_min << (u16) CLIENT_PROTOCOL_VERSION_MAX;
974 void Client::sendInit(const std::string &playerName)
976 NetworkPacket pkt(TOSERVER_INIT, 1 + 2 + 2 + (1 + playerName.size()));
978 // we don't support network compression yet
979 u16 supp_comp_modes = NETPROTO_COMPRESSION_NONE;
981 u16 proto_version_min = g_settings->getFlag("send_pre_v25_init") ?
982 CLIENT_PROTOCOL_VERSION_MIN_LEGACY : CLIENT_PROTOCOL_VERSION_MIN;
984 pkt << (u8) SER_FMT_VER_HIGHEST_READ << (u16) supp_comp_modes;
985 pkt << (u16) proto_version_min << (u16) CLIENT_PROTOCOL_VERSION_MAX;
991 void Client::startAuth(AuthMechanism chosen_auth_mechanism)
993 m_chosen_auth_mech = chosen_auth_mechanism;
995 switch (chosen_auth_mechanism) {
996 case AUTH_MECHANISM_FIRST_SRP: {
997 // send srp verifier to server
998 std::string verifier;
1000 generate_srp_verifier_and_salt(getPlayerName(), m_password,
1003 NetworkPacket resp_pkt(TOSERVER_FIRST_SRP, 0);
1004 resp_pkt << salt << verifier << (u8)((m_password == "") ? 1 : 0);
1009 case AUTH_MECHANISM_SRP:
1010 case AUTH_MECHANISM_LEGACY_PASSWORD: {
1013 if (chosen_auth_mechanism == AUTH_MECHANISM_LEGACY_PASSWORD) {
1014 m_password = translate_password(getPlayerName(), m_password);
1018 std::string playername_u = lowercase(getPlayerName());
1019 m_auth_data = srp_user_new(SRP_SHA256, SRP_NG_2048,
1020 getPlayerName().c_str(), playername_u.c_str(),
1021 (const unsigned char *) m_password.c_str(),
1022 m_password.length(), NULL, NULL);
1025 SRP_Result res = srp_user_start_authentication(
1026 (struct SRPUser *) m_auth_data, NULL, NULL, 0,
1027 (unsigned char **) &bytes_A, &len_A);
1028 FATAL_ERROR_IF(res != SRP_OK, "Creating local SRP user failed.");
1030 NetworkPacket resp_pkt(TOSERVER_SRP_BYTES_A, 0);
1031 resp_pkt << std::string(bytes_A, len_A) << based_on;
1035 case AUTH_MECHANISM_NONE:
1036 break; // not handled in this method
1040 void Client::sendDeletedBlocks(std::vector<v3s16> &blocks)
1042 NetworkPacket pkt(TOSERVER_DELETEDBLOCKS, 1 + sizeof(v3s16) * blocks.size());
1044 pkt << (u8) blocks.size();
1047 for(std::vector<v3s16>::iterator
1049 j != blocks.end(); ++j) {
1057 void Client::sendGotBlocks(v3s16 block)
1059 NetworkPacket pkt(TOSERVER_GOTBLOCKS, 1 + 6);
1060 pkt << (u8) 1 << block;
1064 void Client::sendRemovedSounds(std::vector<s32> &soundList)
1066 size_t server_ids = soundList.size();
1067 assert(server_ids <= 0xFFFF);
1069 NetworkPacket pkt(TOSERVER_REMOVED_SOUNDS, 2 + server_ids * 4);
1071 pkt << (u16) (server_ids & 0xFFFF);
1073 for(std::vector<s32>::iterator i = soundList.begin();
1074 i != soundList.end(); ++i)
1080 void Client::sendNodemetaFields(v3s16 p, const std::string &formname,
1081 const StringMap &fields)
1083 size_t fields_size = fields.size();
1085 FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of nodemeta fields");
1087 NetworkPacket pkt(TOSERVER_NODEMETA_FIELDS, 0);
1089 pkt << p << formname << (u16) (fields_size & 0xFFFF);
1091 StringMap::const_iterator it;
1092 for (it = fields.begin(); it != fields.end(); ++it) {
1093 const std::string &name = it->first;
1094 const std::string &value = it->second;
1096 pkt.putLongString(value);
1102 void Client::sendInventoryFields(const std::string &formname,
1103 const StringMap &fields)
1105 size_t fields_size = fields.size();
1106 FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of inventory fields");
1108 NetworkPacket pkt(TOSERVER_INVENTORY_FIELDS, 0);
1109 pkt << formname << (u16) (fields_size & 0xFFFF);
1111 StringMap::const_iterator it;
1112 for (it = fields.begin(); it != fields.end(); ++it) {
1113 const std::string &name = it->first;
1114 const std::string &value = it->second;
1116 pkt.putLongString(value);
1122 void Client::sendInventoryAction(InventoryAction *a)
1124 std::ostringstream os(std::ios_base::binary);
1129 std::string s = os.str();
1131 NetworkPacket pkt(TOSERVER_INVENTORY_ACTION, s.size());
1132 pkt.putRawString(s.c_str(),s.size());
1137 bool Client::canSendChatMessage() const
1139 u32 now = time(NULL);
1140 float time_passed = now - m_last_chat_message_sent;
1142 float virt_chat_message_allowance = m_chat_message_allowance + time_passed *
1143 (CLIENT_CHAT_MESSAGE_LIMIT_PER_10S / 8.0f);
1145 if (virt_chat_message_allowance < 1.0f)
1151 void Client::sendChatMessage(const std::wstring &message)
1153 const s16 max_queue_size = g_settings->getS16("max_out_chat_queue_size");
1154 if (canSendChatMessage()) {
1155 u32 now = time(NULL);
1156 float time_passed = now - m_last_chat_message_sent;
1157 m_last_chat_message_sent = time(NULL);
1159 m_chat_message_allowance += time_passed * (CLIENT_CHAT_MESSAGE_LIMIT_PER_10S / 8.0f);
1160 if (m_chat_message_allowance > CLIENT_CHAT_MESSAGE_LIMIT_PER_10S)
1161 m_chat_message_allowance = CLIENT_CHAT_MESSAGE_LIMIT_PER_10S;
1163 m_chat_message_allowance -= 1.0f;
1165 NetworkPacket pkt(TOSERVER_CHAT_MESSAGE, 2 + message.size() * sizeof(u16));
1170 } else if (m_out_chat_queue.size() < (u16) max_queue_size || max_queue_size == -1) {
1171 m_out_chat_queue.push(message);
1173 infostream << "Could not queue chat message because maximum out chat queue size ("
1174 << max_queue_size << ") is reached." << std::endl;
1178 void Client::clearOutChatQueue()
1180 m_out_chat_queue = std::queue<std::wstring>();
1183 void Client::sendChangePassword(const std::string &oldpassword,
1184 const std::string &newpassword)
1186 LocalPlayer *player = m_env.getLocalPlayer();
1190 std::string playername = player->getName();
1191 if (m_proto_ver >= 25) {
1192 // get into sudo mode and then send new password to server
1193 m_password = oldpassword;
1194 m_new_password = newpassword;
1195 startAuth(choseAuthMech(m_sudo_auth_methods));
1197 std::string oldpwd = translate_password(playername, oldpassword);
1198 std::string newpwd = translate_password(playername, newpassword);
1200 NetworkPacket pkt(TOSERVER_PASSWORD_LEGACY, 2 * PASSWORD_SIZE);
1202 for (u8 i = 0; i < PASSWORD_SIZE; i++) {
1203 pkt << (u8) (i < oldpwd.length() ? oldpwd[i] : 0);
1206 for (u8 i = 0; i < PASSWORD_SIZE; i++) {
1207 pkt << (u8) (i < newpwd.length() ? newpwd[i] : 0);
1214 void Client::sendDamage(u8 damage)
1216 DSTACK(FUNCTION_NAME);
1218 NetworkPacket pkt(TOSERVER_DAMAGE, sizeof(u8));
1223 void Client::sendBreath(u16 breath)
1225 DSTACK(FUNCTION_NAME);
1227 // Protocol v29 make this obsolete
1228 if (m_proto_ver >= 29)
1231 NetworkPacket pkt(TOSERVER_BREATH, sizeof(u16));
1236 void Client::sendRespawn()
1238 DSTACK(FUNCTION_NAME);
1240 NetworkPacket pkt(TOSERVER_RESPAWN, 0);
1244 void Client::sendReady()
1246 DSTACK(FUNCTION_NAME);
1248 NetworkPacket pkt(TOSERVER_CLIENT_READY,
1249 1 + 1 + 1 + 1 + 2 + sizeof(char) * strlen(g_version_hash));
1251 pkt << (u8) VERSION_MAJOR << (u8) VERSION_MINOR << (u8) VERSION_PATCH
1252 << (u8) 0 << (u16) strlen(g_version_hash);
1254 pkt.putRawString(g_version_hash, (u16) strlen(g_version_hash));
1258 void Client::sendPlayerPos()
1260 LocalPlayer *myplayer = m_env.getLocalPlayer();
1261 if(myplayer == NULL)
1264 ClientMap &map = m_env.getClientMap();
1266 u8 camera_fov = map.getCameraFov();
1267 u8 wanted_range = map.getControl().wanted_range;
1269 // Save bandwidth by only updating position when something changed
1270 if(myplayer->last_position == myplayer->getPosition() &&
1271 myplayer->last_speed == myplayer->getSpeed() &&
1272 myplayer->last_pitch == myplayer->getPitch() &&
1273 myplayer->last_yaw == myplayer->getYaw() &&
1274 myplayer->last_keyPressed == myplayer->keyPressed &&
1275 myplayer->last_camera_fov == camera_fov &&
1276 myplayer->last_wanted_range == wanted_range)
1279 myplayer->last_position = myplayer->getPosition();
1280 myplayer->last_speed = myplayer->getSpeed();
1281 myplayer->last_pitch = myplayer->getPitch();
1282 myplayer->last_yaw = myplayer->getYaw();
1283 myplayer->last_keyPressed = myplayer->keyPressed;
1284 myplayer->last_camera_fov = camera_fov;
1285 myplayer->last_wanted_range = wanted_range;
1287 //infostream << "Sending Player Position information" << std::endl;
1291 //MutexAutoLock lock(m_con_mutex); //bulk comment-out
1292 our_peer_id = m_con.GetPeerID();
1295 // Set peer id if not set already
1296 if(myplayer->peer_id == PEER_ID_INEXISTENT)
1297 myplayer->peer_id = our_peer_id;
1299 assert(myplayer->peer_id == our_peer_id);
1301 NetworkPacket pkt(TOSERVER_PLAYERPOS, 12 + 12 + 4 + 4 + 4 + 1 + 1);
1303 writePlayerPos(myplayer, &map, &pkt);
1308 void Client::sendPlayerItem(u16 item)
1310 LocalPlayer *myplayer = m_env.getLocalPlayer();
1311 if(myplayer == NULL)
1314 u16 our_peer_id = m_con.GetPeerID();
1316 // Set peer id if not set already
1317 if(myplayer->peer_id == PEER_ID_INEXISTENT)
1318 myplayer->peer_id = our_peer_id;
1319 assert(myplayer->peer_id == our_peer_id);
1321 NetworkPacket pkt(TOSERVER_PLAYERITEM, 2);
1328 void Client::removeNode(v3s16 p)
1330 std::map<v3s16, MapBlock*> modified_blocks;
1333 m_env.getMap().removeNodeAndUpdate(p, modified_blocks);
1335 catch(InvalidPositionException &e) {
1338 for(std::map<v3s16, MapBlock *>::iterator
1339 i = modified_blocks.begin();
1340 i != modified_blocks.end(); ++i) {
1341 addUpdateMeshTaskWithEdge(i->first, false, true);
1345 MapNode Client::getNode(v3s16 p, bool *is_valid_position)
1347 return m_env.getMap().getNodeNoEx(p, is_valid_position);
1350 void Client::addNode(v3s16 p, MapNode n, bool remove_metadata)
1352 //TimeTaker timer1("Client::addNode()");
1354 std::map<v3s16, MapBlock*> modified_blocks;
1357 //TimeTaker timer3("Client::addNode(): addNodeAndUpdate");
1358 m_env.getMap().addNodeAndUpdate(p, n, modified_blocks, remove_metadata);
1360 catch(InvalidPositionException &e) {
1363 for(std::map<v3s16, MapBlock *>::iterator
1364 i = modified_blocks.begin();
1365 i != modified_blocks.end(); ++i) {
1366 addUpdateMeshTaskWithEdge(i->first, false, true);
1370 void Client::setPlayerControl(PlayerControl &control)
1372 LocalPlayer *player = m_env.getLocalPlayer();
1374 player->control = control;
1377 void Client::selectPlayerItem(u16 item)
1379 m_playeritem = item;
1380 m_inventory_updated = true;
1381 sendPlayerItem(item);
1384 // Returns true if the inventory of the local player has been
1385 // updated from the server. If it is true, it is set to false.
1386 bool Client::getLocalInventoryUpdated()
1388 bool updated = m_inventory_updated;
1389 m_inventory_updated = false;
1393 // Copies the inventory of the local player to parameter
1394 void Client::getLocalInventory(Inventory &dst)
1396 LocalPlayer *player = m_env.getLocalPlayer();
1398 dst = player->inventory;
1401 Inventory* Client::getInventory(const InventoryLocation &loc)
1404 case InventoryLocation::UNDEFINED:
1407 case InventoryLocation::CURRENT_PLAYER:
1409 LocalPlayer *player = m_env.getLocalPlayer();
1411 return &player->inventory;
1414 case InventoryLocation::PLAYER:
1416 // Check if we are working with local player inventory
1417 LocalPlayer *player = m_env.getLocalPlayer();
1418 if (!player || strcmp(player->getName(), loc.name.c_str()) != 0)
1420 return &player->inventory;
1423 case InventoryLocation::NODEMETA:
1425 NodeMetadata *meta = m_env.getMap().getNodeMetadata(loc.p);
1428 return meta->getInventory();
1431 case InventoryLocation::DETACHED:
1433 if (m_detached_inventories.count(loc.name) == 0)
1435 return m_detached_inventories[loc.name];
1439 FATAL_ERROR("Invalid inventory location type.");
1445 void Client::inventoryAction(InventoryAction *a)
1448 Send it to the server
1450 sendInventoryAction(a);
1453 Predict some local inventory changes
1455 a->clientApply(this, this);
1461 float Client::getAnimationTime()
1463 return m_animation_time;
1466 int Client::getCrackLevel()
1468 return m_crack_level;
1471 v3s16 Client::getCrackPos()
1476 void Client::setCrack(int level, v3s16 pos)
1478 int old_crack_level = m_crack_level;
1479 v3s16 old_crack_pos = m_crack_pos;
1481 m_crack_level = level;
1484 if(old_crack_level >= 0 && (level < 0 || pos != old_crack_pos))
1487 addUpdateMeshTaskForNode(old_crack_pos, false, true);
1489 if(level >= 0 && (old_crack_level < 0 || pos != old_crack_pos))
1492 addUpdateMeshTaskForNode(pos, false, true);
1498 LocalPlayer *player = m_env.getLocalPlayer();
1503 bool Client::getChatMessage(std::wstring &message)
1505 if(m_chat_queue.size() == 0)
1507 message = m_chat_queue.front();
1512 void Client::typeChatMessage(const std::wstring &message)
1514 // Discard empty line
1518 // If message was ate by script API, don't send it to server
1519 if (m_script->on_sending_message(wide_to_utf8(message))) {
1524 sendChatMessage(message);
1527 if (message[0] != L'/')
1529 // compatibility code
1530 if (m_proto_ver < 29) {
1531 LocalPlayer *player = m_env.getLocalPlayer();
1533 std::wstring name = narrow_to_wide(player->getName());
1534 pushToChatQueue((std::wstring)L"<" + name + L"> " + message);
1539 void Client::addUpdateMeshTask(v3s16 p, bool ack_to_server, bool urgent)
1541 // Check if the block exists to begin with. In the case when a non-existing
1542 // neighbor is automatically added, it may not. In that case we don't want
1543 // to tell the mesh update thread about it.
1544 MapBlock *b = m_env.getMap().getBlockNoCreateNoEx(p);
1548 m_mesh_update_thread.updateBlock(&m_env.getMap(), p, ack_to_server, urgent);
1551 void Client::addUpdateMeshTaskWithEdge(v3s16 blockpos, bool ack_to_server, bool urgent)
1554 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1556 catch(InvalidPositionException &e){}
1559 for (int i=0;i<6;i++)
1562 v3s16 p = blockpos + g_6dirs[i];
1563 addUpdateMeshTask(p, false, urgent);
1565 catch(InvalidPositionException &e){}
1569 void Client::addUpdateMeshTaskForNode(v3s16 nodepos, bool ack_to_server, bool urgent)
1573 infostream<<"Client::addUpdateMeshTaskForNode(): "
1574 <<"("<<p.X<<","<<p.Y<<","<<p.Z<<")"
1578 v3s16 blockpos = getNodeBlockPos(nodepos);
1579 v3s16 blockpos_relative = blockpos * MAP_BLOCKSIZE;
1582 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1584 catch(InvalidPositionException &e) {}
1587 if(nodepos.X == blockpos_relative.X){
1589 v3s16 p = blockpos + v3s16(-1,0,0);
1590 addUpdateMeshTask(p, false, urgent);
1592 catch(InvalidPositionException &e){}
1595 if(nodepos.Y == blockpos_relative.Y){
1597 v3s16 p = blockpos + v3s16(0,-1,0);
1598 addUpdateMeshTask(p, false, urgent);
1600 catch(InvalidPositionException &e){}
1603 if(nodepos.Z == blockpos_relative.Z){
1605 v3s16 p = blockpos + v3s16(0,0,-1);
1606 addUpdateMeshTask(p, false, urgent);
1608 catch(InvalidPositionException &e){}
1612 ClientEvent Client::getClientEvent()
1614 FATAL_ERROR_IF(m_client_event_queue.empty(),
1615 "Cannot getClientEvent, queue is empty.");
1617 ClientEvent event = m_client_event_queue.front();
1618 m_client_event_queue.pop();
1622 float Client::mediaReceiveProgress()
1624 if (m_media_downloader)
1625 return m_media_downloader->getProgress();
1627 return 1.0; // downloader only exists when not yet done
1630 typedef struct TextureUpdateArgs {
1631 IrrlichtDevice *device;
1632 gui::IGUIEnvironment *guienv;
1635 const wchar_t* text_base;
1636 ITextureSource *tsrc;
1637 } TextureUpdateArgs;
1639 void texture_update_progress(void *args, u32 progress, u32 max_progress)
1641 TextureUpdateArgs* targs = (TextureUpdateArgs*) args;
1642 u16 cur_percent = ceil(progress / (double) max_progress * 100.);
1644 // update the loading menu -- if neccessary
1645 bool do_draw = false;
1646 u64 time_ms = targs->last_time_ms;
1647 if (cur_percent != targs->last_percent) {
1648 targs->last_percent = cur_percent;
1649 time_ms = porting::getTimeMs();
1650 // only draw when the user will notice something:
1651 do_draw = (time_ms - targs->last_time_ms > 100);
1655 targs->last_time_ms = time_ms;
1656 std::basic_stringstream<wchar_t> strm;
1657 strm << targs->text_base << " " << targs->last_percent << "%...";
1658 draw_load_screen(strm.str(), targs->device, targs->guienv, targs->tsrc, 0,
1659 72 + (u16) ((18. / 100.) * (double) targs->last_percent), true);
1663 void Client::afterContentReceived(IrrlichtDevice *device)
1665 infostream<<"Client::afterContentReceived() started"<<std::endl;
1666 assert(m_itemdef_received); // pre-condition
1667 assert(m_nodedef_received); // pre-condition
1668 assert(mediaReceived()); // pre-condition
1670 const wchar_t* text = wgettext("Loading textures...");
1672 // Clear cached pre-scaled 2D GUI images, as this cache
1673 // might have images with the same name but different
1674 // content from previous sessions.
1675 guiScalingCacheClear(device->getVideoDriver());
1677 // Rebuild inherited images and recreate textures
1678 infostream<<"- Rebuilding images and textures"<<std::endl;
1679 draw_load_screen(text,device, guienv, m_tsrc, 0, 70);
1680 m_tsrc->rebuildImagesAndTextures();
1684 infostream<<"- Rebuilding shaders"<<std::endl;
1685 text = wgettext("Rebuilding shaders...");
1686 draw_load_screen(text, device, guienv, m_tsrc, 0, 71);
1687 m_shsrc->rebuildShaders();
1690 // Update node aliases
1691 infostream<<"- Updating node aliases"<<std::endl;
1692 text = wgettext("Initializing nodes...");
1693 draw_load_screen(text, device, guienv, m_tsrc, 0, 72);
1694 m_nodedef->updateAliases(m_itemdef);
1695 std::string texture_path = g_settings->get("texture_path");
1696 if (texture_path != "" && fs::IsDir(texture_path))
1697 m_nodedef->applyTextureOverrides(texture_path + DIR_DELIM + "override.txt");
1698 m_nodedef->setNodeRegistrationStatus(true);
1699 m_nodedef->runNodeResolveCallbacks();
1702 // Update node textures and assign shaders to each tile
1703 infostream<<"- Updating node textures"<<std::endl;
1704 TextureUpdateArgs tu_args;
1705 tu_args.device = device;
1706 tu_args.guienv = guienv;
1707 tu_args.last_time_ms = porting::getTimeMs();
1708 tu_args.last_percent = 0;
1709 tu_args.text_base = wgettext("Initializing nodes");
1710 tu_args.tsrc = m_tsrc;
1711 m_nodedef->updateTextures(this, texture_update_progress, &tu_args);
1712 delete[] tu_args.text_base;
1714 // Start mesh update thread after setting up content definitions
1715 infostream<<"- Starting mesh update thread"<<std::endl;
1716 m_mesh_update_thread.start();
1721 if (g_settings->getBool("enable_client_modding")) {
1722 m_script->on_client_ready(m_env.getLocalPlayer());
1723 m_script->on_connect();
1726 text = wgettext("Done!");
1727 draw_load_screen(text, device, guienv, m_tsrc, 0, 100);
1728 infostream<<"Client::afterContentReceived() done"<<std::endl;
1732 float Client::getRTT()
1734 return m_con.getPeerStat(PEER_ID_SERVER,con::AVG_RTT);
1737 float Client::getCurRate()
1739 return (m_con.getLocalStat(con::CUR_INC_RATE) +
1740 m_con.getLocalStat(con::CUR_DL_RATE));
1743 void Client::makeScreenshot()
1745 irr::video::IVideoDriver *driver = m_device->getVideoDriver();
1746 irr::video::IImage* const raw_image = driver->createScreenShot();
1751 time_t t = time(NULL);
1752 struct tm *tm = localtime(&t);
1754 char timetstamp_c[64];
1755 strftime(timetstamp_c, sizeof(timetstamp_c), "%Y%m%d_%H%M%S", tm);
1757 std::string filename_base = g_settings->get("screenshot_path")
1759 + std::string("screenshot_")
1760 + std::string(timetstamp_c);
1761 std::string filename_ext = "." + g_settings->get("screenshot_format");
1762 std::string filename;
1764 u32 quality = (u32)g_settings->getS32("screenshot_quality");
1765 quality = MYMIN(MYMAX(quality, 0), 100) / 100.0 * 255;
1767 // Try to find a unique filename
1768 unsigned serial = 0;
1770 while (serial < SCREENSHOT_MAX_SERIAL_TRIES) {
1771 filename = filename_base + (serial > 0 ? ("_" + itos(serial)) : "") + filename_ext;
1772 std::ifstream tmp(filename.c_str());
1774 break; // File did not apparently exist, we'll go with it
1778 if (serial == SCREENSHOT_MAX_SERIAL_TRIES) {
1779 infostream << "Could not find suitable filename for screenshot" << std::endl;
1781 irr::video::IImage* const image =
1782 driver->createImage(video::ECF_R8G8B8, raw_image->getDimension());
1785 raw_image->copyTo(image);
1787 std::ostringstream sstr;
1788 if (driver->writeImageToFile(image, filename.c_str(), quality)) {
1789 sstr << "Saved screenshot to '" << filename << "'";
1791 sstr << "Failed to save screenshot '" << filename << "'";
1793 pushToChatQueue(narrow_to_wide(sstr.str()));
1794 infostream << sstr.str() << std::endl;
1802 bool Client::shouldShowMinimap() const
1804 return !m_minimap_disabled_by_server;
1807 void Client::showGameChat(const bool show)
1809 m_game_ui_flags->show_chat = show;
1812 void Client::showGameHud(const bool show)
1814 m_game_ui_flags->show_hud = show;
1817 void Client::showMinimap(const bool show)
1819 m_game_ui_flags->show_minimap = show;
1822 void Client::showProfiler(const bool show)
1824 m_game_ui_flags->show_profiler_graph = show;
1827 void Client::showGameFog(const bool show)
1829 m_game_ui_flags->force_fog_off = !show;
1832 void Client::showGameDebug(const bool show)
1834 m_game_ui_flags->show_debug = show;
1837 // IGameDef interface
1839 IItemDefManager* Client::getItemDefManager()
1843 INodeDefManager* Client::getNodeDefManager()
1847 ICraftDefManager* Client::getCraftDefManager()
1850 //return m_craftdef;
1852 ITextureSource* Client::getTextureSource()
1856 IShaderSource* Client::getShaderSource()
1860 scene::ISceneManager* Client::getSceneManager()
1862 return m_device->getSceneManager();
1864 u16 Client::allocateUnknownNodeId(const std::string &name)
1866 errorstream << "Client::allocateUnknownNodeId(): "
1867 << "Client cannot allocate node IDs" << std::endl;
1868 FATAL_ERROR("Client allocated unknown node");
1870 return CONTENT_IGNORE;
1872 ISoundManager* Client::getSoundManager()
1876 MtEventManager* Client::getEventManager()
1881 ParticleManager* Client::getParticleManager()
1883 return &m_particle_manager;
1886 scene::IAnimatedMesh* Client::getMesh(const std::string &filename)
1888 StringMap::const_iterator it = m_mesh_data.find(filename);
1889 if (it == m_mesh_data.end()) {
1890 errorstream << "Client::getMesh(): Mesh not found: \"" << filename
1891 << "\"" << std::endl;
1894 const std::string &data = it->second;
1895 scene::ISceneManager *smgr = m_device->getSceneManager();
1897 // Create the mesh, remove it from cache and return it
1898 // This allows unique vertex colors and other properties for each instance
1899 Buffer<char> data_rw(data.c_str(), data.size()); // Const-incorrect Irrlicht
1900 io::IFileSystem *irrfs = m_device->getFileSystem();
1901 io::IReadFile *rfile = irrfs->createMemoryReadFile(
1902 *data_rw, data_rw.getSize(), filename.c_str());
1903 FATAL_ERROR_IF(!rfile, "Could not create/open RAM file");
1905 scene::IAnimatedMesh *mesh = smgr->getMesh(rfile);
1907 // NOTE: By playing with Irrlicht refcounts, maybe we could cache a bunch
1908 // of uniquely named instances and re-use them
1910 smgr->getMeshCache()->removeMesh(mesh);
1914 bool Client::registerModStorage(ModMetadata *storage)
1916 if (m_mod_storages.find(storage->getModName()) != m_mod_storages.end()) {
1917 errorstream << "Unable to register same mod storage twice. Storage name: "
1918 << storage->getModName() << std::endl;
1922 m_mod_storages[storage->getModName()] = storage;
1926 void Client::unregisterModStorage(const std::string &name)
1928 std::unordered_map<std::string, ModMetadata *>::const_iterator it =
1929 m_mod_storages.find(name);
1930 if (it != m_mod_storages.end()) {
1931 // Save unconditionaly on unregistration
1932 it->second->save(getModStoragePath());
1933 m_mod_storages.erase(name);
1937 std::string Client::getModStoragePath() const
1939 return porting::path_user + DIR_DELIM + "client" + DIR_DELIM + "mod_storage";