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"
51 extern gui::IGUIEnvironment* guienv;
57 QueuedMeshUpdate::QueuedMeshUpdate():
60 ack_block_to_server(false)
64 QueuedMeshUpdate::~QueuedMeshUpdate()
74 MeshUpdateQueue::MeshUpdateQueue()
78 MeshUpdateQueue::~MeshUpdateQueue()
80 MutexAutoLock lock(m_mutex);
82 for(std::vector<QueuedMeshUpdate*>::iterator
84 i != m_queue.end(); ++i)
86 QueuedMeshUpdate *q = *i;
92 peer_id=0 adds with nobody to send to
94 void MeshUpdateQueue::addBlock(v3s16 p, MeshMakeData *data, bool ack_block_to_server, bool urgent)
96 DSTACK(FUNCTION_NAME);
98 assert(data); // pre-condition
100 MutexAutoLock lock(m_mutex);
106 Find if block is already in queue.
107 If it is, update the data and quit.
109 for(std::vector<QueuedMeshUpdate*>::iterator
111 i != m_queue.end(); ++i)
113 QueuedMeshUpdate *q = *i;
119 if(ack_block_to_server)
120 q->ack_block_to_server = true;
128 QueuedMeshUpdate *q = new QueuedMeshUpdate;
131 q->ack_block_to_server = ack_block_to_server;
132 m_queue.push_back(q);
135 // Returned pointer must be deleted
136 // Returns NULL if queue is empty
137 QueuedMeshUpdate *MeshUpdateQueue::pop()
139 MutexAutoLock lock(m_mutex);
141 bool must_be_urgent = !m_urgents.empty();
142 for(std::vector<QueuedMeshUpdate*>::iterator
144 i != m_queue.end(); ++i)
146 QueuedMeshUpdate *q = *i;
147 if(must_be_urgent && m_urgents.count(q->p) == 0)
150 m_urgents.erase(q->p);
160 void MeshUpdateThread::enqueueUpdate(v3s16 p, MeshMakeData *data,
161 bool ack_block_to_server, bool urgent)
163 m_queue_in.addBlock(p, data, ack_block_to_server, urgent);
167 void MeshUpdateThread::doUpdate()
170 while ((q = m_queue_in.pop())) {
172 ScopeProfiler sp(g_profiler, "Client: Mesh making");
174 MapBlockMesh *mesh_new = new MapBlockMesh(q->data, m_camera_offset);
179 r.ack_block_to_server = q->ack_block_to_server;
181 m_queue_out.push_back(r);
192 IrrlichtDevice *device,
193 const char *playername,
194 std::string password,
195 MapDrawControl &control,
196 IWritableTextureSource *tsrc,
197 IWritableShaderSource *shsrc,
198 IWritableItemDefManager *itemdef,
199 IWritableNodeDefManager *nodedef,
200 ISoundManager *sound,
201 MtEventManager *event,
203 GameUIFlags *game_ui_flags
205 m_packetcounter_timer(0.0),
206 m_connection_reinit_timer(0.1),
207 m_avg_rtt_timer(0.0),
208 m_playerpos_send_timer(0.0),
209 m_ignore_damage_timer(0.0),
216 m_mesh_update_thread(),
218 new ClientMap(this, control,
219 device->getSceneManager()->getRootSceneNode(),
220 device->getSceneManager(), 666),
221 device->getSceneManager(),
224 m_particle_manager(&m_env),
225 m_con(PROTOCOL_ID, 512, CONNECTION_TIMEOUT, ipv6, this),
228 m_minimap_disabled_by_server(false),
229 m_server_ser_ver(SER_FMT_VER_INVALID),
232 m_inventory_updated(false),
233 m_inventory_from_server(NULL),
234 m_inventory_from_server_age(0.0),
239 m_password(password),
240 m_chosen_auth_mech(AUTH_MECHANISM_NONE),
242 m_access_denied(false),
243 m_access_denied_reconnect(false),
244 m_itemdef_received(false),
245 m_nodedef_received(false),
246 m_media_downloader(new ClientMediaDownloader()),
247 m_time_of_day_set(false),
248 m_last_time_of_day_f(-1),
249 m_time_of_day_update_timer(0),
250 m_recommended_send_interval(0.1),
251 m_removed_sounds_check_timer(0),
255 m_mod_storage_save_timer(10.0f),
256 m_game_ui_flags(game_ui_flags)
259 m_env.setLocalPlayer(new LocalPlayer(this, playername));
261 m_minimap = new Minimap(device, this);
262 m_cache_save_interval = g_settings->getU16("server_map_save_interval");
264 m_cache_smooth_lighting = g_settings->getBool("smooth_lighting");
265 m_cache_enable_shaders = g_settings->getBool("enable_shaders");
266 m_cache_use_tangent_vertices = m_cache_enable_shaders && (
267 g_settings->getBool("enable_bumpmapping") ||
268 g_settings->getBool("enable_parallax_occlusion"));
270 m_modding_enabled = g_settings->getBool("enable_client_modding");
271 m_script = new ClientScripting(this);
272 m_env.setScript(m_script);
273 m_script->setEnv(&m_env);
276 void Client::initMods()
278 m_script->loadMod(getBuiltinLuaPath() + DIR_DELIM "init.lua", BUILTIN_MOD_NAME);
280 // If modding is not enabled, don't load mods, just builtin
281 if (!m_modding_enabled) {
285 ClientModConfiguration modconf(getClientModsLuaPath());
286 std::vector<ModSpec> mods = modconf.getMods();
287 std::vector<ModSpec> unsatisfied_mods = modconf.getUnsatisfiedMods();
288 // complain about mods with unsatisfied dependencies
289 if (!modconf.isConsistent()) {
290 modconf.printUnsatisfiedModsError();
294 infostream << "Client Loading mods: ";
295 for (std::vector<ModSpec>::const_iterator i = mods.begin();
296 i != mods.end(); ++i) {
297 infostream << (*i).name << " ";
300 infostream << std::endl;
301 // Load and run "mod" scripts
302 for (std::vector<ModSpec>::const_iterator it = mods.begin();
303 it != mods.end(); ++it) {
304 const ModSpec &mod = *it;
305 if (!string_allowed(mod.name, MODNAME_ALLOWED_CHARS)) {
306 throw ModError("Error loading mod \"" + mod.name +
307 "\": Mod name does not follow naming conventions: "
308 "Only chararacters [a-z0-9_] are allowed.");
310 std::string script_path = mod.path + DIR_DELIM + "init.lua";
311 infostream << " [" << padStringRight(mod.name, 12) << "] [\""
312 << script_path << "\"]" << std::endl;
313 m_script->loadMod(script_path, mod.name);
317 const std::string &Client::getBuiltinLuaPath()
319 static const std::string builtin_dir = porting::path_share + DIR_DELIM + "builtin";
323 const std::string &Client::getClientModsLuaPath()
325 static const std::string clientmods_dir = porting::path_share + DIR_DELIM + "clientmods";
326 return clientmods_dir;
329 const std::vector<ModSpec>& Client::getMods() const
331 static std::vector<ModSpec> client_modspec_temp;
332 return client_modspec_temp;
335 const ModSpec* Client::getModSpec(const std::string &modname) const
342 // Don't disable this part when modding is disabled, it's used in builtin
343 m_script->on_shutdown();
344 //request all client managed threads to stop
345 m_mesh_update_thread.stop();
346 // Save local server map
348 infostream << "Local map saving ended." << std::endl;
349 m_localdb->endSave();
355 bool Client::isShutdown()
358 if (!m_mesh_update_thread.isRunning()) return true;
367 m_mesh_update_thread.stop();
368 m_mesh_update_thread.wait();
369 while (!m_mesh_update_thread.m_queue_out.empty()) {
370 MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_frontNoEx();
375 delete m_inventory_from_server;
377 // Delete detached inventories
378 for (UNORDERED_MAP<std::string, Inventory*>::iterator
379 i = m_detached_inventories.begin();
380 i != m_detached_inventories.end(); ++i) {
384 // cleanup 3d model meshes on client shutdown
385 while (m_device->getSceneManager()->getMeshCache()->getMeshCount() != 0) {
386 scene::IAnimatedMesh *mesh =
387 m_device->getSceneManager()->getMeshCache()->getMeshByIndex(0);
390 m_device->getSceneManager()->getMeshCache()->removeMesh(mesh);
396 void Client::connect(Address address,
397 const std::string &address_name,
398 bool is_local_server)
400 DSTACK(FUNCTION_NAME);
402 initLocalMapSaving(address, address_name, is_local_server);
404 m_con.SetTimeoutMs(0);
405 m_con.Connect(address);
408 void Client::step(float dtime)
410 DSTACK(FUNCTION_NAME);
416 if(m_ignore_damage_timer > dtime)
417 m_ignore_damage_timer -= dtime;
419 m_ignore_damage_timer = 0.0;
421 m_animation_time += dtime;
422 if(m_animation_time > 60.0)
423 m_animation_time -= 60.0;
425 m_time_of_day_update_timer += dtime;
433 float &counter = m_packetcounter_timer;
439 infostream << "Client packetcounter (" << m_packetcounter_timer
441 m_packetcounter.print(infostream);
442 m_packetcounter.clear();
446 // UGLY hack to fix 2 second startup delay caused by non existent
447 // server client startup synchronization in local server or singleplayer mode
448 static bool initial_step = true;
450 initial_step = false;
452 else if(m_state == LC_Created) {
453 float &counter = m_connection_reinit_timer;
458 LocalPlayer *myplayer = m_env.getLocalPlayer();
459 FATAL_ERROR_IF(myplayer == NULL, "Local player not found in environment.");
461 u16 proto_version_min = g_settings->getFlag("send_pre_v25_init") ?
462 CLIENT_PROTOCOL_VERSION_MIN_LEGACY : CLIENT_PROTOCOL_VERSION_MIN;
464 if (proto_version_min < 25) {
465 // Send TOSERVER_INIT_LEGACY
466 // [0] u16 TOSERVER_INIT_LEGACY
467 // [2] u8 SER_FMT_VER_HIGHEST_READ
468 // [3] u8[20] player_name
469 // [23] u8[28] password (new in some version)
470 // [51] u16 minimum supported network protocol version (added sometime)
471 // [53] u16 maximum supported network protocol version (added later than the previous one)
473 char pName[PLAYERNAME_SIZE];
474 char pPassword[PASSWORD_SIZE];
475 memset(pName, 0, PLAYERNAME_SIZE * sizeof(char));
476 memset(pPassword, 0, PASSWORD_SIZE * sizeof(char));
478 std::string hashed_password = translate_password(myplayer->getName(), m_password);
479 snprintf(pName, PLAYERNAME_SIZE, "%s", myplayer->getName());
480 snprintf(pPassword, PASSWORD_SIZE, "%s", hashed_password.c_str());
482 sendLegacyInit(pName, pPassword);
484 if (CLIENT_PROTOCOL_VERSION_MAX >= 25)
485 sendInit(myplayer->getName());
488 // Not connected, return
493 Do stuff if connected
497 Run Map's timers and unload unused data
499 const float map_timer_and_unload_dtime = 5.25;
500 if(m_map_timer_and_unload_interval.step(dtime, map_timer_and_unload_dtime)) {
501 ScopeProfiler sp(g_profiler, "Client: map timer and unload");
502 std::vector<v3s16> deleted_blocks;
503 m_env.getMap().timerUpdate(map_timer_and_unload_dtime,
504 g_settings->getFloat("client_unload_unused_data_timeout"),
505 g_settings->getS32("client_mapblock_limit"),
510 NOTE: This loop is intentionally iterated the way it is.
513 std::vector<v3s16>::iterator i = deleted_blocks.begin();
514 std::vector<v3s16> sendlist;
516 if(sendlist.size() == 255 || i == deleted_blocks.end()) {
527 sendDeletedBlocks(sendlist);
529 if(i == deleted_blocks.end())
535 sendlist.push_back(*i);
543 // Control local player (0ms)
544 LocalPlayer *player = m_env.getLocalPlayer();
545 assert(player != NULL);
546 player->applyControl(dtime);
555 ClientEnvEvent event = m_env.getClientEvent();
556 if(event.type == CEE_NONE) {
559 else if(event.type == CEE_PLAYER_DAMAGE) {
560 if(m_ignore_damage_timer <= 0) {
561 u8 damage = event.player_damage.amount;
563 if(event.player_damage.send_to_server)
566 // Add to ClientEvent queue
568 event.type = CE_PLAYER_DAMAGE;
569 event.player_damage.amount = damage;
570 m_client_event_queue.push(event);
573 // Protocol v29 or greater obsoleted this event
574 else if (event.type == CEE_PLAYER_BREATH && m_proto_ver < 29) {
575 u16 breath = event.player_breath.amount;
583 float &counter = m_avg_rtt_timer;
587 // connectedAndInitialized() is true, peer exists.
588 float avg_rtt = getRTT();
589 infostream << "Client: avg_rtt=" << avg_rtt << std::endl;
593 Send player position to server
596 float &counter = m_playerpos_send_timer;
598 if((m_state == LC_Ready) && (counter >= m_recommended_send_interval))
606 Replace updated meshes
609 int num_processed_meshes = 0;
610 while (!m_mesh_update_thread.m_queue_out.empty())
612 num_processed_meshes++;
614 MinimapMapblock *minimap_mapblock = NULL;
615 bool do_mapper_update = true;
617 MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_frontNoEx();
618 MapBlock *block = m_env.getMap().getBlockNoCreateNoEx(r.p);
620 // Delete the old mesh
621 if (block->mesh != NULL) {
627 minimap_mapblock = r.mesh->moveMinimapMapblock();
628 if (minimap_mapblock == NULL)
629 do_mapper_update = false;
632 if (r.mesh && r.mesh->getMesh()->getMeshBufferCount() == 0) {
635 // Replace with the new mesh
636 block->mesh = r.mesh;
642 if (do_mapper_update)
643 m_minimap->addBlock(r.p, minimap_mapblock);
645 if (r.ack_block_to_server) {
655 if (num_processed_meshes > 0)
656 g_profiler->graphAdd("num_processed_meshes", num_processed_meshes);
662 if (m_media_downloader && m_media_downloader->isStarted()) {
663 m_media_downloader->step(this);
664 if (m_media_downloader->isDone()) {
666 delete m_media_downloader;
667 m_media_downloader = NULL;
672 If the server didn't update the inventory in a while, revert
673 the local inventory (so the player notices the lag problem
674 and knows something is wrong).
676 if(m_inventory_from_server)
678 float interval = 10.0;
679 float count_before = floor(m_inventory_from_server_age / interval);
681 m_inventory_from_server_age += dtime;
683 float count_after = floor(m_inventory_from_server_age / interval);
685 if(count_after != count_before)
687 // Do this every <interval> seconds after TOCLIENT_INVENTORY
688 // Reset the locally changed inventory to the authoritative inventory
689 LocalPlayer *player = m_env.getLocalPlayer();
690 player->inventory = *m_inventory_from_server;
691 m_inventory_updated = true;
696 Update positions of sounds attached to objects
699 for(UNORDERED_MAP<int, u16>::iterator i = m_sounds_to_objects.begin();
700 i != m_sounds_to_objects.end(); ++i) {
701 int client_id = i->first;
702 u16 object_id = i->second;
703 ClientActiveObject *cao = m_env.getActiveObject(object_id);
706 v3f pos = cao->getPosition();
707 m_sound->updateSoundPosition(client_id, pos);
712 Handle removed remotely initiated sounds
714 m_removed_sounds_check_timer += dtime;
715 if(m_removed_sounds_check_timer >= 2.32) {
716 m_removed_sounds_check_timer = 0;
717 // Find removed sounds and clear references to them
718 std::vector<s32> removed_server_ids;
719 for(UNORDERED_MAP<s32, int>::iterator i = m_sounds_server_to_client.begin();
720 i != m_sounds_server_to_client.end();) {
721 s32 server_id = i->first;
722 int client_id = i->second;
724 if(!m_sound->soundExists(client_id)) {
725 m_sounds_server_to_client.erase(server_id);
726 m_sounds_client_to_server.erase(client_id);
727 m_sounds_to_objects.erase(client_id);
728 removed_server_ids.push_back(server_id);
733 if(!removed_server_ids.empty()) {
734 sendRemovedSounds(removed_server_ids);
738 m_mod_storage_save_timer -= dtime;
739 if (m_mod_storage_save_timer <= 0.0f) {
740 verbosestream << "Saving registered mod storages." << std::endl;
741 m_mod_storage_save_timer = g_settings->getFloat("server_map_save_interval");
742 for (UNORDERED_MAP<std::string, ModMetadata *>::const_iterator
743 it = m_mod_storages.begin(); it != m_mod_storages.end(); ++it) {
744 if (it->second->isModified()) {
745 it->second->save(getModStoragePath());
751 if (m_localdb && m_localdb_save_interval.step(dtime,
752 m_cache_save_interval)) {
753 m_localdb->endSave();
754 m_localdb->beginSave();
758 bool Client::loadMedia(const std::string &data, const std::string &filename)
760 // Silly irrlicht's const-incorrectness
761 Buffer<char> data_rw(data.c_str(), data.size());
765 const char *image_ext[] = {
766 ".png", ".jpg", ".bmp", ".tga",
767 ".pcx", ".ppm", ".psd", ".wal", ".rgb",
770 name = removeStringEnd(filename, image_ext);
773 verbosestream<<"Client: Attempting to load image "
774 <<"file \""<<filename<<"\""<<std::endl;
776 io::IFileSystem *irrfs = m_device->getFileSystem();
777 video::IVideoDriver *vdrv = m_device->getVideoDriver();
779 // Create an irrlicht memory file
780 io::IReadFile *rfile = irrfs->createMemoryReadFile(
781 *data_rw, data_rw.getSize(), "_tempreadfile");
783 FATAL_ERROR_IF(!rfile, "Could not create irrlicht memory file.");
786 video::IImage *img = vdrv->createImageFromFile(rfile);
788 errorstream<<"Client: Cannot create image from data of "
789 <<"file \""<<filename<<"\""<<std::endl;
794 m_tsrc->insertSourceImage(filename, img);
801 const char *sound_ext[] = {
802 ".0.ogg", ".1.ogg", ".2.ogg", ".3.ogg", ".4.ogg",
803 ".5.ogg", ".6.ogg", ".7.ogg", ".8.ogg", ".9.ogg",
806 name = removeStringEnd(filename, sound_ext);
809 verbosestream<<"Client: Attempting to load sound "
810 <<"file \""<<filename<<"\""<<std::endl;
811 m_sound->loadSoundData(name, data);
815 const char *model_ext[] = {
816 ".x", ".b3d", ".md2", ".obj",
819 name = removeStringEnd(filename, model_ext);
822 verbosestream<<"Client: Storing model into memory: "
823 <<"\""<<filename<<"\""<<std::endl;
824 if(m_mesh_data.count(filename))
825 errorstream<<"Multiple models with name \""<<filename.c_str()
826 <<"\" found; replacing previous model"<<std::endl;
827 m_mesh_data[filename] = data;
831 errorstream<<"Client: Don't know how to load file \""
832 <<filename<<"\""<<std::endl;
836 // Virtual methods from con::PeerHandler
837 void Client::peerAdded(con::Peer *peer)
839 infostream << "Client::peerAdded(): peer->id="
840 << peer->id << std::endl;
842 void Client::deletingPeer(con::Peer *peer, bool timeout)
844 infostream << "Client::deletingPeer(): "
845 "Server Peer is getting deleted "
846 << "(timeout=" << timeout << ")" << std::endl;
849 m_access_denied = true;
850 m_access_denied_reason = gettext("Connection timed out.");
856 u16 number of files requested
862 void Client::request_media(const std::vector<std::string> &file_requests)
864 std::ostringstream os(std::ios_base::binary);
865 writeU16(os, TOSERVER_REQUEST_MEDIA);
866 size_t file_requests_size = file_requests.size();
868 FATAL_ERROR_IF(file_requests_size > 0xFFFF, "Unsupported number of file requests");
870 // Packet dynamicly resized
871 NetworkPacket pkt(TOSERVER_REQUEST_MEDIA, 2 + 0);
873 pkt << (u16) (file_requests_size & 0xFFFF);
875 for(std::vector<std::string>::const_iterator i = file_requests.begin();
876 i != file_requests.end(); ++i) {
882 infostream << "Client: Sending media request list to server ("
883 << file_requests.size() << " files. packet size)" << std::endl;
886 void Client::received_media()
888 NetworkPacket pkt(TOSERVER_RECEIVED_MEDIA, 0);
890 infostream << "Client: Notifying server that we received all media"
894 void Client::initLocalMapSaving(const Address &address,
895 const std::string &hostname,
896 bool is_local_server)
898 if (!g_settings->getBool("enable_local_map_saving") || is_local_server) {
902 const std::string world_path = porting::path_user
903 + DIR_DELIM + "worlds"
904 + DIR_DELIM + "server_"
905 + hostname + "_" + std::to_string(address.getPort());
907 fs::CreateAllDirs(world_path);
909 m_localdb = new Database_SQLite3(world_path);
910 m_localdb->beginSave();
911 actionstream << "Local map saving started, map will be saved at '" << world_path << "'" << std::endl;
914 void Client::ReceiveAll()
916 DSTACK(FUNCTION_NAME);
917 u32 start_ms = porting::getTimeMs();
920 // Limit time even if there would be huge amounts of data to
922 if(porting::getTimeMs() > start_ms + 100)
927 g_profiler->graphAdd("client_received_packets", 1);
929 catch(con::NoIncomingDataException &e) {
932 catch(con::InvalidIncomingDataException &e) {
933 infostream<<"Client::ReceiveAll(): "
934 "InvalidIncomingDataException: what()="
935 <<e.what()<<std::endl;
940 void Client::Receive()
942 DSTACK(FUNCTION_NAME);
948 inline void Client::handleCommand(NetworkPacket* pkt)
950 const ToClientCommandHandler& opHandle = toClientCommandTable[pkt->getCommand()];
951 (this->*opHandle.handler)(pkt);
955 sender_peer_id given to this shall be quaranteed to be a valid peer
957 void Client::ProcessData(NetworkPacket *pkt)
959 DSTACK(FUNCTION_NAME);
961 ToClientCommand command = (ToClientCommand) pkt->getCommand();
962 u32 sender_peer_id = pkt->getPeerId();
964 //infostream<<"Client: received command="<<command<<std::endl;
965 m_packetcounter.add((u16)command);
968 If this check is removed, be sure to change the queue
969 system to know the ids
971 if(sender_peer_id != PEER_ID_SERVER) {
972 infostream << "Client::ProcessData(): Discarding data not "
973 "coming from server: peer_id=" << sender_peer_id
978 // Command must be handled into ToClientCommandHandler
979 if (command >= TOCLIENT_NUM_MSG_TYPES) {
980 infostream << "Client: Ignoring unknown command "
981 << command << std::endl;
986 * Those packets are handled before m_server_ser_ver is set, it's normal
987 * But we must use the new ToClientConnectionState in the future,
990 if(toClientCommandTable[command].state == TOCLIENT_STATE_NOT_CONNECTED) {
995 if(m_server_ser_ver == SER_FMT_VER_INVALID) {
996 infostream << "Client: Server serialization"
997 " format invalid or not initialized."
998 " Skipping incoming command=" << command << std::endl;
1003 Handle runtime commands
1009 void Client::Send(NetworkPacket* pkt)
1011 m_con.Send(PEER_ID_SERVER,
1012 serverCommandFactoryTable[pkt->getCommand()].channel,
1014 serverCommandFactoryTable[pkt->getCommand()].reliable);
1017 // Will fill up 12 + 12 + 4 + 4 + 4 bytes
1018 void writePlayerPos(LocalPlayer *myplayer, ClientMap *clientMap, NetworkPacket *pkt)
1020 v3f pf = myplayer->getPosition() * 100;
1021 v3f sf = myplayer->getSpeed() * 100;
1022 s32 pitch = myplayer->getPitch() * 100;
1023 s32 yaw = myplayer->getYaw() * 100;
1024 u32 keyPressed = myplayer->keyPressed;
1025 // scaled by 80, so that pi can fit into a u8
1026 u8 fov = clientMap->getCameraFov() * 80;
1027 u8 wanted_range = MYMIN(255,
1028 std::ceil(clientMap->getControl().wanted_range / MAP_BLOCKSIZE));
1030 v3s32 position(pf.X, pf.Y, pf.Z);
1031 v3s32 speed(sf.X, sf.Y, sf.Z);
1035 [0] v3s32 position*100
1036 [12] v3s32 speed*100
1037 [12+12] s32 pitch*100
1038 [12+12+4] s32 yaw*100
1039 [12+12+4+4] u32 keyPressed
1040 [12+12+4+4+4] u8 fov*80
1041 [12+12+4+4+4+1] u8 ceil(wanted_range / MAP_BLOCKSIZE)
1043 *pkt << position << speed << pitch << yaw << keyPressed;
1044 *pkt << fov << wanted_range;
1047 void Client::interact(u8 action, const PointedThing& pointed)
1049 if(m_state != LC_Ready) {
1050 errorstream << "Client::interact() "
1051 "Canceled (not connected)"
1056 LocalPlayer *myplayer = m_env.getLocalPlayer();
1057 if (myplayer == NULL)
1064 [5] u32 length of the next item (plen)
1065 [9] serialized PointedThing
1066 [9 + plen] player position information
1068 0: start digging (from undersurface) or use
1069 1: stop digging (all parameters ignored)
1070 2: digging completed
1071 3: place block or item (to abovesurface)
1073 5: perform secondary action of item
1076 NetworkPacket pkt(TOSERVER_INTERACT, 1 + 2 + 0);
1079 pkt << (u16)getPlayerItem();
1081 std::ostringstream tmp_os(std::ios::binary);
1082 pointed.serialize(tmp_os);
1084 pkt.putLongString(tmp_os.str());
1086 writePlayerPos(myplayer, &m_env.getClientMap(), &pkt);
1091 void Client::deleteAuthData()
1096 switch (m_chosen_auth_mech) {
1097 case AUTH_MECHANISM_FIRST_SRP:
1099 case AUTH_MECHANISM_SRP:
1100 case AUTH_MECHANISM_LEGACY_PASSWORD:
1101 srp_user_delete((SRPUser *) m_auth_data);
1104 case AUTH_MECHANISM_NONE:
1107 m_chosen_auth_mech = AUTH_MECHANISM_NONE;
1111 AuthMechanism Client::choseAuthMech(const u32 mechs)
1113 if (mechs & AUTH_MECHANISM_SRP)
1114 return AUTH_MECHANISM_SRP;
1116 if (mechs & AUTH_MECHANISM_FIRST_SRP)
1117 return AUTH_MECHANISM_FIRST_SRP;
1119 if (mechs & AUTH_MECHANISM_LEGACY_PASSWORD)
1120 return AUTH_MECHANISM_LEGACY_PASSWORD;
1122 return AUTH_MECHANISM_NONE;
1125 void Client::sendLegacyInit(const char* playerName, const char* playerPassword)
1127 NetworkPacket pkt(TOSERVER_INIT_LEGACY,
1128 1 + PLAYERNAME_SIZE + PASSWORD_SIZE + 2 + 2);
1130 u16 proto_version_min = g_settings->getFlag("send_pre_v25_init") ?
1131 CLIENT_PROTOCOL_VERSION_MIN_LEGACY : CLIENT_PROTOCOL_VERSION_MIN;
1133 pkt << (u8) SER_FMT_VER_HIGHEST_READ;
1134 pkt.putRawString(playerName,PLAYERNAME_SIZE);
1135 pkt.putRawString(playerPassword, PASSWORD_SIZE);
1136 pkt << (u16) proto_version_min << (u16) CLIENT_PROTOCOL_VERSION_MAX;
1141 void Client::sendInit(const std::string &playerName)
1143 NetworkPacket pkt(TOSERVER_INIT, 1 + 2 + 2 + (1 + playerName.size()));
1145 // we don't support network compression yet
1146 u16 supp_comp_modes = NETPROTO_COMPRESSION_NONE;
1148 u16 proto_version_min = g_settings->getFlag("send_pre_v25_init") ?
1149 CLIENT_PROTOCOL_VERSION_MIN_LEGACY : CLIENT_PROTOCOL_VERSION_MIN;
1151 pkt << (u8) SER_FMT_VER_HIGHEST_READ << (u16) supp_comp_modes;
1152 pkt << (u16) proto_version_min << (u16) CLIENT_PROTOCOL_VERSION_MAX;
1158 void Client::startAuth(AuthMechanism chosen_auth_mechanism)
1160 m_chosen_auth_mech = chosen_auth_mechanism;
1162 switch (chosen_auth_mechanism) {
1163 case AUTH_MECHANISM_FIRST_SRP: {
1164 // send srp verifier to server
1165 std::string verifier;
1167 generate_srp_verifier_and_salt(getPlayerName(), m_password,
1170 NetworkPacket resp_pkt(TOSERVER_FIRST_SRP, 0);
1171 resp_pkt << salt << verifier << (u8)((m_password == "") ? 1 : 0);
1176 case AUTH_MECHANISM_SRP:
1177 case AUTH_MECHANISM_LEGACY_PASSWORD: {
1180 if (chosen_auth_mechanism == AUTH_MECHANISM_LEGACY_PASSWORD) {
1181 m_password = translate_password(getPlayerName(), m_password);
1185 std::string playername_u = lowercase(getPlayerName());
1186 m_auth_data = srp_user_new(SRP_SHA256, SRP_NG_2048,
1187 getPlayerName().c_str(), playername_u.c_str(),
1188 (const unsigned char *) m_password.c_str(),
1189 m_password.length(), NULL, NULL);
1192 SRP_Result res = srp_user_start_authentication(
1193 (struct SRPUser *) m_auth_data, NULL, NULL, 0,
1194 (unsigned char **) &bytes_A, &len_A);
1195 FATAL_ERROR_IF(res != SRP_OK, "Creating local SRP user failed.");
1197 NetworkPacket resp_pkt(TOSERVER_SRP_BYTES_A, 0);
1198 resp_pkt << std::string(bytes_A, len_A) << based_on;
1202 case AUTH_MECHANISM_NONE:
1203 break; // not handled in this method
1207 void Client::sendDeletedBlocks(std::vector<v3s16> &blocks)
1209 NetworkPacket pkt(TOSERVER_DELETEDBLOCKS, 1 + sizeof(v3s16) * blocks.size());
1211 pkt << (u8) blocks.size();
1214 for(std::vector<v3s16>::iterator
1216 j != blocks.end(); ++j) {
1224 void Client::sendGotBlocks(v3s16 block)
1226 NetworkPacket pkt(TOSERVER_GOTBLOCKS, 1 + 6);
1227 pkt << (u8) 1 << block;
1231 void Client::sendRemovedSounds(std::vector<s32> &soundList)
1233 size_t server_ids = soundList.size();
1234 assert(server_ids <= 0xFFFF);
1236 NetworkPacket pkt(TOSERVER_REMOVED_SOUNDS, 2 + server_ids * 4);
1238 pkt << (u16) (server_ids & 0xFFFF);
1240 for(std::vector<s32>::iterator i = soundList.begin();
1241 i != soundList.end(); ++i)
1247 void Client::sendNodemetaFields(v3s16 p, const std::string &formname,
1248 const StringMap &fields)
1250 size_t fields_size = fields.size();
1252 FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of nodemeta fields");
1254 NetworkPacket pkt(TOSERVER_NODEMETA_FIELDS, 0);
1256 pkt << p << formname << (u16) (fields_size & 0xFFFF);
1258 StringMap::const_iterator it;
1259 for (it = fields.begin(); it != fields.end(); ++it) {
1260 const std::string &name = it->first;
1261 const std::string &value = it->second;
1263 pkt.putLongString(value);
1269 void Client::sendInventoryFields(const std::string &formname,
1270 const StringMap &fields)
1272 size_t fields_size = fields.size();
1273 FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of inventory fields");
1275 NetworkPacket pkt(TOSERVER_INVENTORY_FIELDS, 0);
1276 pkt << formname << (u16) (fields_size & 0xFFFF);
1278 StringMap::const_iterator it;
1279 for (it = fields.begin(); it != fields.end(); ++it) {
1280 const std::string &name = it->first;
1281 const std::string &value = it->second;
1283 pkt.putLongString(value);
1289 void Client::sendInventoryAction(InventoryAction *a)
1291 std::ostringstream os(std::ios_base::binary);
1296 std::string s = os.str();
1298 NetworkPacket pkt(TOSERVER_INVENTORY_ACTION, s.size());
1299 pkt.putRawString(s.c_str(),s.size());
1304 void Client::sendChatMessage(const std::wstring &message)
1306 NetworkPacket pkt(TOSERVER_CHAT_MESSAGE, 2 + message.size() * sizeof(u16));
1313 void Client::sendChangePassword(const std::string &oldpassword,
1314 const std::string &newpassword)
1316 LocalPlayer *player = m_env.getLocalPlayer();
1320 std::string playername = player->getName();
1321 if (m_proto_ver >= 25) {
1322 // get into sudo mode and then send new password to server
1323 m_password = oldpassword;
1324 m_new_password = newpassword;
1325 startAuth(choseAuthMech(m_sudo_auth_methods));
1327 std::string oldpwd = translate_password(playername, oldpassword);
1328 std::string newpwd = translate_password(playername, newpassword);
1330 NetworkPacket pkt(TOSERVER_PASSWORD_LEGACY, 2 * PASSWORD_SIZE);
1332 for (u8 i = 0; i < PASSWORD_SIZE; i++) {
1333 pkt << (u8) (i < oldpwd.length() ? oldpwd[i] : 0);
1336 for (u8 i = 0; i < PASSWORD_SIZE; i++) {
1337 pkt << (u8) (i < newpwd.length() ? newpwd[i] : 0);
1344 void Client::sendDamage(u8 damage)
1346 DSTACK(FUNCTION_NAME);
1348 NetworkPacket pkt(TOSERVER_DAMAGE, sizeof(u8));
1353 void Client::sendBreath(u16 breath)
1355 DSTACK(FUNCTION_NAME);
1357 // Protocol v29 make this obsolete
1358 if (m_proto_ver >= 29)
1361 NetworkPacket pkt(TOSERVER_BREATH, sizeof(u16));
1366 void Client::sendRespawn()
1368 DSTACK(FUNCTION_NAME);
1370 NetworkPacket pkt(TOSERVER_RESPAWN, 0);
1374 void Client::sendReady()
1376 DSTACK(FUNCTION_NAME);
1378 NetworkPacket pkt(TOSERVER_CLIENT_READY,
1379 1 + 1 + 1 + 1 + 2 + sizeof(char) * strlen(g_version_hash));
1381 pkt << (u8) VERSION_MAJOR << (u8) VERSION_MINOR << (u8) VERSION_PATCH
1382 << (u8) 0 << (u16) strlen(g_version_hash);
1384 pkt.putRawString(g_version_hash, (u16) strlen(g_version_hash));
1388 void Client::sendPlayerPos()
1390 LocalPlayer *myplayer = m_env.getLocalPlayer();
1391 if(myplayer == NULL)
1394 ClientMap &map = m_env.getClientMap();
1396 u8 camera_fov = map.getCameraFov();
1397 u8 wanted_range = map.getControl().wanted_range;
1399 // Save bandwidth by only updating position when something changed
1400 if(myplayer->last_position == myplayer->getPosition() &&
1401 myplayer->last_speed == myplayer->getSpeed() &&
1402 myplayer->last_pitch == myplayer->getPitch() &&
1403 myplayer->last_yaw == myplayer->getYaw() &&
1404 myplayer->last_keyPressed == myplayer->keyPressed &&
1405 myplayer->last_camera_fov == camera_fov &&
1406 myplayer->last_wanted_range == wanted_range)
1409 myplayer->last_position = myplayer->getPosition();
1410 myplayer->last_speed = myplayer->getSpeed();
1411 myplayer->last_pitch = myplayer->getPitch();
1412 myplayer->last_yaw = myplayer->getYaw();
1413 myplayer->last_keyPressed = myplayer->keyPressed;
1414 myplayer->last_camera_fov = camera_fov;
1415 myplayer->last_wanted_range = wanted_range;
1417 //infostream << "Sending Player Position information" << std::endl;
1421 //MutexAutoLock lock(m_con_mutex); //bulk comment-out
1422 our_peer_id = m_con.GetPeerID();
1425 // Set peer id if not set already
1426 if(myplayer->peer_id == PEER_ID_INEXISTENT)
1427 myplayer->peer_id = our_peer_id;
1429 assert(myplayer->peer_id == our_peer_id);
1431 NetworkPacket pkt(TOSERVER_PLAYERPOS, 12 + 12 + 4 + 4 + 4 + 1 + 1);
1433 writePlayerPos(myplayer, &map, &pkt);
1438 void Client::sendPlayerItem(u16 item)
1440 LocalPlayer *myplayer = m_env.getLocalPlayer();
1441 if(myplayer == NULL)
1444 u16 our_peer_id = m_con.GetPeerID();
1446 // Set peer id if not set already
1447 if(myplayer->peer_id == PEER_ID_INEXISTENT)
1448 myplayer->peer_id = our_peer_id;
1449 assert(myplayer->peer_id == our_peer_id);
1451 NetworkPacket pkt(TOSERVER_PLAYERITEM, 2);
1458 void Client::removeNode(v3s16 p)
1460 std::map<v3s16, MapBlock*> modified_blocks;
1463 m_env.getMap().removeNodeAndUpdate(p, modified_blocks);
1465 catch(InvalidPositionException &e) {
1468 for(std::map<v3s16, MapBlock *>::iterator
1469 i = modified_blocks.begin();
1470 i != modified_blocks.end(); ++i) {
1471 addUpdateMeshTaskWithEdge(i->first, false, true);
1475 MapNode Client::getNode(v3s16 p, bool *is_valid_position)
1477 return m_env.getMap().getNodeNoEx(p, is_valid_position);
1480 void Client::addNode(v3s16 p, MapNode n, bool remove_metadata)
1482 //TimeTaker timer1("Client::addNode()");
1484 std::map<v3s16, MapBlock*> modified_blocks;
1487 //TimeTaker timer3("Client::addNode(): addNodeAndUpdate");
1488 m_env.getMap().addNodeAndUpdate(p, n, modified_blocks, remove_metadata);
1490 catch(InvalidPositionException &e) {
1493 for(std::map<v3s16, MapBlock *>::iterator
1494 i = modified_blocks.begin();
1495 i != modified_blocks.end(); ++i) {
1496 addUpdateMeshTaskWithEdge(i->first, false, true);
1500 void Client::setPlayerControl(PlayerControl &control)
1502 LocalPlayer *player = m_env.getLocalPlayer();
1503 assert(player != NULL);
1504 player->control = control;
1507 void Client::selectPlayerItem(u16 item)
1509 m_playeritem = item;
1510 m_inventory_updated = true;
1511 sendPlayerItem(item);
1514 // Returns true if the inventory of the local player has been
1515 // updated from the server. If it is true, it is set to false.
1516 bool Client::getLocalInventoryUpdated()
1518 bool updated = m_inventory_updated;
1519 m_inventory_updated = false;
1523 // Copies the inventory of the local player to parameter
1524 void Client::getLocalInventory(Inventory &dst)
1526 LocalPlayer *player = m_env.getLocalPlayer();
1527 assert(player != NULL);
1528 dst = player->inventory;
1531 Inventory* Client::getInventory(const InventoryLocation &loc)
1534 case InventoryLocation::UNDEFINED:
1537 case InventoryLocation::CURRENT_PLAYER:
1539 LocalPlayer *player = m_env.getLocalPlayer();
1540 assert(player != NULL);
1541 return &player->inventory;
1544 case InventoryLocation::PLAYER:
1546 // Check if we are working with local player inventory
1547 LocalPlayer *player = m_env.getLocalPlayer();
1548 if (!player || strcmp(player->getName(), loc.name.c_str()) != 0)
1550 return &player->inventory;
1553 case InventoryLocation::NODEMETA:
1555 NodeMetadata *meta = m_env.getMap().getNodeMetadata(loc.p);
1558 return meta->getInventory();
1561 case InventoryLocation::DETACHED:
1563 if (m_detached_inventories.count(loc.name) == 0)
1565 return m_detached_inventories[loc.name];
1569 FATAL_ERROR("Invalid inventory location type.");
1575 void Client::inventoryAction(InventoryAction *a)
1578 Send it to the server
1580 sendInventoryAction(a);
1583 Predict some local inventory changes
1585 a->clientApply(this, this);
1591 float Client::getAnimationTime()
1593 return m_animation_time;
1596 int Client::getCrackLevel()
1598 return m_crack_level;
1601 void Client::setCrack(int level, v3s16 pos)
1603 int old_crack_level = m_crack_level;
1604 v3s16 old_crack_pos = m_crack_pos;
1606 m_crack_level = level;
1609 if(old_crack_level >= 0 && (level < 0 || pos != old_crack_pos))
1612 addUpdateMeshTaskForNode(old_crack_pos, false, true);
1614 if(level >= 0 && (old_crack_level < 0 || pos != old_crack_pos))
1617 addUpdateMeshTaskForNode(pos, false, true);
1623 LocalPlayer *player = m_env.getLocalPlayer();
1624 assert(player != NULL);
1628 bool Client::getChatMessage(std::wstring &message)
1630 if(m_chat_queue.size() == 0)
1632 message = m_chat_queue.front();
1637 void Client::typeChatMessage(const std::wstring &message)
1639 // Discard empty line
1643 // If message was ate by script API, don't send it to server
1644 if (m_script->on_sending_message(wide_to_utf8(message))) {
1649 sendChatMessage(message);
1652 if (message[0] != L'/')
1654 // compatibility code
1655 if (m_proto_ver < 29) {
1656 LocalPlayer *player = m_env.getLocalPlayer();
1657 assert(player != NULL);
1658 std::wstring name = narrow_to_wide(player->getName());
1659 pushToChatQueue((std::wstring)L"<" + name + L"> " + message);
1664 void Client::addUpdateMeshTask(v3s16 p, bool ack_to_server, bool urgent)
1666 MapBlock *b = m_env.getMap().getBlockNoCreateNoEx(p);
1671 Create a task to update the mesh of the block
1674 MeshMakeData *data = new MeshMakeData(this, m_cache_enable_shaders,
1675 m_cache_use_tangent_vertices);
1678 //TimeTaker timer("data fill");
1680 // Debug: 1-6ms, avg=2ms
1682 data->setCrack(m_crack_level, m_crack_pos);
1683 data->setSmoothLighting(m_cache_smooth_lighting);
1686 // Add task to queue
1687 m_mesh_update_thread.enqueueUpdate(p, data, ack_to_server, urgent);
1690 void Client::addUpdateMeshTaskWithEdge(v3s16 blockpos, bool ack_to_server, bool urgent)
1693 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1695 catch(InvalidPositionException &e){}
1698 for (int i=0;i<6;i++)
1701 v3s16 p = blockpos + g_6dirs[i];
1702 addUpdateMeshTask(p, false, urgent);
1704 catch(InvalidPositionException &e){}
1708 void Client::addUpdateMeshTaskForNode(v3s16 nodepos, bool ack_to_server, bool urgent)
1712 infostream<<"Client::addUpdateMeshTaskForNode(): "
1713 <<"("<<p.X<<","<<p.Y<<","<<p.Z<<")"
1717 v3s16 blockpos = getNodeBlockPos(nodepos);
1718 v3s16 blockpos_relative = blockpos * MAP_BLOCKSIZE;
1721 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1723 catch(InvalidPositionException &e) {}
1726 if(nodepos.X == blockpos_relative.X){
1728 v3s16 p = blockpos + v3s16(-1,0,0);
1729 addUpdateMeshTask(p, false, urgent);
1731 catch(InvalidPositionException &e){}
1734 if(nodepos.Y == blockpos_relative.Y){
1736 v3s16 p = blockpos + v3s16(0,-1,0);
1737 addUpdateMeshTask(p, false, urgent);
1739 catch(InvalidPositionException &e){}
1742 if(nodepos.Z == blockpos_relative.Z){
1744 v3s16 p = blockpos + v3s16(0,0,-1);
1745 addUpdateMeshTask(p, false, urgent);
1747 catch(InvalidPositionException &e){}
1751 ClientEvent Client::getClientEvent()
1754 if (m_client_event_queue.empty()) {
1755 event.type = CE_NONE;
1758 event = m_client_event_queue.front();
1759 m_client_event_queue.pop();
1764 float Client::mediaReceiveProgress()
1766 if (m_media_downloader)
1767 return m_media_downloader->getProgress();
1769 return 1.0; // downloader only exists when not yet done
1772 typedef struct TextureUpdateArgs {
1773 IrrlichtDevice *device;
1774 gui::IGUIEnvironment *guienv;
1777 const wchar_t* text_base;
1778 } TextureUpdateArgs;
1780 void texture_update_progress(void *args, u32 progress, u32 max_progress)
1782 TextureUpdateArgs* targs = (TextureUpdateArgs*) args;
1783 u16 cur_percent = ceil(progress / (double) max_progress * 100.);
1785 // update the loading menu -- if neccessary
1786 bool do_draw = false;
1787 u32 time_ms = targs->last_time_ms;
1788 if (cur_percent != targs->last_percent) {
1789 targs->last_percent = cur_percent;
1790 time_ms = getTimeMs();
1791 // only draw when the user will notice something:
1792 do_draw = (time_ms - targs->last_time_ms > 100);
1796 targs->last_time_ms = time_ms;
1797 std::basic_stringstream<wchar_t> strm;
1798 strm << targs->text_base << " " << targs->last_percent << "%...";
1799 draw_load_screen(strm.str(), targs->device, targs->guienv, 0,
1800 72 + (u16) ((18. / 100.) * (double) targs->last_percent));
1804 void Client::afterContentReceived(IrrlichtDevice *device)
1806 infostream<<"Client::afterContentReceived() started"<<std::endl;
1807 assert(m_itemdef_received); // pre-condition
1808 assert(m_nodedef_received); // pre-condition
1809 assert(mediaReceived()); // pre-condition
1811 const wchar_t* text = wgettext("Loading textures...");
1813 // Clear cached pre-scaled 2D GUI images, as this cache
1814 // might have images with the same name but different
1815 // content from previous sessions.
1816 guiScalingCacheClear(device->getVideoDriver());
1818 // Rebuild inherited images and recreate textures
1819 infostream<<"- Rebuilding images and textures"<<std::endl;
1820 draw_load_screen(text,device, guienv, 0, 70);
1821 m_tsrc->rebuildImagesAndTextures();
1825 infostream<<"- Rebuilding shaders"<<std::endl;
1826 text = wgettext("Rebuilding shaders...");
1827 draw_load_screen(text, device, guienv, 0, 71);
1828 m_shsrc->rebuildShaders();
1831 // Update node aliases
1832 infostream<<"- Updating node aliases"<<std::endl;
1833 text = wgettext("Initializing nodes...");
1834 draw_load_screen(text, device, guienv, 0, 72);
1835 m_nodedef->updateAliases(m_itemdef);
1836 std::string texture_path = g_settings->get("texture_path");
1837 if (texture_path != "" && fs::IsDir(texture_path))
1838 m_nodedef->applyTextureOverrides(texture_path + DIR_DELIM + "override.txt");
1839 m_nodedef->setNodeRegistrationStatus(true);
1840 m_nodedef->runNodeResolveCallbacks();
1843 // Update node textures and assign shaders to each tile
1844 infostream<<"- Updating node textures"<<std::endl;
1845 TextureUpdateArgs tu_args;
1846 tu_args.device = device;
1847 tu_args.guienv = guienv;
1848 tu_args.last_time_ms = getTimeMs();
1849 tu_args.last_percent = 0;
1850 tu_args.text_base = wgettext("Initializing nodes");
1851 m_nodedef->updateTextures(this, texture_update_progress, &tu_args);
1852 delete[] tu_args.text_base;
1854 // Start mesh update thread after setting up content definitions
1855 infostream<<"- Starting mesh update thread"<<std::endl;
1856 m_mesh_update_thread.start();
1860 text = wgettext("Done!");
1861 draw_load_screen(text, device, guienv, 0, 100);
1862 infostream<<"Client::afterContentReceived() done"<<std::endl;
1866 float Client::getRTT()
1868 return m_con.getPeerStat(PEER_ID_SERVER,con::AVG_RTT);
1871 float Client::getCurRate()
1873 return ( m_con.getLocalStat(con::CUR_INC_RATE) +
1874 m_con.getLocalStat(con::CUR_DL_RATE));
1877 void Client::makeScreenshot(IrrlichtDevice *device)
1879 irr::video::IVideoDriver *driver = device->getVideoDriver();
1880 irr::video::IImage* const raw_image = driver->createScreenShot();
1885 time_t t = time(NULL);
1886 struct tm *tm = localtime(&t);
1888 char timetstamp_c[64];
1889 strftime(timetstamp_c, sizeof(timetstamp_c), "%Y%m%d_%H%M%S", tm);
1891 std::string filename_base = g_settings->get("screenshot_path")
1893 + std::string("screenshot_")
1894 + std::string(timetstamp_c);
1895 std::string filename_ext = "." + g_settings->get("screenshot_format");
1896 std::string filename;
1898 u32 quality = (u32)g_settings->getS32("screenshot_quality");
1899 quality = MYMIN(MYMAX(quality, 0), 100) / 100.0 * 255;
1901 // Try to find a unique filename
1902 unsigned serial = 0;
1904 while (serial < SCREENSHOT_MAX_SERIAL_TRIES) {
1905 filename = filename_base + (serial > 0 ? ("_" + itos(serial)) : "") + filename_ext;
1906 std::ifstream tmp(filename.c_str());
1908 break; // File did not apparently exist, we'll go with it
1912 if (serial == SCREENSHOT_MAX_SERIAL_TRIES) {
1913 infostream << "Could not find suitable filename for screenshot" << std::endl;
1915 irr::video::IImage* const image =
1916 driver->createImage(video::ECF_R8G8B8, raw_image->getDimension());
1919 raw_image->copyTo(image);
1921 std::ostringstream sstr;
1922 if (driver->writeImageToFile(image, filename.c_str(), quality)) {
1923 sstr << "Saved screenshot to '" << filename << "'";
1925 sstr << "Failed to save screenshot '" << filename << "'";
1927 pushToChatQueue(narrow_to_wide(sstr.str()));
1928 infostream << sstr.str() << std::endl;
1936 bool Client::shouldShowMinimap() const
1938 return !m_minimap_disabled_by_server;
1941 void Client::showGameChat(const bool show)
1943 m_game_ui_flags->show_chat = show;
1946 void Client::showGameHud(const bool show)
1948 m_game_ui_flags->show_hud = show;
1951 void Client::showMinimap(const bool show)
1953 m_game_ui_flags->show_minimap = show;
1956 void Client::showProfiler(const bool show)
1958 m_game_ui_flags->show_profiler_graph = show;
1961 void Client::showGameFog(const bool show)
1963 m_game_ui_flags->force_fog_off = !show;
1966 void Client::showGameDebug(const bool show)
1968 m_game_ui_flags->show_debug = show;
1971 // IGameDef interface
1973 IItemDefManager* Client::getItemDefManager()
1977 INodeDefManager* Client::getNodeDefManager()
1981 ICraftDefManager* Client::getCraftDefManager()
1984 //return m_craftdef;
1986 ITextureSource* Client::getTextureSource()
1990 IShaderSource* Client::getShaderSource()
1994 scene::ISceneManager* Client::getSceneManager()
1996 return m_device->getSceneManager();
1998 u16 Client::allocateUnknownNodeId(const std::string &name)
2000 errorstream << "Client::allocateUnknownNodeId(): "
2001 << "Client cannot allocate node IDs" << std::endl;
2002 FATAL_ERROR("Client allocated unknown node");
2004 return CONTENT_IGNORE;
2006 ISoundManager* Client::getSoundManager()
2010 MtEventManager* Client::getEventManager()
2015 ParticleManager* Client::getParticleManager()
2017 return &m_particle_manager;
2020 scene::IAnimatedMesh* Client::getMesh(const std::string &filename)
2022 StringMap::const_iterator it = m_mesh_data.find(filename);
2023 if (it == m_mesh_data.end()) {
2024 errorstream << "Client::getMesh(): Mesh not found: \"" << filename
2025 << "\"" << std::endl;
2028 const std::string &data = it->second;
2029 scene::ISceneManager *smgr = m_device->getSceneManager();
2031 // Create the mesh, remove it from cache and return it
2032 // This allows unique vertex colors and other properties for each instance
2033 Buffer<char> data_rw(data.c_str(), data.size()); // Const-incorrect Irrlicht
2034 io::IFileSystem *irrfs = m_device->getFileSystem();
2035 io::IReadFile *rfile = irrfs->createMemoryReadFile(
2036 *data_rw, data_rw.getSize(), filename.c_str());
2037 FATAL_ERROR_IF(!rfile, "Could not create/open RAM file");
2039 scene::IAnimatedMesh *mesh = smgr->getMesh(rfile);
2041 // NOTE: By playing with Irrlicht refcounts, maybe we could cache a bunch
2042 // of uniquely named instances and re-use them
2044 smgr->getMeshCache()->removeMesh(mesh);
2048 bool Client::registerModStorage(ModMetadata *storage)
2050 if (m_mod_storages.find(storage->getModName()) != m_mod_storages.end()) {
2051 errorstream << "Unable to register same mod storage twice. Storage name: "
2052 << storage->getModName() << std::endl;
2056 m_mod_storages[storage->getModName()] = storage;
2060 void Client::unregisterModStorage(const std::string &name)
2062 UNORDERED_MAP<std::string, ModMetadata *>::const_iterator it = m_mod_storages.find(name);
2063 if (it != m_mod_storages.end()) {
2064 // Save unconditionaly on unregistration
2065 it->second->save(getModStoragePath());
2066 m_mod_storages.erase(name);
2070 std::string Client::getModStoragePath() const
2072 return porting::path_user + DIR_DELIM + "client" + DIR_DELIM + "mod_storage";