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/clientscripting.h"
50 extern gui::IGUIEnvironment* guienv;
56 QueuedMeshUpdate::QueuedMeshUpdate():
59 ack_block_to_server(false)
63 QueuedMeshUpdate::~QueuedMeshUpdate()
73 MeshUpdateQueue::MeshUpdateQueue()
77 MeshUpdateQueue::~MeshUpdateQueue()
79 MutexAutoLock lock(m_mutex);
81 for(std::vector<QueuedMeshUpdate*>::iterator
83 i != m_queue.end(); ++i)
85 QueuedMeshUpdate *q = *i;
91 peer_id=0 adds with nobody to send to
93 void MeshUpdateQueue::addBlock(v3s16 p, MeshMakeData *data, bool ack_block_to_server, bool urgent)
95 DSTACK(FUNCTION_NAME);
97 assert(data); // pre-condition
99 MutexAutoLock lock(m_mutex);
105 Find if block is already in queue.
106 If it is, update the data and quit.
108 for(std::vector<QueuedMeshUpdate*>::iterator
110 i != m_queue.end(); ++i)
112 QueuedMeshUpdate *q = *i;
118 if(ack_block_to_server)
119 q->ack_block_to_server = true;
127 QueuedMeshUpdate *q = new QueuedMeshUpdate;
130 q->ack_block_to_server = ack_block_to_server;
131 m_queue.push_back(q);
134 // Returned pointer must be deleted
135 // Returns NULL if queue is empty
136 QueuedMeshUpdate *MeshUpdateQueue::pop()
138 MutexAutoLock lock(m_mutex);
140 bool must_be_urgent = !m_urgents.empty();
141 for(std::vector<QueuedMeshUpdate*>::iterator
143 i != m_queue.end(); ++i)
145 QueuedMeshUpdate *q = *i;
146 if(must_be_urgent && m_urgents.count(q->p) == 0)
149 m_urgents.erase(q->p);
159 void MeshUpdateThread::enqueueUpdate(v3s16 p, MeshMakeData *data,
160 bool ack_block_to_server, bool urgent)
162 m_queue_in.addBlock(p, data, ack_block_to_server, urgent);
166 void MeshUpdateThread::doUpdate()
169 while ((q = m_queue_in.pop())) {
171 ScopeProfiler sp(g_profiler, "Client: Mesh making");
173 MapBlockMesh *mesh_new = new MapBlockMesh(q->data, m_camera_offset);
178 r.ack_block_to_server = q->ack_block_to_server;
180 m_queue_out.push_back(r);
191 IrrlichtDevice *device,
192 const char *playername,
193 std::string password,
194 MapDrawControl &control,
195 IWritableTextureSource *tsrc,
196 IWritableShaderSource *shsrc,
197 IWritableItemDefManager *itemdef,
198 IWritableNodeDefManager *nodedef,
199 ISoundManager *sound,
200 MtEventManager *event,
203 m_packetcounter_timer(0.0),
204 m_connection_reinit_timer(0.1),
205 m_avg_rtt_timer(0.0),
206 m_playerpos_send_timer(0.0),
207 m_ignore_damage_timer(0.0),
214 m_mesh_update_thread(),
216 new ClientMap(this, control,
217 device->getSceneManager()->getRootSceneNode(),
218 device->getSceneManager(), 666),
219 device->getSceneManager(),
222 m_particle_manager(&m_env),
223 m_con(PROTOCOL_ID, 512, CONNECTION_TIMEOUT, ipv6, this),
226 m_minimap_disabled_by_server(false),
227 m_minimap_shown_by_mod(false),
228 m_server_ser_ver(SER_FMT_VER_INVALID),
231 m_inventory_updated(false),
232 m_inventory_from_server(NULL),
233 m_inventory_from_server_age(0.0),
238 m_password(password),
239 m_chosen_auth_mech(AUTH_MECHANISM_NONE),
241 m_access_denied(false),
242 m_access_denied_reconnect(false),
243 m_itemdef_received(false),
244 m_nodedef_received(false),
245 m_media_downloader(new ClientMediaDownloader()),
246 m_time_of_day_set(false),
247 m_last_time_of_day_f(-1),
248 m_time_of_day_update_timer(0),
249 m_recommended_send_interval(0.1),
250 m_removed_sounds_check_timer(0),
254 m_mod_storage_save_timer(10.0f)
257 m_env.setLocalPlayer(new LocalPlayer(this, playername));
259 m_minimap = new Minimap(device, this);
260 m_cache_save_interval = g_settings->getU16("server_map_save_interval");
262 m_cache_smooth_lighting = g_settings->getBool("smooth_lighting");
263 m_cache_enable_shaders = g_settings->getBool("enable_shaders");
264 m_cache_use_tangent_vertices = m_cache_enable_shaders && (
265 g_settings->getBool("enable_bumpmapping") ||
266 g_settings->getBool("enable_parallax_occlusion"));
268 m_modding_enabled = g_settings->getBool("enable_client_modding");
269 m_script = new ClientScripting(this);
270 m_env.setScript(m_script);
271 m_script->setEnv(&m_env);
274 void Client::initMods()
276 m_script->loadMod(getBuiltinLuaPath() + DIR_DELIM "init.lua", BUILTIN_MOD_NAME);
278 // If modding is not enabled, don't load mods, just builtin
279 if (!m_modding_enabled) {
283 ClientModConfiguration modconf(getClientModsLuaPath());
284 std::vector<ModSpec> mods = modconf.getMods();
285 std::vector<ModSpec> unsatisfied_mods = modconf.getUnsatisfiedMods();
286 // complain about mods with unsatisfied dependencies
287 if (!modconf.isConsistent()) {
288 modconf.printUnsatisfiedModsError();
292 infostream << "Client Loading mods: ";
293 for (std::vector<ModSpec>::const_iterator i = mods.begin();
294 i != mods.end(); ++i) {
295 infostream << (*i).name << " ";
298 infostream << std::endl;
299 // Load and run "mod" scripts
300 for (std::vector<ModSpec>::const_iterator it = mods.begin();
301 it != mods.end(); ++it) {
302 const ModSpec &mod = *it;
303 if (!string_allowed(mod.name, MODNAME_ALLOWED_CHARS)) {
304 throw ModError("Error loading mod \"" + mod.name +
305 "\": Mod name does not follow naming conventions: "
306 "Only chararacters [a-z0-9_] are allowed.");
308 std::string script_path = mod.path + DIR_DELIM + "init.lua";
309 infostream << " [" << padStringRight(mod.name, 12) << "] [\""
310 << script_path << "\"]" << std::endl;
311 m_script->loadMod(script_path, mod.name);
315 const std::string &Client::getBuiltinLuaPath()
317 static const std::string builtin_dir = porting::path_share + DIR_DELIM + "builtin";
321 const std::string &Client::getClientModsLuaPath()
323 static const std::string clientmods_dir = porting::path_share + DIR_DELIM + "clientmods";
324 return clientmods_dir;
327 const std::vector<ModSpec>& Client::getMods() const
329 static std::vector<ModSpec> client_modspec_temp;
330 return client_modspec_temp;
333 const ModSpec* Client::getModSpec(const std::string &modname) const
340 // Don't disable this part when modding is disabled, it's used in builtin
341 m_script->on_shutdown();
342 //request all client managed threads to stop
343 m_mesh_update_thread.stop();
344 // Save local server map
346 infostream << "Local map saving ended." << std::endl;
347 m_localdb->endSave();
353 bool Client::isShutdown()
356 if (!m_mesh_update_thread.isRunning()) return true;
365 m_mesh_update_thread.stop();
366 m_mesh_update_thread.wait();
367 while (!m_mesh_update_thread.m_queue_out.empty()) {
368 MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_frontNoEx();
373 delete m_inventory_from_server;
375 // Delete detached inventories
376 for (UNORDERED_MAP<std::string, Inventory*>::iterator
377 i = m_detached_inventories.begin();
378 i != m_detached_inventories.end(); ++i) {
382 // cleanup 3d model meshes on client shutdown
383 while (m_device->getSceneManager()->getMeshCache()->getMeshCount() != 0) {
384 scene::IAnimatedMesh *mesh =
385 m_device->getSceneManager()->getMeshCache()->getMeshByIndex(0);
388 m_device->getSceneManager()->getMeshCache()->removeMesh(mesh);
394 void Client::connect(Address address,
395 const std::string &address_name,
396 bool is_local_server)
398 DSTACK(FUNCTION_NAME);
400 initLocalMapSaving(address, address_name, is_local_server);
402 m_con.SetTimeoutMs(0);
403 m_con.Connect(address);
406 void Client::step(float dtime)
408 DSTACK(FUNCTION_NAME);
414 if(m_ignore_damage_timer > dtime)
415 m_ignore_damage_timer -= dtime;
417 m_ignore_damage_timer = 0.0;
419 m_animation_time += dtime;
420 if(m_animation_time > 60.0)
421 m_animation_time -= 60.0;
423 m_time_of_day_update_timer += dtime;
431 float &counter = m_packetcounter_timer;
437 infostream << "Client packetcounter (" << m_packetcounter_timer
439 m_packetcounter.print(infostream);
440 m_packetcounter.clear();
444 // UGLY hack to fix 2 second startup delay caused by non existent
445 // server client startup synchronization in local server or singleplayer mode
446 static bool initial_step = true;
448 initial_step = false;
450 else if(m_state == LC_Created) {
451 float &counter = m_connection_reinit_timer;
456 LocalPlayer *myplayer = m_env.getLocalPlayer();
457 FATAL_ERROR_IF(myplayer == NULL, "Local player not found in environment.");
459 u16 proto_version_min = g_settings->getFlag("send_pre_v25_init") ?
460 CLIENT_PROTOCOL_VERSION_MIN_LEGACY : CLIENT_PROTOCOL_VERSION_MIN;
462 if (proto_version_min < 25) {
463 // Send TOSERVER_INIT_LEGACY
464 // [0] u16 TOSERVER_INIT_LEGACY
465 // [2] u8 SER_FMT_VER_HIGHEST_READ
466 // [3] u8[20] player_name
467 // [23] u8[28] password (new in some version)
468 // [51] u16 minimum supported network protocol version (added sometime)
469 // [53] u16 maximum supported network protocol version (added later than the previous one)
471 char pName[PLAYERNAME_SIZE];
472 char pPassword[PASSWORD_SIZE];
473 memset(pName, 0, PLAYERNAME_SIZE * sizeof(char));
474 memset(pPassword, 0, PASSWORD_SIZE * sizeof(char));
476 std::string hashed_password = translate_password(myplayer->getName(), m_password);
477 snprintf(pName, PLAYERNAME_SIZE, "%s", myplayer->getName());
478 snprintf(pPassword, PASSWORD_SIZE, "%s", hashed_password.c_str());
480 sendLegacyInit(pName, pPassword);
482 if (CLIENT_PROTOCOL_VERSION_MAX >= 25)
483 sendInit(myplayer->getName());
486 // Not connected, return
491 Do stuff if connected
495 Run Map's timers and unload unused data
497 const float map_timer_and_unload_dtime = 5.25;
498 if(m_map_timer_and_unload_interval.step(dtime, map_timer_and_unload_dtime)) {
499 ScopeProfiler sp(g_profiler, "Client: map timer and unload");
500 std::vector<v3s16> deleted_blocks;
501 m_env.getMap().timerUpdate(map_timer_and_unload_dtime,
502 g_settings->getFloat("client_unload_unused_data_timeout"),
503 g_settings->getS32("client_mapblock_limit"),
508 NOTE: This loop is intentionally iterated the way it is.
511 std::vector<v3s16>::iterator i = deleted_blocks.begin();
512 std::vector<v3s16> sendlist;
514 if(sendlist.size() == 255 || i == deleted_blocks.end()) {
525 sendDeletedBlocks(sendlist);
527 if(i == deleted_blocks.end())
533 sendlist.push_back(*i);
541 // Control local player (0ms)
542 LocalPlayer *player = m_env.getLocalPlayer();
543 assert(player != NULL);
544 player->applyControl(dtime);
553 ClientEnvEvent event = m_env.getClientEvent();
554 if(event.type == CEE_NONE) {
557 else if(event.type == CEE_PLAYER_DAMAGE) {
558 if(m_ignore_damage_timer <= 0) {
559 u8 damage = event.player_damage.amount;
561 if(event.player_damage.send_to_server)
564 // Add to ClientEvent queue
566 event.type = CE_PLAYER_DAMAGE;
567 event.player_damage.amount = damage;
568 m_client_event_queue.push(event);
571 // Protocol v29 or greater obsoleted this event
572 else if (event.type == CEE_PLAYER_BREATH && m_proto_ver < 29) {
573 u16 breath = event.player_breath.amount;
581 float &counter = m_avg_rtt_timer;
585 // connectedAndInitialized() is true, peer exists.
586 float avg_rtt = getRTT();
587 infostream << "Client: avg_rtt=" << avg_rtt << std::endl;
591 Send player position to server
594 float &counter = m_playerpos_send_timer;
596 if((m_state == LC_Ready) && (counter >= m_recommended_send_interval))
604 Replace updated meshes
607 int num_processed_meshes = 0;
608 while (!m_mesh_update_thread.m_queue_out.empty())
610 num_processed_meshes++;
612 MinimapMapblock *minimap_mapblock = NULL;
613 bool do_mapper_update = true;
615 MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_frontNoEx();
616 MapBlock *block = m_env.getMap().getBlockNoCreateNoEx(r.p);
618 // Delete the old mesh
619 if (block->mesh != NULL) {
625 minimap_mapblock = r.mesh->moveMinimapMapblock();
626 if (minimap_mapblock == NULL)
627 do_mapper_update = false;
630 if (r.mesh && r.mesh->getMesh()->getMeshBufferCount() == 0) {
633 // Replace with the new mesh
634 block->mesh = r.mesh;
640 if (do_mapper_update)
641 m_minimap->addBlock(r.p, minimap_mapblock);
643 if (r.ack_block_to_server) {
653 if (num_processed_meshes > 0)
654 g_profiler->graphAdd("num_processed_meshes", num_processed_meshes);
660 if (m_media_downloader && m_media_downloader->isStarted()) {
661 m_media_downloader->step(this);
662 if (m_media_downloader->isDone()) {
664 delete m_media_downloader;
665 m_media_downloader = NULL;
670 If the server didn't update the inventory in a while, revert
671 the local inventory (so the player notices the lag problem
672 and knows something is wrong).
674 if(m_inventory_from_server)
676 float interval = 10.0;
677 float count_before = floor(m_inventory_from_server_age / interval);
679 m_inventory_from_server_age += dtime;
681 float count_after = floor(m_inventory_from_server_age / interval);
683 if(count_after != count_before)
685 // Do this every <interval> seconds after TOCLIENT_INVENTORY
686 // Reset the locally changed inventory to the authoritative inventory
687 LocalPlayer *player = m_env.getLocalPlayer();
688 player->inventory = *m_inventory_from_server;
689 m_inventory_updated = true;
694 Update positions of sounds attached to objects
697 for(UNORDERED_MAP<int, u16>::iterator i = m_sounds_to_objects.begin();
698 i != m_sounds_to_objects.end(); ++i) {
699 int client_id = i->first;
700 u16 object_id = i->second;
701 ClientActiveObject *cao = m_env.getActiveObject(object_id);
704 v3f pos = cao->getPosition();
705 m_sound->updateSoundPosition(client_id, pos);
710 Handle removed remotely initiated sounds
712 m_removed_sounds_check_timer += dtime;
713 if(m_removed_sounds_check_timer >= 2.32) {
714 m_removed_sounds_check_timer = 0;
715 // Find removed sounds and clear references to them
716 std::vector<s32> removed_server_ids;
717 for(UNORDERED_MAP<s32, int>::iterator i = m_sounds_server_to_client.begin();
718 i != m_sounds_server_to_client.end();) {
719 s32 server_id = i->first;
720 int client_id = i->second;
722 if(!m_sound->soundExists(client_id)) {
723 m_sounds_server_to_client.erase(server_id);
724 m_sounds_client_to_server.erase(client_id);
725 m_sounds_to_objects.erase(client_id);
726 removed_server_ids.push_back(server_id);
731 if(!removed_server_ids.empty()) {
732 sendRemovedSounds(removed_server_ids);
736 m_mod_storage_save_timer -= dtime;
737 if (m_mod_storage_save_timer <= 0.0f) {
738 verbosestream << "Saving registered mod storages." << std::endl;
739 m_mod_storage_save_timer = g_settings->getFloat("server_map_save_interval");
740 for (UNORDERED_MAP<std::string, ModMetadata *>::const_iterator
741 it = m_mod_storages.begin(); it != m_mod_storages.end(); ++it) {
742 if (it->second->isModified()) {
743 it->second->save(getModStoragePath());
749 if (m_localdb && m_localdb_save_interval.step(dtime,
750 m_cache_save_interval)) {
751 m_localdb->endSave();
752 m_localdb->beginSave();
756 bool Client::loadMedia(const std::string &data, const std::string &filename)
758 // Silly irrlicht's const-incorrectness
759 Buffer<char> data_rw(data.c_str(), data.size());
763 const char *image_ext[] = {
764 ".png", ".jpg", ".bmp", ".tga",
765 ".pcx", ".ppm", ".psd", ".wal", ".rgb",
768 name = removeStringEnd(filename, image_ext);
771 verbosestream<<"Client: Attempting to load image "
772 <<"file \""<<filename<<"\""<<std::endl;
774 io::IFileSystem *irrfs = m_device->getFileSystem();
775 video::IVideoDriver *vdrv = m_device->getVideoDriver();
777 // Create an irrlicht memory file
778 io::IReadFile *rfile = irrfs->createMemoryReadFile(
779 *data_rw, data_rw.getSize(), "_tempreadfile");
781 FATAL_ERROR_IF(!rfile, "Could not create irrlicht memory file.");
784 video::IImage *img = vdrv->createImageFromFile(rfile);
786 errorstream<<"Client: Cannot create image from data of "
787 <<"file \""<<filename<<"\""<<std::endl;
792 m_tsrc->insertSourceImage(filename, img);
799 const char *sound_ext[] = {
800 ".0.ogg", ".1.ogg", ".2.ogg", ".3.ogg", ".4.ogg",
801 ".5.ogg", ".6.ogg", ".7.ogg", ".8.ogg", ".9.ogg",
804 name = removeStringEnd(filename, sound_ext);
807 verbosestream<<"Client: Attempting to load sound "
808 <<"file \""<<filename<<"\""<<std::endl;
809 m_sound->loadSoundData(name, data);
813 const char *model_ext[] = {
814 ".x", ".b3d", ".md2", ".obj",
817 name = removeStringEnd(filename, model_ext);
820 verbosestream<<"Client: Storing model into memory: "
821 <<"\""<<filename<<"\""<<std::endl;
822 if(m_mesh_data.count(filename))
823 errorstream<<"Multiple models with name \""<<filename.c_str()
824 <<"\" found; replacing previous model"<<std::endl;
825 m_mesh_data[filename] = data;
829 errorstream<<"Client: Don't know how to load file \""
830 <<filename<<"\""<<std::endl;
834 // Virtual methods from con::PeerHandler
835 void Client::peerAdded(con::Peer *peer)
837 infostream << "Client::peerAdded(): peer->id="
838 << peer->id << std::endl;
840 void Client::deletingPeer(con::Peer *peer, bool timeout)
842 infostream << "Client::deletingPeer(): "
843 "Server Peer is getting deleted "
844 << "(timeout=" << timeout << ")" << std::endl;
847 m_access_denied = true;
848 m_access_denied_reason = gettext("Connection timed out.");
854 u16 number of files requested
860 void Client::request_media(const std::vector<std::string> &file_requests)
862 std::ostringstream os(std::ios_base::binary);
863 writeU16(os, TOSERVER_REQUEST_MEDIA);
864 size_t file_requests_size = file_requests.size();
866 FATAL_ERROR_IF(file_requests_size > 0xFFFF, "Unsupported number of file requests");
868 // Packet dynamicly resized
869 NetworkPacket pkt(TOSERVER_REQUEST_MEDIA, 2 + 0);
871 pkt << (u16) (file_requests_size & 0xFFFF);
873 for(std::vector<std::string>::const_iterator i = file_requests.begin();
874 i != file_requests.end(); ++i) {
880 infostream << "Client: Sending media request list to server ("
881 << file_requests.size() << " files. packet size)" << std::endl;
884 void Client::received_media()
886 NetworkPacket pkt(TOSERVER_RECEIVED_MEDIA, 0);
888 infostream << "Client: Notifying server that we received all media"
892 void Client::initLocalMapSaving(const Address &address,
893 const std::string &hostname,
894 bool is_local_server)
896 if (!g_settings->getBool("enable_local_map_saving") || is_local_server) {
900 const std::string world_path = porting::path_user
901 + DIR_DELIM + "worlds"
902 + DIR_DELIM + "server_"
903 + hostname + "_" + std::to_string(address.getPort());
905 fs::CreateAllDirs(world_path);
907 m_localdb = new Database_SQLite3(world_path);
908 m_localdb->beginSave();
909 actionstream << "Local map saving started, map will be saved at '" << world_path << "'" << std::endl;
912 void Client::ReceiveAll()
914 DSTACK(FUNCTION_NAME);
915 u32 start_ms = porting::getTimeMs();
918 // Limit time even if there would be huge amounts of data to
920 if(porting::getTimeMs() > start_ms + 100)
925 g_profiler->graphAdd("client_received_packets", 1);
927 catch(con::NoIncomingDataException &e) {
930 catch(con::InvalidIncomingDataException &e) {
931 infostream<<"Client::ReceiveAll(): "
932 "InvalidIncomingDataException: what()="
933 <<e.what()<<std::endl;
938 void Client::Receive()
940 DSTACK(FUNCTION_NAME);
946 inline void Client::handleCommand(NetworkPacket* pkt)
948 const ToClientCommandHandler& opHandle = toClientCommandTable[pkt->getCommand()];
949 (this->*opHandle.handler)(pkt);
953 sender_peer_id given to this shall be quaranteed to be a valid peer
955 void Client::ProcessData(NetworkPacket *pkt)
957 DSTACK(FUNCTION_NAME);
959 ToClientCommand command = (ToClientCommand) pkt->getCommand();
960 u32 sender_peer_id = pkt->getPeerId();
962 //infostream<<"Client: received command="<<command<<std::endl;
963 m_packetcounter.add((u16)command);
966 If this check is removed, be sure to change the queue
967 system to know the ids
969 if(sender_peer_id != PEER_ID_SERVER) {
970 infostream << "Client::ProcessData(): Discarding data not "
971 "coming from server: peer_id=" << sender_peer_id
976 // Command must be handled into ToClientCommandHandler
977 if (command >= TOCLIENT_NUM_MSG_TYPES) {
978 infostream << "Client: Ignoring unknown command "
979 << command << std::endl;
984 * Those packets are handled before m_server_ser_ver is set, it's normal
985 * But we must use the new ToClientConnectionState in the future,
988 if(toClientCommandTable[command].state == TOCLIENT_STATE_NOT_CONNECTED) {
993 if(m_server_ser_ver == SER_FMT_VER_INVALID) {
994 infostream << "Client: Server serialization"
995 " format invalid or not initialized."
996 " Skipping incoming command=" << command << std::endl;
1001 Handle runtime commands
1007 void Client::Send(NetworkPacket* pkt)
1009 m_con.Send(PEER_ID_SERVER,
1010 serverCommandFactoryTable[pkt->getCommand()].channel,
1012 serverCommandFactoryTable[pkt->getCommand()].reliable);
1015 // Will fill up 12 + 12 + 4 + 4 + 4 bytes
1016 void writePlayerPos(LocalPlayer *myplayer, ClientMap *clientMap, NetworkPacket *pkt)
1018 v3f pf = myplayer->getPosition() * 100;
1019 v3f sf = myplayer->getSpeed() * 100;
1020 s32 pitch = myplayer->getPitch() * 100;
1021 s32 yaw = myplayer->getYaw() * 100;
1022 u32 keyPressed = myplayer->keyPressed;
1023 // scaled by 80, so that pi can fit into a u8
1024 u8 fov = clientMap->getCameraFov() * 80;
1025 u8 wanted_range = MYMIN(255,
1026 std::ceil(clientMap->getControl().wanted_range / MAP_BLOCKSIZE));
1028 v3s32 position(pf.X, pf.Y, pf.Z);
1029 v3s32 speed(sf.X, sf.Y, sf.Z);
1033 [0] v3s32 position*100
1034 [12] v3s32 speed*100
1035 [12+12] s32 pitch*100
1036 [12+12+4] s32 yaw*100
1037 [12+12+4+4] u32 keyPressed
1038 [12+12+4+4+4] u8 fov*80
1039 [12+12+4+4+4+1] u8 ceil(wanted_range / MAP_BLOCKSIZE)
1041 *pkt << position << speed << pitch << yaw << keyPressed;
1042 *pkt << fov << wanted_range;
1045 void Client::interact(u8 action, const PointedThing& pointed)
1047 if(m_state != LC_Ready) {
1048 errorstream << "Client::interact() "
1049 "Canceled (not connected)"
1054 LocalPlayer *myplayer = m_env.getLocalPlayer();
1055 if (myplayer == NULL)
1062 [5] u32 length of the next item (plen)
1063 [9] serialized PointedThing
1064 [9 + plen] player position information
1066 0: start digging (from undersurface) or use
1067 1: stop digging (all parameters ignored)
1068 2: digging completed
1069 3: place block or item (to abovesurface)
1071 5: perform secondary action of item
1074 NetworkPacket pkt(TOSERVER_INTERACT, 1 + 2 + 0);
1077 pkt << (u16)getPlayerItem();
1079 std::ostringstream tmp_os(std::ios::binary);
1080 pointed.serialize(tmp_os);
1082 pkt.putLongString(tmp_os.str());
1084 writePlayerPos(myplayer, &m_env.getClientMap(), &pkt);
1089 void Client::deleteAuthData()
1094 switch (m_chosen_auth_mech) {
1095 case AUTH_MECHANISM_FIRST_SRP:
1097 case AUTH_MECHANISM_SRP:
1098 case AUTH_MECHANISM_LEGACY_PASSWORD:
1099 srp_user_delete((SRPUser *) m_auth_data);
1102 case AUTH_MECHANISM_NONE:
1105 m_chosen_auth_mech = AUTH_MECHANISM_NONE;
1109 AuthMechanism Client::choseAuthMech(const u32 mechs)
1111 if (mechs & AUTH_MECHANISM_SRP)
1112 return AUTH_MECHANISM_SRP;
1114 if (mechs & AUTH_MECHANISM_FIRST_SRP)
1115 return AUTH_MECHANISM_FIRST_SRP;
1117 if (mechs & AUTH_MECHANISM_LEGACY_PASSWORD)
1118 return AUTH_MECHANISM_LEGACY_PASSWORD;
1120 return AUTH_MECHANISM_NONE;
1123 void Client::sendLegacyInit(const char* playerName, const char* playerPassword)
1125 NetworkPacket pkt(TOSERVER_INIT_LEGACY,
1126 1 + PLAYERNAME_SIZE + PASSWORD_SIZE + 2 + 2);
1128 u16 proto_version_min = g_settings->getFlag("send_pre_v25_init") ?
1129 CLIENT_PROTOCOL_VERSION_MIN_LEGACY : CLIENT_PROTOCOL_VERSION_MIN;
1131 pkt << (u8) SER_FMT_VER_HIGHEST_READ;
1132 pkt.putRawString(playerName,PLAYERNAME_SIZE);
1133 pkt.putRawString(playerPassword, PASSWORD_SIZE);
1134 pkt << (u16) proto_version_min << (u16) CLIENT_PROTOCOL_VERSION_MAX;
1139 void Client::sendInit(const std::string &playerName)
1141 NetworkPacket pkt(TOSERVER_INIT, 1 + 2 + 2 + (1 + playerName.size()));
1143 // we don't support network compression yet
1144 u16 supp_comp_modes = NETPROTO_COMPRESSION_NONE;
1146 u16 proto_version_min = g_settings->getFlag("send_pre_v25_init") ?
1147 CLIENT_PROTOCOL_VERSION_MIN_LEGACY : CLIENT_PROTOCOL_VERSION_MIN;
1149 pkt << (u8) SER_FMT_VER_HIGHEST_READ << (u16) supp_comp_modes;
1150 pkt << (u16) proto_version_min << (u16) CLIENT_PROTOCOL_VERSION_MAX;
1156 void Client::startAuth(AuthMechanism chosen_auth_mechanism)
1158 m_chosen_auth_mech = chosen_auth_mechanism;
1160 switch (chosen_auth_mechanism) {
1161 case AUTH_MECHANISM_FIRST_SRP: {
1162 // send srp verifier to server
1163 std::string verifier;
1165 generate_srp_verifier_and_salt(getPlayerName(), m_password,
1168 NetworkPacket resp_pkt(TOSERVER_FIRST_SRP, 0);
1169 resp_pkt << salt << verifier << (u8)((m_password == "") ? 1 : 0);
1174 case AUTH_MECHANISM_SRP:
1175 case AUTH_MECHANISM_LEGACY_PASSWORD: {
1178 if (chosen_auth_mechanism == AUTH_MECHANISM_LEGACY_PASSWORD) {
1179 m_password = translate_password(getPlayerName(), m_password);
1183 std::string playername_u = lowercase(getPlayerName());
1184 m_auth_data = srp_user_new(SRP_SHA256, SRP_NG_2048,
1185 getPlayerName().c_str(), playername_u.c_str(),
1186 (const unsigned char *) m_password.c_str(),
1187 m_password.length(), NULL, NULL);
1190 SRP_Result res = srp_user_start_authentication(
1191 (struct SRPUser *) m_auth_data, NULL, NULL, 0,
1192 (unsigned char **) &bytes_A, &len_A);
1193 FATAL_ERROR_IF(res != SRP_OK, "Creating local SRP user failed.");
1195 NetworkPacket resp_pkt(TOSERVER_SRP_BYTES_A, 0);
1196 resp_pkt << std::string(bytes_A, len_A) << based_on;
1200 case AUTH_MECHANISM_NONE:
1201 break; // not handled in this method
1205 void Client::sendDeletedBlocks(std::vector<v3s16> &blocks)
1207 NetworkPacket pkt(TOSERVER_DELETEDBLOCKS, 1 + sizeof(v3s16) * blocks.size());
1209 pkt << (u8) blocks.size();
1212 for(std::vector<v3s16>::iterator
1214 j != blocks.end(); ++j) {
1222 void Client::sendGotBlocks(v3s16 block)
1224 NetworkPacket pkt(TOSERVER_GOTBLOCKS, 1 + 6);
1225 pkt << (u8) 1 << block;
1229 void Client::sendRemovedSounds(std::vector<s32> &soundList)
1231 size_t server_ids = soundList.size();
1232 assert(server_ids <= 0xFFFF);
1234 NetworkPacket pkt(TOSERVER_REMOVED_SOUNDS, 2 + server_ids * 4);
1236 pkt << (u16) (server_ids & 0xFFFF);
1238 for(std::vector<s32>::iterator i = soundList.begin();
1239 i != soundList.end(); ++i)
1245 void Client::sendNodemetaFields(v3s16 p, const std::string &formname,
1246 const StringMap &fields)
1248 size_t fields_size = fields.size();
1250 FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of nodemeta fields");
1252 NetworkPacket pkt(TOSERVER_NODEMETA_FIELDS, 0);
1254 pkt << p << formname << (u16) (fields_size & 0xFFFF);
1256 StringMap::const_iterator it;
1257 for (it = fields.begin(); it != fields.end(); ++it) {
1258 const std::string &name = it->first;
1259 const std::string &value = it->second;
1261 pkt.putLongString(value);
1267 void Client::sendInventoryFields(const std::string &formname,
1268 const StringMap &fields)
1270 size_t fields_size = fields.size();
1271 FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of inventory fields");
1273 NetworkPacket pkt(TOSERVER_INVENTORY_FIELDS, 0);
1274 pkt << formname << (u16) (fields_size & 0xFFFF);
1276 StringMap::const_iterator it;
1277 for (it = fields.begin(); it != fields.end(); ++it) {
1278 const std::string &name = it->first;
1279 const std::string &value = it->second;
1281 pkt.putLongString(value);
1287 void Client::sendInventoryAction(InventoryAction *a)
1289 std::ostringstream os(std::ios_base::binary);
1294 std::string s = os.str();
1296 NetworkPacket pkt(TOSERVER_INVENTORY_ACTION, s.size());
1297 pkt.putRawString(s.c_str(),s.size());
1302 void Client::sendChatMessage(const std::wstring &message)
1304 NetworkPacket pkt(TOSERVER_CHAT_MESSAGE, 2 + message.size() * sizeof(u16));
1311 void Client::sendChangePassword(const std::string &oldpassword,
1312 const std::string &newpassword)
1314 LocalPlayer *player = m_env.getLocalPlayer();
1318 std::string playername = player->getName();
1319 if (m_proto_ver >= 25) {
1320 // get into sudo mode and then send new password to server
1321 m_password = oldpassword;
1322 m_new_password = newpassword;
1323 startAuth(choseAuthMech(m_sudo_auth_methods));
1325 std::string oldpwd = translate_password(playername, oldpassword);
1326 std::string newpwd = translate_password(playername, newpassword);
1328 NetworkPacket pkt(TOSERVER_PASSWORD_LEGACY, 2 * PASSWORD_SIZE);
1330 for (u8 i = 0; i < PASSWORD_SIZE; i++) {
1331 pkt << (u8) (i < oldpwd.length() ? oldpwd[i] : 0);
1334 for (u8 i = 0; i < PASSWORD_SIZE; i++) {
1335 pkt << (u8) (i < newpwd.length() ? newpwd[i] : 0);
1342 void Client::sendDamage(u8 damage)
1344 DSTACK(FUNCTION_NAME);
1346 NetworkPacket pkt(TOSERVER_DAMAGE, sizeof(u8));
1351 void Client::sendBreath(u16 breath)
1353 DSTACK(FUNCTION_NAME);
1355 // Protocol v29 make this obsolete
1356 if (m_proto_ver >= 29)
1359 NetworkPacket pkt(TOSERVER_BREATH, sizeof(u16));
1364 void Client::sendRespawn()
1366 DSTACK(FUNCTION_NAME);
1368 NetworkPacket pkt(TOSERVER_RESPAWN, 0);
1372 void Client::sendReady()
1374 DSTACK(FUNCTION_NAME);
1376 NetworkPacket pkt(TOSERVER_CLIENT_READY,
1377 1 + 1 + 1 + 1 + 2 + sizeof(char) * strlen(g_version_hash));
1379 pkt << (u8) VERSION_MAJOR << (u8) VERSION_MINOR << (u8) VERSION_PATCH
1380 << (u8) 0 << (u16) strlen(g_version_hash);
1382 pkt.putRawString(g_version_hash, (u16) strlen(g_version_hash));
1386 void Client::sendPlayerPos()
1388 LocalPlayer *myplayer = m_env.getLocalPlayer();
1389 if(myplayer == NULL)
1392 ClientMap &map = m_env.getClientMap();
1394 u8 camera_fov = map.getCameraFov();
1395 u8 wanted_range = map.getControl().wanted_range;
1397 // Save bandwidth by only updating position when something changed
1398 if(myplayer->last_position == myplayer->getPosition() &&
1399 myplayer->last_speed == myplayer->getSpeed() &&
1400 myplayer->last_pitch == myplayer->getPitch() &&
1401 myplayer->last_yaw == myplayer->getYaw() &&
1402 myplayer->last_keyPressed == myplayer->keyPressed &&
1403 myplayer->last_camera_fov == camera_fov &&
1404 myplayer->last_wanted_range == wanted_range)
1407 myplayer->last_position = myplayer->getPosition();
1408 myplayer->last_speed = myplayer->getSpeed();
1409 myplayer->last_pitch = myplayer->getPitch();
1410 myplayer->last_yaw = myplayer->getYaw();
1411 myplayer->last_keyPressed = myplayer->keyPressed;
1412 myplayer->last_camera_fov = camera_fov;
1413 myplayer->last_wanted_range = wanted_range;
1415 //infostream << "Sending Player Position information" << std::endl;
1419 //MutexAutoLock lock(m_con_mutex); //bulk comment-out
1420 our_peer_id = m_con.GetPeerID();
1423 // Set peer id if not set already
1424 if(myplayer->peer_id == PEER_ID_INEXISTENT)
1425 myplayer->peer_id = our_peer_id;
1427 assert(myplayer->peer_id == our_peer_id);
1429 NetworkPacket pkt(TOSERVER_PLAYERPOS, 12 + 12 + 4 + 4 + 4 + 1 + 1);
1431 writePlayerPos(myplayer, &map, &pkt);
1436 void Client::sendPlayerItem(u16 item)
1438 LocalPlayer *myplayer = m_env.getLocalPlayer();
1439 if(myplayer == NULL)
1442 u16 our_peer_id = m_con.GetPeerID();
1444 // Set peer id if not set already
1445 if(myplayer->peer_id == PEER_ID_INEXISTENT)
1446 myplayer->peer_id = our_peer_id;
1447 assert(myplayer->peer_id == our_peer_id);
1449 NetworkPacket pkt(TOSERVER_PLAYERITEM, 2);
1456 void Client::removeNode(v3s16 p)
1458 std::map<v3s16, MapBlock*> modified_blocks;
1461 m_env.getMap().removeNodeAndUpdate(p, modified_blocks);
1463 catch(InvalidPositionException &e) {
1466 for(std::map<v3s16, MapBlock *>::iterator
1467 i = modified_blocks.begin();
1468 i != modified_blocks.end(); ++i) {
1469 addUpdateMeshTaskWithEdge(i->first, false, true);
1473 MapNode Client::getNode(v3s16 p, bool *is_valid_position)
1475 return m_env.getMap().getNodeNoEx(p, is_valid_position);
1478 void Client::addNode(v3s16 p, MapNode n, bool remove_metadata)
1480 //TimeTaker timer1("Client::addNode()");
1482 std::map<v3s16, MapBlock*> modified_blocks;
1485 //TimeTaker timer3("Client::addNode(): addNodeAndUpdate");
1486 m_env.getMap().addNodeAndUpdate(p, n, modified_blocks, remove_metadata);
1488 catch(InvalidPositionException &e) {
1491 for(std::map<v3s16, MapBlock *>::iterator
1492 i = modified_blocks.begin();
1493 i != modified_blocks.end(); ++i) {
1494 addUpdateMeshTaskWithEdge(i->first, false, true);
1498 void Client::setPlayerControl(PlayerControl &control)
1500 LocalPlayer *player = m_env.getLocalPlayer();
1501 assert(player != NULL);
1502 player->control = control;
1505 void Client::selectPlayerItem(u16 item)
1507 m_playeritem = item;
1508 m_inventory_updated = true;
1509 sendPlayerItem(item);
1512 // Returns true if the inventory of the local player has been
1513 // updated from the server. If it is true, it is set to false.
1514 bool Client::getLocalInventoryUpdated()
1516 bool updated = m_inventory_updated;
1517 m_inventory_updated = false;
1521 // Copies the inventory of the local player to parameter
1522 void Client::getLocalInventory(Inventory &dst)
1524 LocalPlayer *player = m_env.getLocalPlayer();
1525 assert(player != NULL);
1526 dst = player->inventory;
1529 Inventory* Client::getInventory(const InventoryLocation &loc)
1532 case InventoryLocation::UNDEFINED:
1535 case InventoryLocation::CURRENT_PLAYER:
1537 LocalPlayer *player = m_env.getLocalPlayer();
1538 assert(player != NULL);
1539 return &player->inventory;
1542 case InventoryLocation::PLAYER:
1544 // Check if we are working with local player inventory
1545 LocalPlayer *player = m_env.getLocalPlayer();
1546 if (!player || strcmp(player->getName(), loc.name.c_str()) != 0)
1548 return &player->inventory;
1551 case InventoryLocation::NODEMETA:
1553 NodeMetadata *meta = m_env.getMap().getNodeMetadata(loc.p);
1556 return meta->getInventory();
1559 case InventoryLocation::DETACHED:
1561 if (m_detached_inventories.count(loc.name) == 0)
1563 return m_detached_inventories[loc.name];
1567 FATAL_ERROR("Invalid inventory location type.");
1573 void Client::inventoryAction(InventoryAction *a)
1576 Send it to the server
1578 sendInventoryAction(a);
1581 Predict some local inventory changes
1583 a->clientApply(this, this);
1589 float Client::getAnimationTime()
1591 return m_animation_time;
1594 int Client::getCrackLevel()
1596 return m_crack_level;
1599 void Client::setCrack(int level, v3s16 pos)
1601 int old_crack_level = m_crack_level;
1602 v3s16 old_crack_pos = m_crack_pos;
1604 m_crack_level = level;
1607 if(old_crack_level >= 0 && (level < 0 || pos != old_crack_pos))
1610 addUpdateMeshTaskForNode(old_crack_pos, false, true);
1612 if(level >= 0 && (old_crack_level < 0 || pos != old_crack_pos))
1615 addUpdateMeshTaskForNode(pos, false, true);
1621 LocalPlayer *player = m_env.getLocalPlayer();
1622 assert(player != NULL);
1626 bool Client::getChatMessage(std::wstring &message)
1628 if(m_chat_queue.size() == 0)
1630 message = m_chat_queue.front();
1635 void Client::typeChatMessage(const std::wstring &message)
1637 // Discard empty line
1641 // If message was ate by script API, don't send it to server
1642 if (m_script->on_sending_message(wide_to_utf8(message))) {
1647 sendChatMessage(message);
1650 if (message[0] != L'/')
1652 // compatibility code
1653 if (m_proto_ver < 29) {
1654 LocalPlayer *player = m_env.getLocalPlayer();
1655 assert(player != NULL);
1656 std::wstring name = narrow_to_wide(player->getName());
1657 pushToChatQueue((std::wstring)L"<" + name + L"> " + message);
1662 void Client::addUpdateMeshTask(v3s16 p, bool ack_to_server, bool urgent)
1664 MapBlock *b = m_env.getMap().getBlockNoCreateNoEx(p);
1669 Create a task to update the mesh of the block
1672 MeshMakeData *data = new MeshMakeData(this, m_cache_enable_shaders,
1673 m_cache_use_tangent_vertices);
1676 //TimeTaker timer("data fill");
1678 // Debug: 1-6ms, avg=2ms
1680 data->setCrack(m_crack_level, m_crack_pos);
1681 data->setSmoothLighting(m_cache_smooth_lighting);
1684 // Add task to queue
1685 m_mesh_update_thread.enqueueUpdate(p, data, ack_to_server, urgent);
1688 void Client::addUpdateMeshTaskWithEdge(v3s16 blockpos, bool ack_to_server, bool urgent)
1691 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1693 catch(InvalidPositionException &e){}
1696 for (int i=0;i<6;i++)
1699 v3s16 p = blockpos + g_6dirs[i];
1700 addUpdateMeshTask(p, false, urgent);
1702 catch(InvalidPositionException &e){}
1706 void Client::addUpdateMeshTaskForNode(v3s16 nodepos, bool ack_to_server, bool urgent)
1710 infostream<<"Client::addUpdateMeshTaskForNode(): "
1711 <<"("<<p.X<<","<<p.Y<<","<<p.Z<<")"
1715 v3s16 blockpos = getNodeBlockPos(nodepos);
1716 v3s16 blockpos_relative = blockpos * MAP_BLOCKSIZE;
1719 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1721 catch(InvalidPositionException &e) {}
1724 if(nodepos.X == blockpos_relative.X){
1726 v3s16 p = blockpos + v3s16(-1,0,0);
1727 addUpdateMeshTask(p, false, urgent);
1729 catch(InvalidPositionException &e){}
1732 if(nodepos.Y == blockpos_relative.Y){
1734 v3s16 p = blockpos + v3s16(0,-1,0);
1735 addUpdateMeshTask(p, false, urgent);
1737 catch(InvalidPositionException &e){}
1740 if(nodepos.Z == blockpos_relative.Z){
1742 v3s16 p = blockpos + v3s16(0,0,-1);
1743 addUpdateMeshTask(p, false, urgent);
1745 catch(InvalidPositionException &e){}
1749 ClientEvent Client::getClientEvent()
1752 if (m_client_event_queue.empty()) {
1753 event.type = CE_NONE;
1756 event = m_client_event_queue.front();
1757 m_client_event_queue.pop();
1762 float Client::mediaReceiveProgress()
1764 if (m_media_downloader)
1765 return m_media_downloader->getProgress();
1767 return 1.0; // downloader only exists when not yet done
1770 typedef struct TextureUpdateArgs {
1771 IrrlichtDevice *device;
1772 gui::IGUIEnvironment *guienv;
1775 const wchar_t* text_base;
1776 } TextureUpdateArgs;
1778 void texture_update_progress(void *args, u32 progress, u32 max_progress)
1780 TextureUpdateArgs* targs = (TextureUpdateArgs*) args;
1781 u16 cur_percent = ceil(progress / (double) max_progress * 100.);
1783 // update the loading menu -- if neccessary
1784 bool do_draw = false;
1785 u32 time_ms = targs->last_time_ms;
1786 if (cur_percent != targs->last_percent) {
1787 targs->last_percent = cur_percent;
1788 time_ms = getTimeMs();
1789 // only draw when the user will notice something:
1790 do_draw = (time_ms - targs->last_time_ms > 100);
1794 targs->last_time_ms = time_ms;
1795 std::basic_stringstream<wchar_t> strm;
1796 strm << targs->text_base << " " << targs->last_percent << "%...";
1797 draw_load_screen(strm.str(), targs->device, targs->guienv, 0,
1798 72 + (u16) ((18. / 100.) * (double) targs->last_percent));
1802 void Client::afterContentReceived(IrrlichtDevice *device)
1804 infostream<<"Client::afterContentReceived() started"<<std::endl;
1805 assert(m_itemdef_received); // pre-condition
1806 assert(m_nodedef_received); // pre-condition
1807 assert(mediaReceived()); // pre-condition
1809 const wchar_t* text = wgettext("Loading textures...");
1811 // Clear cached pre-scaled 2D GUI images, as this cache
1812 // might have images with the same name but different
1813 // content from previous sessions.
1814 guiScalingCacheClear(device->getVideoDriver());
1816 // Rebuild inherited images and recreate textures
1817 infostream<<"- Rebuilding images and textures"<<std::endl;
1818 draw_load_screen(text,device, guienv, 0, 70);
1819 m_tsrc->rebuildImagesAndTextures();
1823 infostream<<"- Rebuilding shaders"<<std::endl;
1824 text = wgettext("Rebuilding shaders...");
1825 draw_load_screen(text, device, guienv, 0, 71);
1826 m_shsrc->rebuildShaders();
1829 // Update node aliases
1830 infostream<<"- Updating node aliases"<<std::endl;
1831 text = wgettext("Initializing nodes...");
1832 draw_load_screen(text, device, guienv, 0, 72);
1833 m_nodedef->updateAliases(m_itemdef);
1834 std::string texture_path = g_settings->get("texture_path");
1835 if (texture_path != "" && fs::IsDir(texture_path))
1836 m_nodedef->applyTextureOverrides(texture_path + DIR_DELIM + "override.txt");
1837 m_nodedef->setNodeRegistrationStatus(true);
1838 m_nodedef->runNodeResolveCallbacks();
1841 // Update node textures and assign shaders to each tile
1842 infostream<<"- Updating node textures"<<std::endl;
1843 TextureUpdateArgs tu_args;
1844 tu_args.device = device;
1845 tu_args.guienv = guienv;
1846 tu_args.last_time_ms = getTimeMs();
1847 tu_args.last_percent = 0;
1848 tu_args.text_base = wgettext("Initializing nodes");
1849 m_nodedef->updateTextures(this, texture_update_progress, &tu_args);
1850 delete[] tu_args.text_base;
1852 // Start mesh update thread after setting up content definitions
1853 infostream<<"- Starting mesh update thread"<<std::endl;
1854 m_mesh_update_thread.start();
1858 text = wgettext("Done!");
1859 draw_load_screen(text, device, guienv, 0, 100);
1860 infostream<<"Client::afterContentReceived() done"<<std::endl;
1864 float Client::getRTT()
1866 return m_con.getPeerStat(PEER_ID_SERVER,con::AVG_RTT);
1869 float Client::getCurRate()
1871 return ( m_con.getLocalStat(con::CUR_INC_RATE) +
1872 m_con.getLocalStat(con::CUR_DL_RATE));
1875 void Client::makeScreenshot(IrrlichtDevice *device)
1877 irr::video::IVideoDriver *driver = device->getVideoDriver();
1878 irr::video::IImage* const raw_image = driver->createScreenShot();
1883 time_t t = time(NULL);
1884 struct tm *tm = localtime(&t);
1886 char timetstamp_c[64];
1887 strftime(timetstamp_c, sizeof(timetstamp_c), "%Y%m%d_%H%M%S", tm);
1889 std::string filename_base = g_settings->get("screenshot_path")
1891 + std::string("screenshot_")
1892 + std::string(timetstamp_c);
1893 std::string filename_ext = "." + g_settings->get("screenshot_format");
1894 std::string filename;
1896 u32 quality = (u32)g_settings->getS32("screenshot_quality");
1897 quality = MYMIN(MYMAX(quality, 0), 100) / 100.0 * 255;
1899 // Try to find a unique filename
1900 unsigned serial = 0;
1902 while (serial < SCREENSHOT_MAX_SERIAL_TRIES) {
1903 filename = filename_base + (serial > 0 ? ("_" + itos(serial)) : "") + filename_ext;
1904 std::ifstream tmp(filename.c_str());
1906 break; // File did not apparently exist, we'll go with it
1910 if (serial == SCREENSHOT_MAX_SERIAL_TRIES) {
1911 infostream << "Could not find suitable filename for screenshot" << std::endl;
1913 irr::video::IImage* const image =
1914 driver->createImage(video::ECF_R8G8B8, raw_image->getDimension());
1917 raw_image->copyTo(image);
1919 std::ostringstream sstr;
1920 if (driver->writeImageToFile(image, filename.c_str(), quality)) {
1921 sstr << "Saved screenshot to '" << filename << "'";
1923 sstr << "Failed to save screenshot '" << filename << "'";
1925 pushToChatQueue(narrow_to_wide(sstr.str()));
1926 infostream << sstr.str() << std::endl;
1934 bool Client::shouldShowMinimap() const
1936 if (m_minimap_disabled_by_server) {
1940 return m_minimap_shown_by_mod;
1943 // IGameDef interface
1945 IItemDefManager* Client::getItemDefManager()
1949 INodeDefManager* Client::getNodeDefManager()
1953 ICraftDefManager* Client::getCraftDefManager()
1956 //return m_craftdef;
1958 ITextureSource* Client::getTextureSource()
1962 IShaderSource* Client::getShaderSource()
1966 scene::ISceneManager* Client::getSceneManager()
1968 return m_device->getSceneManager();
1970 u16 Client::allocateUnknownNodeId(const std::string &name)
1972 errorstream << "Client::allocateUnknownNodeId(): "
1973 << "Client cannot allocate node IDs" << std::endl;
1974 FATAL_ERROR("Client allocated unknown node");
1976 return CONTENT_IGNORE;
1978 ISoundManager* Client::getSoundManager()
1982 MtEventManager* Client::getEventManager()
1987 ParticleManager* Client::getParticleManager()
1989 return &m_particle_manager;
1992 scene::IAnimatedMesh* Client::getMesh(const std::string &filename)
1994 StringMap::const_iterator it = m_mesh_data.find(filename);
1995 if (it == m_mesh_data.end()) {
1996 errorstream << "Client::getMesh(): Mesh not found: \"" << filename
1997 << "\"" << std::endl;
2000 const std::string &data = it->second;
2001 scene::ISceneManager *smgr = m_device->getSceneManager();
2003 // Create the mesh, remove it from cache and return it
2004 // This allows unique vertex colors and other properties for each instance
2005 Buffer<char> data_rw(data.c_str(), data.size()); // Const-incorrect Irrlicht
2006 io::IFileSystem *irrfs = m_device->getFileSystem();
2007 io::IReadFile *rfile = irrfs->createMemoryReadFile(
2008 *data_rw, data_rw.getSize(), filename.c_str());
2009 FATAL_ERROR_IF(!rfile, "Could not create/open RAM file");
2011 scene::IAnimatedMesh *mesh = smgr->getMesh(rfile);
2013 // NOTE: By playing with Irrlicht refcounts, maybe we could cache a bunch
2014 // of uniquely named instances and re-use them
2016 smgr->getMeshCache()->removeMesh(mesh);
2020 bool Client::registerModStorage(ModMetadata *storage)
2022 if (m_mod_storages.find(storage->getModName()) != m_mod_storages.end()) {
2023 errorstream << "Unable to register same mod storage twice. Storage name: "
2024 << storage->getModName() << std::endl;
2028 m_mod_storages[storage->getModName()] = storage;
2032 void Client::unregisterModStorage(const std::string &name)
2034 UNORDERED_MAP<std::string, ModMetadata *>::const_iterator it = m_mod_storages.find(name);
2035 if (it != m_mod_storages.end()) {
2036 // Save unconditionaly on unregistration
2037 it->second->save(getModStoragePath());
2038 m_mod_storages.erase(name);
2042 std::string Client::getModStoragePath() const
2044 return porting::path_user + DIR_DELIM + "client" + DIR_DELIM + "mod_storage";