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.
23 #include <IFileSystem.h>
24 #include "jthread/jmutexautolock.h"
25 #include "util/directiontables.h"
26 #include "util/pointedthing.h"
27 #include "util/serialize.h"
28 #include "util/string.h"
30 #include "network/clientopcodes.h"
34 #include "mapblock_mesh.h"
40 #include "nodemetadata.h"
43 #include "clientmap.h"
44 #include "clientmedia.h"
46 #include "IMeshCache.h"
49 #include "drawscene.h"
50 #include "database-sqlite3.h"
51 #include "serialization.h"
52 #include "guiscalingfilter.h"
54 extern gui::IGUIEnvironment* guienv;
60 QueuedMeshUpdate::QueuedMeshUpdate():
63 ack_block_to_server(false)
67 QueuedMeshUpdate::~QueuedMeshUpdate()
77 MeshUpdateQueue::MeshUpdateQueue()
81 MeshUpdateQueue::~MeshUpdateQueue()
83 JMutexAutoLock lock(m_mutex);
85 for(std::vector<QueuedMeshUpdate*>::iterator
87 i != m_queue.end(); i++)
89 QueuedMeshUpdate *q = *i;
95 peer_id=0 adds with nobody to send to
97 void MeshUpdateQueue::addBlock(v3s16 p, MeshMakeData *data, bool ack_block_to_server, bool urgent)
99 DSTACK(__FUNCTION_NAME);
101 assert(data); // pre-condition
103 JMutexAutoLock lock(m_mutex);
109 Find if block is already in queue.
110 If it is, update the data and quit.
112 for(std::vector<QueuedMeshUpdate*>::iterator
114 i != m_queue.end(); i++)
116 QueuedMeshUpdate *q = *i;
122 if(ack_block_to_server)
123 q->ack_block_to_server = true;
131 QueuedMeshUpdate *q = new QueuedMeshUpdate;
134 q->ack_block_to_server = ack_block_to_server;
135 m_queue.push_back(q);
138 // Returned pointer must be deleted
139 // Returns NULL if queue is empty
140 QueuedMeshUpdate * MeshUpdateQueue::pop()
142 JMutexAutoLock lock(m_mutex);
144 bool must_be_urgent = !m_urgents.empty();
145 for(std::vector<QueuedMeshUpdate*>::iterator
147 i != m_queue.end(); i++)
149 QueuedMeshUpdate *q = *i;
150 if(must_be_urgent && m_urgents.count(q->p) == 0)
153 m_urgents.erase(q->p);
163 void * MeshUpdateThread::Thread()
167 log_register_thread("MeshUpdateThread");
169 DSTACK(__FUNCTION_NAME);
171 BEGIN_DEBUG_EXCEPTION_HANDLER
173 porting::setThreadName("MeshUpdateThread");
175 while(!StopRequested())
177 QueuedMeshUpdate *q = m_queue_in.pop();
184 ScopeProfiler sp(g_profiler, "Client: Mesh making");
186 MapBlockMesh *mesh_new = new MapBlockMesh(q->data, m_camera_offset);
187 if(mesh_new->getMesh()->getMeshBufferCount() == 0)
196 r.ack_block_to_server = q->ack_block_to_server;
198 m_queue_out.push_back(r);
203 END_DEBUG_EXCEPTION_HANDLER(errorstream)
213 IrrlichtDevice *device,
214 const char *playername,
215 std::string password,
216 MapDrawControl &control,
217 IWritableTextureSource *tsrc,
218 IWritableShaderSource *shsrc,
219 IWritableItemDefManager *itemdef,
220 IWritableNodeDefManager *nodedef,
221 ISoundManager *sound,
222 MtEventManager *event,
225 m_packetcounter_timer(0.0),
226 m_connection_reinit_timer(0.1),
227 m_avg_rtt_timer(0.0),
228 m_playerpos_send_timer(0.0),
229 m_ignore_damage_timer(0.0),
236 m_mesh_update_thread(this),
238 new ClientMap(this, this, control,
239 device->getSceneManager()->getRootSceneNode(),
240 device->getSceneManager(), 666),
241 device->getSceneManager(),
244 m_particle_manager(&m_env),
245 m_con(PROTOCOL_ID, 512, CONNECTION_TIMEOUT, ipv6, this),
247 m_server_ser_ver(SER_FMT_VER_INVALID),
249 m_inventory_updated(false),
250 m_inventory_from_server(NULL),
251 m_inventory_from_server_age(0.0),
252 m_show_highlighted(false),
256 m_highlighted_pos(0,0,0),
258 m_password(password),
259 m_access_denied(false),
260 m_itemdef_received(false),
261 m_nodedef_received(false),
262 m_media_downloader(new ClientMediaDownloader()),
263 m_time_of_day_set(false),
264 m_last_time_of_day_f(-1),
265 m_time_of_day_update_timer(0),
266 m_recommended_send_interval(0.1),
267 m_removed_sounds_check_timer(0),
272 m_env.addPlayer(new LocalPlayer(this, playername));
274 m_cache_save_interval = g_settings->getU16("server_map_save_interval");
276 m_cache_smooth_lighting = g_settings->getBool("smooth_lighting");
277 m_cache_enable_shaders = g_settings->getBool("enable_shaders");
282 //request all client managed threads to stop
283 m_mesh_update_thread.Stop();
284 // Save local server map
286 infostream << "Local map saving ended." << std::endl;
287 m_localdb->endSave();
291 bool Client::isShutdown()
294 if (!m_mesh_update_thread.IsRunning()) return true;
303 m_mesh_update_thread.Stop();
304 m_mesh_update_thread.Wait();
305 while(!m_mesh_update_thread.m_queue_out.empty()) {
306 MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_frontNoEx();
311 delete m_inventory_from_server;
313 // Delete detached inventories
314 for(std::map<std::string, Inventory*>::iterator
315 i = m_detached_inventories.begin();
316 i != m_detached_inventories.end(); i++){
320 // cleanup 3d model meshes on client shutdown
321 while (m_device->getSceneManager()->getMeshCache()->getMeshCount() != 0) {
322 scene::IAnimatedMesh * mesh =
323 m_device->getSceneManager()->getMeshCache()->getMeshByIndex(0);
326 m_device->getSceneManager()->getMeshCache()->removeMesh(mesh);
330 void Client::connect(Address address,
331 const std::string &address_name,
332 bool is_local_server)
334 DSTACK(__FUNCTION_NAME);
336 initLocalMapSaving(address, address_name, is_local_server);
338 m_con.SetTimeoutMs(0);
339 m_con.Connect(address);
342 void Client::step(float dtime)
344 DSTACK(__FUNCTION_NAME);
350 if(m_ignore_damage_timer > dtime)
351 m_ignore_damage_timer -= dtime;
353 m_ignore_damage_timer = 0.0;
355 m_animation_time += dtime;
356 if(m_animation_time > 60.0)
357 m_animation_time -= 60.0;
359 m_time_of_day_update_timer += dtime;
367 float &counter = m_packetcounter_timer;
373 infostream << "Client packetcounter (" << m_packetcounter_timer
375 m_packetcounter.print(infostream);
376 m_packetcounter.clear();
380 // UGLY hack to fix 2 second startup delay caused by non existent
381 // server client startup synchronization in local server or singleplayer mode
382 static bool initial_step = true;
384 initial_step = false;
386 else if(m_state == LC_Created) {
387 float &counter = m_connection_reinit_timer;
392 Player *myplayer = m_env.getLocalPlayer();
393 FATAL_ERROR_IF(myplayer == NULL, "Local player not found in environment.");
395 // Send TOSERVER_INIT
396 // [0] u16 TOSERVER_INIT
397 // [2] u8 SER_FMT_VER_HIGHEST_READ
398 // [3] u8[20] player_name
399 // [23] u8[28] password (new in some version)
400 // [51] u16 minimum supported network protocol version (added sometime)
401 // [53] u16 maximum supported network protocol version (added later than the previous one)
403 char pName[PLAYERNAME_SIZE];
404 char pPassword[PASSWORD_SIZE];
405 memset(pName, 0, PLAYERNAME_SIZE * sizeof(char));
406 memset(pPassword, 0, PASSWORD_SIZE * sizeof(char));
408 snprintf(pName, PLAYERNAME_SIZE, "%s", myplayer->getName());
409 snprintf(pPassword, PASSWORD_SIZE, "%s", m_password.c_str());
411 sendLegacyInit(pName, pPassword);
414 // Not connected, return
419 Do stuff if connected
423 Run Map's timers and unload unused data
425 const float map_timer_and_unload_dtime = 5.25;
426 if(m_map_timer_and_unload_interval.step(dtime, map_timer_and_unload_dtime)) {
427 ScopeProfiler sp(g_profiler, "Client: map timer and unload");
428 std::vector<v3s16> deleted_blocks;
429 m_env.getMap().timerUpdate(map_timer_and_unload_dtime,
430 g_settings->getFloat("client_unload_unused_data_timeout"),
435 NOTE: This loop is intentionally iterated the way it is.
438 std::vector<v3s16>::iterator i = deleted_blocks.begin();
439 std::vector<v3s16> sendlist;
441 if(sendlist.size() == 255 || i == deleted_blocks.end()) {
452 sendDeletedBlocks(sendlist);
454 if(i == deleted_blocks.end())
460 sendlist.push_back(*i);
468 // Control local player (0ms)
469 LocalPlayer *player = m_env.getLocalPlayer();
470 assert(player != NULL);
471 player->applyControl(dtime);
480 ClientEnvEvent event = m_env.getClientEvent();
481 if(event.type == CEE_NONE) {
484 else if(event.type == CEE_PLAYER_DAMAGE) {
485 if(m_ignore_damage_timer <= 0) {
486 u8 damage = event.player_damage.amount;
488 if(event.player_damage.send_to_server)
491 // Add to ClientEvent queue
493 event.type = CE_PLAYER_DAMAGE;
494 event.player_damage.amount = damage;
495 m_client_event_queue.push(event);
498 else if(event.type == CEE_PLAYER_BREATH) {
499 u16 breath = event.player_breath.amount;
507 float &counter = m_avg_rtt_timer;
511 // connectedAndInitialized() is true, peer exists.
512 float avg_rtt = getRTT();
513 infostream << "Client: avg_rtt=" << avg_rtt << std::endl;
517 Send player position to server
520 float &counter = m_playerpos_send_timer;
522 if((m_state == LC_Ready) && (counter >= m_recommended_send_interval))
530 Replace updated meshes
533 int num_processed_meshes = 0;
534 while(!m_mesh_update_thread.m_queue_out.empty())
536 num_processed_meshes++;
537 MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_frontNoEx();
538 MapBlock *block = m_env.getMap().getBlockNoCreateNoEx(r.p);
540 // Delete the old mesh
541 if(block->mesh != NULL)
543 // TODO: Remove hardware buffers of meshbuffers of block->mesh
548 // Replace with the new mesh
549 block->mesh = r.mesh;
554 if(r.ack_block_to_server) {
564 if(num_processed_meshes > 0)
565 g_profiler->graphAdd("num_processed_meshes", num_processed_meshes);
571 if (m_media_downloader && m_media_downloader->isStarted()) {
572 m_media_downloader->step(this);
573 if (m_media_downloader->isDone()) {
575 delete m_media_downloader;
576 m_media_downloader = NULL;
581 If the server didn't update the inventory in a while, revert
582 the local inventory (so the player notices the lag problem
583 and knows something is wrong).
585 if(m_inventory_from_server)
587 float interval = 10.0;
588 float count_before = floor(m_inventory_from_server_age / interval);
590 m_inventory_from_server_age += dtime;
592 float count_after = floor(m_inventory_from_server_age / interval);
594 if(count_after != count_before)
596 // Do this every <interval> seconds after TOCLIENT_INVENTORY
597 // Reset the locally changed inventory to the authoritative inventory
598 Player *player = m_env.getLocalPlayer();
599 player->inventory = *m_inventory_from_server;
600 m_inventory_updated = true;
605 Update positions of sounds attached to objects
608 for(std::map<int, u16>::iterator
609 i = m_sounds_to_objects.begin();
610 i != m_sounds_to_objects.end(); i++)
612 int client_id = i->first;
613 u16 object_id = i->second;
614 ClientActiveObject *cao = m_env.getActiveObject(object_id);
617 v3f pos = cao->getPosition();
618 m_sound->updateSoundPosition(client_id, pos);
623 Handle removed remotely initiated sounds
625 m_removed_sounds_check_timer += dtime;
626 if(m_removed_sounds_check_timer >= 2.32) {
627 m_removed_sounds_check_timer = 0;
628 // Find removed sounds and clear references to them
629 std::vector<s32> removed_server_ids;
630 for(std::map<s32, int>::iterator
631 i = m_sounds_server_to_client.begin();
632 i != m_sounds_server_to_client.end();) {
633 s32 server_id = i->first;
634 int client_id = i->second;
636 if(!m_sound->soundExists(client_id)) {
637 m_sounds_server_to_client.erase(server_id);
638 m_sounds_client_to_server.erase(client_id);
639 m_sounds_to_objects.erase(client_id);
640 removed_server_ids.push_back(server_id);
645 if(!removed_server_ids.empty()) {
646 sendRemovedSounds(removed_server_ids);
651 if (m_localdb && m_localdb_save_interval.step(dtime,
652 m_cache_save_interval)) {
653 m_localdb->endSave();
654 m_localdb->beginSave();
658 bool Client::loadMedia(const std::string &data, const std::string &filename)
660 // Silly irrlicht's const-incorrectness
661 Buffer<char> data_rw(data.c_str(), data.size());
665 const char *image_ext[] = {
666 ".png", ".jpg", ".bmp", ".tga",
667 ".pcx", ".ppm", ".psd", ".wal", ".rgb",
670 name = removeStringEnd(filename, image_ext);
673 verbosestream<<"Client: Attempting to load image "
674 <<"file \""<<filename<<"\""<<std::endl;
676 io::IFileSystem *irrfs = m_device->getFileSystem();
677 video::IVideoDriver *vdrv = m_device->getVideoDriver();
679 // Create an irrlicht memory file
680 io::IReadFile *rfile = irrfs->createMemoryReadFile(
681 *data_rw, data_rw.getSize(), "_tempreadfile");
683 FATAL_ERROR_IF(!rfile, "Could not create irrlicht memory file.");
686 video::IImage *img = vdrv->createImageFromFile(rfile);
688 errorstream<<"Client: Cannot create image from data of "
689 <<"file \""<<filename<<"\""<<std::endl;
694 m_tsrc->insertSourceImage(filename, img);
701 const char *sound_ext[] = {
702 ".0.ogg", ".1.ogg", ".2.ogg", ".3.ogg", ".4.ogg",
703 ".5.ogg", ".6.ogg", ".7.ogg", ".8.ogg", ".9.ogg",
706 name = removeStringEnd(filename, sound_ext);
709 verbosestream<<"Client: Attempting to load sound "
710 <<"file \""<<filename<<"\""<<std::endl;
711 m_sound->loadSoundData(name, data);
715 const char *model_ext[] = {
716 ".x", ".b3d", ".md2", ".obj",
719 name = removeStringEnd(filename, model_ext);
722 verbosestream<<"Client: Storing model into memory: "
723 <<"\""<<filename<<"\""<<std::endl;
724 if(m_mesh_data.count(filename))
725 errorstream<<"Multiple models with name \""<<filename.c_str()
726 <<"\" found; replacing previous model"<<std::endl;
727 m_mesh_data[filename] = data;
731 errorstream<<"Client: Don't know how to load file \""
732 <<filename<<"\""<<std::endl;
736 // Virtual methods from con::PeerHandler
737 void Client::peerAdded(con::Peer *peer)
739 infostream<<"Client::peerAdded(): peer->id="
740 <<peer->id<<std::endl;
742 void Client::deletingPeer(con::Peer *peer, bool timeout)
744 infostream<<"Client::deletingPeer(): "
745 "Server Peer is getting deleted "
746 <<"(timeout="<<timeout<<")"<<std::endl;
751 u16 number of files requested
757 void Client::request_media(const std::vector<std::string> &file_requests)
759 std::ostringstream os(std::ios_base::binary);
760 writeU16(os, TOSERVER_REQUEST_MEDIA);
761 size_t file_requests_size = file_requests.size();
763 FATAL_ERROR_IF(file_requests_size > 0xFFFF, "Unsupported number of file requests");
765 // Packet dynamicly resized
766 NetworkPacket pkt(TOSERVER_REQUEST_MEDIA, 2 + 0);
768 pkt << (u16) (file_requests_size & 0xFFFF);
770 for(std::vector<std::string>::const_iterator i = file_requests.begin();
771 i != file_requests.end(); ++i) {
777 infostream << "Client: Sending media request list to server ("
778 << file_requests.size() << " files. packet size)" << std::endl;
781 void Client::received_media()
783 NetworkPacket pkt(TOSERVER_RECEIVED_MEDIA, 0);
785 infostream << "Client: Notifying server that we received all media"
789 void Client::initLocalMapSaving(const Address &address,
790 const std::string &hostname,
791 bool is_local_server)
793 if (!g_settings->getBool("enable_local_map_saving") || is_local_server) {
797 const std::string world_path = porting::path_user
798 + DIR_DELIM + "worlds"
799 + DIR_DELIM + "server_"
800 + hostname + "_" + to_string(address.getPort());
802 fs::CreateAllDirs(world_path);
804 m_localdb = new Database_SQLite3(world_path);
805 m_localdb->beginSave();
806 actionstream << "Local map saving started, map will be saved at '" << world_path << "'" << std::endl;
809 void Client::ReceiveAll()
811 DSTACK(__FUNCTION_NAME);
812 u32 start_ms = porting::getTimeMs();
815 // Limit time even if there would be huge amounts of data to
817 if(porting::getTimeMs() > start_ms + 100)
822 g_profiler->graphAdd("client_received_packets", 1);
824 catch(con::NoIncomingDataException &e) {
827 catch(con::InvalidIncomingDataException &e) {
828 infostream<<"Client::ReceiveAll(): "
829 "InvalidIncomingDataException: what()="
830 <<e.what()<<std::endl;
835 void Client::Receive()
837 DSTACK(__FUNCTION_NAME);
843 inline void Client::handleCommand(NetworkPacket* pkt)
845 const ToClientCommandHandler& opHandle = toClientCommandTable[pkt->getCommand()];
846 (this->*opHandle.handler)(pkt);
850 sender_peer_id given to this shall be quaranteed to be a valid peer
852 void Client::ProcessData(NetworkPacket *pkt)
854 DSTACK(__FUNCTION_NAME);
856 ToClientCommand command = (ToClientCommand) pkt->getCommand();
857 u32 sender_peer_id = pkt->getPeerId();
859 //infostream<<"Client: received command="<<command<<std::endl;
860 m_packetcounter.add((u16)command);
863 If this check is removed, be sure to change the queue
864 system to know the ids
866 if(sender_peer_id != PEER_ID_SERVER) {
867 infostream << "Client::ProcessData(): Discarding data not "
868 "coming from server: peer_id=" << sender_peer_id
873 // Command must be handled into ToClientCommandHandler
874 if (command >= TOCLIENT_NUM_MSG_TYPES) {
875 infostream << "Client: Ignoring unknown command "
876 << command << std::endl;
880 * Those packets are handled before m_server_ser_ver is set, it's normal
881 * But we must use the new ToClientConnectionState in the future,
884 if(toClientCommandTable[command].state == TOCLIENT_STATE_NOT_CONNECTED) {
889 if(m_server_ser_ver == SER_FMT_VER_INVALID) {
890 infostream << "Client: Server serialization"
891 " format invalid or not initialized."
892 " Skipping incoming command=" << command << std::endl;
897 Handle runtime commands
903 void Client::Send(NetworkPacket* pkt)
905 m_con.Send(PEER_ID_SERVER,
906 serverCommandFactoryTable[pkt->getCommand()].channel,
908 serverCommandFactoryTable[pkt->getCommand()].reliable);
911 void Client::interact(u8 action, const PointedThing& pointed)
913 if(m_state != LC_Ready) {
914 errorstream << "Client::interact() "
915 "Canceled (not connected)"
924 [5] u32 length of the next item
925 [9] serialized PointedThing
927 0: start digging (from undersurface) or use
928 1: stop digging (all parameters ignored)
930 3: place block or item (to abovesurface)
934 NetworkPacket pkt(TOSERVER_INTERACT, 1 + 2 + 0);
937 pkt << (u16)getPlayerItem();
939 std::ostringstream tmp_os(std::ios::binary);
940 pointed.serialize(tmp_os);
942 pkt.putLongString(tmp_os.str());
947 void Client::sendLegacyInit(const char* playerName, const char* playerPassword)
949 NetworkPacket pkt(TOSERVER_INIT_LEGACY,
950 1 + PLAYERNAME_SIZE + PASSWORD_SIZE + 2 + 2);
952 pkt << (u8) SER_FMT_VER_HIGHEST_READ;
953 pkt.putRawString(playerName,PLAYERNAME_SIZE);
954 pkt.putRawString(playerPassword, PASSWORD_SIZE);
955 pkt << (u16) CLIENT_PROTOCOL_VERSION_MIN << (u16) CLIENT_PROTOCOL_VERSION_MAX;
960 void Client::sendDeletedBlocks(std::vector<v3s16> &blocks)
962 NetworkPacket pkt(TOSERVER_DELETEDBLOCKS, 1 + sizeof(v3s16) * blocks.size());
964 pkt << (u8) blocks.size();
967 for(std::vector<v3s16>::iterator
969 j != blocks.end(); ++j) {
977 void Client::sendGotBlocks(v3s16 block)
979 NetworkPacket pkt(TOSERVER_GOTBLOCKS, 1 + 6);
980 pkt << (u8) 1 << block;
984 void Client::sendRemovedSounds(std::vector<s32> &soundList)
986 size_t server_ids = soundList.size();
987 assert(server_ids <= 0xFFFF);
989 NetworkPacket pkt(TOSERVER_REMOVED_SOUNDS, 2 + server_ids * 4);
991 pkt << (u16) (server_ids & 0xFFFF);
993 for(std::vector<s32>::iterator i = soundList.begin();
994 i != soundList.end(); i++)
1000 void Client::sendNodemetaFields(v3s16 p, const std::string &formname,
1001 const std::map<std::string, std::string> &fields)
1003 size_t fields_size = fields.size();
1005 FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of nodemeta fields");
1007 NetworkPacket pkt(TOSERVER_NODEMETA_FIELDS, 0);
1009 pkt << p << formname << (u16) (fields_size & 0xFFFF);
1011 for(std::map<std::string, std::string>::const_iterator
1012 i = fields.begin(); i != fields.end(); i++) {
1013 const std::string &name = i->first;
1014 const std::string &value = i->second;
1016 pkt.putLongString(value);
1022 void Client::sendInventoryFields(const std::string &formname,
1023 const std::map<std::string, std::string> &fields)
1025 size_t fields_size = fields.size();
1026 FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of inventory fields");
1028 NetworkPacket pkt(TOSERVER_INVENTORY_FIELDS, 0);
1029 pkt << formname << (u16) (fields_size & 0xFFFF);
1031 for(std::map<std::string, std::string>::const_iterator
1032 i = fields.begin(); i != fields.end(); i++) {
1033 const std::string &name = i->first;
1034 const std::string &value = i->second;
1036 pkt.putLongString(value);
1042 void Client::sendInventoryAction(InventoryAction *a)
1044 std::ostringstream os(std::ios_base::binary);
1049 std::string s = os.str();
1051 NetworkPacket pkt(TOSERVER_INVENTORY_ACTION, s.size());
1052 pkt.putRawString(s.c_str(),s.size());
1057 void Client::sendChatMessage(const std::wstring &message)
1059 NetworkPacket pkt(TOSERVER_CHAT_MESSAGE, 2 + message.size() * sizeof(u16));
1066 void Client::sendChangePassword(const std::wstring &oldpassword,
1067 const std::wstring &newpassword)
1069 Player *player = m_env.getLocalPlayer();
1073 std::string playername = player->getName();
1074 std::string oldpwd = translatePassword(playername, oldpassword);
1075 std::string newpwd = translatePassword(playername, newpassword);
1077 NetworkPacket pkt(TOSERVER_PASSWORD_LEGACY, 2 * PASSWORD_SIZE);
1079 for(u8 i = 0; i < PASSWORD_SIZE; i++) {
1080 pkt << (u8) (i < oldpwd.length() ? oldpwd[i] : 0);
1083 for(u8 i = 0; i < PASSWORD_SIZE; i++) {
1084 pkt << (u8) (i < newpwd.length() ? newpwd[i] : 0);
1091 void Client::sendDamage(u8 damage)
1093 DSTACK(__FUNCTION_NAME);
1095 NetworkPacket pkt(TOSERVER_DAMAGE, sizeof(u8));
1100 void Client::sendBreath(u16 breath)
1102 DSTACK(__FUNCTION_NAME);
1104 NetworkPacket pkt(TOSERVER_BREATH, sizeof(u16));
1109 void Client::sendRespawn()
1111 DSTACK(__FUNCTION_NAME);
1113 NetworkPacket pkt(TOSERVER_RESPAWN, 0);
1117 void Client::sendReady()
1119 DSTACK(__FUNCTION_NAME);
1121 NetworkPacket pkt(TOSERVER_CLIENT_READY,
1122 1 + 1 + 1 + 1 + 2 + sizeof(char) * strlen(g_version_hash));
1124 pkt << (u8) VERSION_MAJOR << (u8) VERSION_MINOR << (u8) VERSION_PATCH
1125 << (u8) 0 << (u16) strlen(g_version_hash);
1127 pkt.putRawString(g_version_hash, (u16) strlen(g_version_hash));
1131 void Client::sendPlayerPos()
1133 LocalPlayer *myplayer = m_env.getLocalPlayer();
1134 if(myplayer == NULL)
1137 // Save bandwidth by only updating position when something changed
1138 if(myplayer->last_position == myplayer->getPosition() &&
1139 myplayer->last_speed == myplayer->getSpeed() &&
1140 myplayer->last_pitch == myplayer->getPitch() &&
1141 myplayer->last_yaw == myplayer->getYaw() &&
1142 myplayer->last_keyPressed == myplayer->keyPressed)
1145 myplayer->last_position = myplayer->getPosition();
1146 myplayer->last_speed = myplayer->getSpeed();
1147 myplayer->last_pitch = myplayer->getPitch();
1148 myplayer->last_yaw = myplayer->getYaw();
1149 myplayer->last_keyPressed = myplayer->keyPressed;
1153 //JMutexAutoLock lock(m_con_mutex); //bulk comment-out
1154 our_peer_id = m_con.GetPeerID();
1157 // Set peer id if not set already
1158 if(myplayer->peer_id == PEER_ID_INEXISTENT)
1159 myplayer->peer_id = our_peer_id;
1161 assert(myplayer->peer_id == our_peer_id);
1163 v3f pf = myplayer->getPosition();
1164 v3f sf = myplayer->getSpeed();
1165 s32 pitch = myplayer->getPitch() * 100;
1166 s32 yaw = myplayer->getYaw() * 100;
1167 u32 keyPressed = myplayer->keyPressed;
1169 v3s32 position(pf.X*100, pf.Y*100, pf.Z*100);
1170 v3s32 speed(sf.X*100, sf.Y*100, sf.Z*100);
1173 [0] v3s32 position*100
1174 [12] v3s32 speed*100
1175 [12+12] s32 pitch*100
1176 [12+12+4] s32 yaw*100
1177 [12+12+4+4] u32 keyPressed
1180 NetworkPacket pkt(TOSERVER_PLAYERPOS, 12 + 12 + 4 + 4 + 4);
1182 pkt << position << speed << pitch << yaw << keyPressed;
1187 void Client::sendPlayerItem(u16 item)
1189 Player *myplayer = m_env.getLocalPlayer();
1190 if(myplayer == NULL)
1193 u16 our_peer_id = m_con.GetPeerID();
1195 // Set peer id if not set already
1196 if(myplayer->peer_id == PEER_ID_INEXISTENT)
1197 myplayer->peer_id = our_peer_id;
1198 assert(myplayer->peer_id == our_peer_id);
1200 NetworkPacket pkt(TOSERVER_PLAYERITEM, 2);
1207 void Client::removeNode(v3s16 p)
1209 std::map<v3s16, MapBlock*> modified_blocks;
1212 m_env.getMap().removeNodeAndUpdate(p, modified_blocks);
1214 catch(InvalidPositionException &e) {
1217 for(std::map<v3s16, MapBlock *>::iterator
1218 i = modified_blocks.begin();
1219 i != modified_blocks.end(); ++i) {
1220 addUpdateMeshTaskWithEdge(i->first, false, true);
1224 void Client::addNode(v3s16 p, MapNode n, bool remove_metadata)
1226 //TimeTaker timer1("Client::addNode()");
1228 std::map<v3s16, MapBlock*> modified_blocks;
1231 //TimeTaker timer3("Client::addNode(): addNodeAndUpdate");
1232 m_env.getMap().addNodeAndUpdate(p, n, modified_blocks, remove_metadata);
1234 catch(InvalidPositionException &e) {
1237 for(std::map<v3s16, MapBlock *>::iterator
1238 i = modified_blocks.begin();
1239 i != modified_blocks.end(); ++i) {
1240 addUpdateMeshTaskWithEdge(i->first, false, true);
1244 void Client::setPlayerControl(PlayerControl &control)
1246 LocalPlayer *player = m_env.getLocalPlayer();
1247 assert(player != NULL);
1248 player->control = control;
1251 void Client::selectPlayerItem(u16 item)
1253 m_playeritem = item;
1254 m_inventory_updated = true;
1255 sendPlayerItem(item);
1258 // Returns true if the inventory of the local player has been
1259 // updated from the server. If it is true, it is set to false.
1260 bool Client::getLocalInventoryUpdated()
1262 bool updated = m_inventory_updated;
1263 m_inventory_updated = false;
1267 // Copies the inventory of the local player to parameter
1268 void Client::getLocalInventory(Inventory &dst)
1270 Player *player = m_env.getLocalPlayer();
1271 assert(player != NULL);
1272 dst = player->inventory;
1275 Inventory* Client::getInventory(const InventoryLocation &loc)
1278 case InventoryLocation::UNDEFINED:
1281 case InventoryLocation::CURRENT_PLAYER:
1283 Player *player = m_env.getLocalPlayer();
1284 assert(player != NULL);
1285 return &player->inventory;
1288 case InventoryLocation::PLAYER:
1290 Player *player = m_env.getPlayer(loc.name.c_str());
1293 return &player->inventory;
1296 case InventoryLocation::NODEMETA:
1298 NodeMetadata *meta = m_env.getMap().getNodeMetadata(loc.p);
1301 return meta->getInventory();
1304 case InventoryLocation::DETACHED:
1306 if(m_detached_inventories.count(loc.name) == 0)
1308 return m_detached_inventories[loc.name];
1312 FATAL_ERROR("Invalid inventory location type.");
1318 void Client::inventoryAction(InventoryAction *a)
1321 Send it to the server
1323 sendInventoryAction(a);
1326 Predict some local inventory changes
1328 a->clientApply(this, this);
1334 ClientActiveObject * Client::getSelectedActiveObject(
1336 v3f from_pos_f_on_map,
1337 core::line3d<f32> shootline_on_map
1340 std::vector<DistanceSortedActiveObject> objects;
1342 m_env.getActiveObjects(from_pos_f_on_map, max_d, objects);
1345 // After this, the closest object is the first in the array.
1346 std::sort(objects.begin(), objects.end());
1348 for(unsigned int i=0; i<objects.size(); i++)
1350 ClientActiveObject *obj = objects[i].obj;
1352 core::aabbox3d<f32> *selection_box = obj->getSelectionBox();
1353 if(selection_box == NULL)
1356 v3f pos = obj->getPosition();
1358 core::aabbox3d<f32> offsetted_box(
1359 selection_box->MinEdge + pos,
1360 selection_box->MaxEdge + pos
1363 if(offsetted_box.intersectsWithLine(shootline_on_map))
1372 std::list<std::string> Client::getConnectedPlayerNames()
1374 return m_env.getPlayerNames();
1377 float Client::getAnimationTime()
1379 return m_animation_time;
1382 int Client::getCrackLevel()
1384 return m_crack_level;
1387 void Client::setHighlighted(v3s16 pos, bool show_highlighted)
1389 m_show_highlighted = show_highlighted;
1390 v3s16 old_highlighted_pos = m_highlighted_pos;
1391 m_highlighted_pos = pos;
1392 addUpdateMeshTaskForNode(old_highlighted_pos, false, true);
1393 addUpdateMeshTaskForNode(m_highlighted_pos, false, true);
1396 void Client::setCrack(int level, v3s16 pos)
1398 int old_crack_level = m_crack_level;
1399 v3s16 old_crack_pos = m_crack_pos;
1401 m_crack_level = level;
1404 if(old_crack_level >= 0 && (level < 0 || pos != old_crack_pos))
1407 addUpdateMeshTaskForNode(old_crack_pos, false, true);
1409 if(level >= 0 && (old_crack_level < 0 || pos != old_crack_pos))
1412 addUpdateMeshTaskForNode(pos, false, true);
1418 Player *player = m_env.getLocalPlayer();
1419 assert(player != NULL);
1423 u16 Client::getBreath()
1425 Player *player = m_env.getLocalPlayer();
1426 assert(player != NULL);
1427 return player->getBreath();
1430 bool Client::getChatMessage(std::wstring &message)
1432 if(m_chat_queue.size() == 0)
1434 message = m_chat_queue.front();
1439 void Client::typeChatMessage(const std::wstring &message)
1441 // Discard empty line
1446 sendChatMessage(message);
1449 if (message[0] == L'/')
1451 m_chat_queue.push((std::wstring)L"issued command: " + message);
1455 LocalPlayer *player = m_env.getLocalPlayer();
1456 assert(player != NULL);
1457 std::wstring name = narrow_to_wide(player->getName());
1458 m_chat_queue.push((std::wstring)L"<" + name + L"> " + message);
1462 void Client::addUpdateMeshTask(v3s16 p, bool ack_to_server, bool urgent)
1464 MapBlock *b = m_env.getMap().getBlockNoCreateNoEx(p);
1469 Create a task to update the mesh of the block
1472 MeshMakeData *data = new MeshMakeData(this, m_cache_enable_shaders);
1475 //TimeTaker timer("data fill");
1477 // Debug: 1-6ms, avg=2ms
1479 data->setCrack(m_crack_level, m_crack_pos);
1480 data->setHighlighted(m_highlighted_pos, m_show_highlighted);
1481 data->setSmoothLighting(m_cache_smooth_lighting);
1484 // Add task to queue
1485 m_mesh_update_thread.m_queue_in.addBlock(p, data, ack_to_server, urgent);
1488 void Client::addUpdateMeshTaskWithEdge(v3s16 blockpos, bool ack_to_server, bool urgent)
1491 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1493 catch(InvalidPositionException &e){}
1496 for (int i=0;i<6;i++)
1499 v3s16 p = blockpos + g_6dirs[i];
1500 addUpdateMeshTask(p, false, urgent);
1502 catch(InvalidPositionException &e){}
1506 void Client::addUpdateMeshTaskForNode(v3s16 nodepos, bool ack_to_server, bool urgent)
1510 infostream<<"Client::addUpdateMeshTaskForNode(): "
1511 <<"("<<p.X<<","<<p.Y<<","<<p.Z<<")"
1515 v3s16 blockpos = getNodeBlockPos(nodepos);
1516 v3s16 blockpos_relative = blockpos * MAP_BLOCKSIZE;
1519 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1521 catch(InvalidPositionException &e) {}
1524 if(nodepos.X == blockpos_relative.X){
1526 v3s16 p = blockpos + v3s16(-1,0,0);
1527 addUpdateMeshTask(p, false, urgent);
1529 catch(InvalidPositionException &e){}
1532 if(nodepos.Y == blockpos_relative.Y){
1534 v3s16 p = blockpos + v3s16(0,-1,0);
1535 addUpdateMeshTask(p, false, urgent);
1537 catch(InvalidPositionException &e){}
1540 if(nodepos.Z == blockpos_relative.Z){
1542 v3s16 p = blockpos + v3s16(0,0,-1);
1543 addUpdateMeshTask(p, false, urgent);
1545 catch(InvalidPositionException &e){}
1549 ClientEvent Client::getClientEvent()
1552 if(m_client_event_queue.size() == 0) {
1553 event.type = CE_NONE;
1556 event = m_client_event_queue.front();
1557 m_client_event_queue.pop();
1562 float Client::mediaReceiveProgress()
1564 if (m_media_downloader)
1565 return m_media_downloader->getProgress();
1567 return 1.0; // downloader only exists when not yet done
1570 typedef struct TextureUpdateArgs {
1571 IrrlichtDevice *device;
1572 gui::IGUIEnvironment *guienv;
1575 const wchar_t* text_base;
1576 } TextureUpdateArgs;
1578 void texture_update_progress(void *args, u32 progress, u32 max_progress)
1580 TextureUpdateArgs* targs = (TextureUpdateArgs*) args;
1581 u16 cur_percent = ceil(progress / (double) max_progress * 100.);
1583 // update the loading menu -- if neccessary
1584 bool do_draw = false;
1585 u32 time_ms = targs->last_time_ms;
1586 if (cur_percent != targs->last_percent) {
1587 targs->last_percent = cur_percent;
1588 time_ms = getTimeMs();
1589 // only draw when the user will notice something:
1590 do_draw = (time_ms - targs->last_time_ms > 100);
1594 targs->last_time_ms = time_ms;
1595 std::basic_stringstream<wchar_t> strm;
1596 strm << targs->text_base << " " << targs->last_percent << "%...";
1597 draw_load_screen(strm.str(), targs->device, targs->guienv, 0,
1598 72 + (u16) ((18. / 100.) * (double) targs->last_percent));
1602 void Client::afterContentReceived(IrrlichtDevice *device)
1604 infostream<<"Client::afterContentReceived() started"<<std::endl;
1605 assert(m_itemdef_received); // pre-condition
1606 assert(m_nodedef_received); // pre-condition
1607 assert(mediaReceived()); // pre-condition
1609 const wchar_t* text = wgettext("Loading textures...");
1611 // Clear cached pre-scaled 2D GUI images, as this cache
1612 // might have images with the same name but different
1613 // content from previous sessions.
1614 guiScalingCacheClear(device->getVideoDriver());
1616 // Rebuild inherited images and recreate textures
1617 infostream<<"- Rebuilding images and textures"<<std::endl;
1618 draw_load_screen(text,device, guienv, 0, 70);
1619 m_tsrc->rebuildImagesAndTextures();
1623 infostream<<"- Rebuilding shaders"<<std::endl;
1624 text = wgettext("Rebuilding shaders...");
1625 draw_load_screen(text, device, guienv, 0, 71);
1626 m_shsrc->rebuildShaders();
1629 // Update node aliases
1630 infostream<<"- Updating node aliases"<<std::endl;
1631 text = wgettext("Initializing nodes...");
1632 draw_load_screen(text, device, guienv, 0, 72);
1633 m_nodedef->updateAliases(m_itemdef);
1634 m_nodedef->setNodeRegistrationStatus(true);
1635 m_nodedef->runNodeResolverCallbacks();
1638 // Update node textures and assign shaders to each tile
1639 infostream<<"- Updating node textures"<<std::endl;
1640 TextureUpdateArgs tu_args;
1641 tu_args.device = device;
1642 tu_args.guienv = guienv;
1643 tu_args.last_time_ms = getTimeMs();
1644 tu_args.last_percent = 0;
1645 tu_args.text_base = wgettext("Initializing nodes");
1646 m_nodedef->updateTextures(this, texture_update_progress, &tu_args);
1647 delete[] tu_args.text_base;
1649 // Preload item textures and meshes if configured to
1650 if(g_settings->getBool("preload_item_visuals"))
1652 verbosestream<<"Updating item textures and meshes"<<std::endl;
1653 text = wgettext("Item textures...");
1654 draw_load_screen(text, device, guienv, 0, 0);
1655 std::set<std::string> names = m_itemdef->getAll();
1656 size_t size = names.size();
1659 for(std::set<std::string>::const_iterator
1660 i = names.begin(); i != names.end(); ++i)
1662 // Asking for these caches the result
1663 m_itemdef->getInventoryTexture(*i, this);
1664 m_itemdef->getWieldMesh(*i, this);
1666 percent = (count * 100 / size * 0.2) + 80;
1667 draw_load_screen(text, device, guienv, 0, percent);
1672 // Start mesh update thread after setting up content definitions
1673 infostream<<"- Starting mesh update thread"<<std::endl;
1674 m_mesh_update_thread.Start();
1678 text = wgettext("Done!");
1679 draw_load_screen(text, device, guienv, 0, 100);
1680 infostream<<"Client::afterContentReceived() done"<<std::endl;
1684 float Client::getRTT(void)
1686 return m_con.getPeerStat(PEER_ID_SERVER,con::AVG_RTT);
1689 float Client::getCurRate(void)
1691 return ( m_con.getLocalStat(con::CUR_INC_RATE) +
1692 m_con.getLocalStat(con::CUR_DL_RATE));
1695 float Client::getAvgRate(void)
1697 return ( m_con.getLocalStat(con::AVG_INC_RATE) +
1698 m_con.getLocalStat(con::AVG_DL_RATE));
1701 void Client::makeScreenshot(IrrlichtDevice *device)
1703 irr::video::IVideoDriver *driver = device->getVideoDriver();
1704 irr::video::IImage* const raw_image = driver->createScreenShot();
1709 time_t t = time(NULL);
1710 struct tm *tm = localtime(&t);
1712 char timetstamp_c[64];
1713 strftime(timetstamp_c, sizeof(timetstamp_c), "%FT%T", tm);
1715 std::string filename_base = g_settings->get("screenshot_path")
1717 + std::string("screenshot_")
1718 + std::string(timetstamp_c);
1719 std::string filename_ext = ".png";
1720 std::string filename;
1722 // Try to find a unique filename
1723 unsigned serial = 0;
1725 while (serial < SCREENSHOT_MAX_SERIAL_TRIES) {
1726 filename = filename_base + (serial > 0 ? ("-" + itos(serial)) : "") + filename_ext;
1727 std::ifstream tmp(filename.c_str());
1729 break; // File did not apparently exist, we'll go with it
1733 if (serial == SCREENSHOT_MAX_SERIAL_TRIES) {
1734 infostream << "Could not find suitable filename for screenshot" << std::endl;
1736 irr::video::IImage* const image =
1737 driver->createImage(video::ECF_R8G8B8, raw_image->getDimension());
1740 raw_image->copyTo(image);
1742 std::ostringstream sstr;
1743 if (driver->writeImageToFile(image, filename.c_str())) {
1744 sstr << "Saved screenshot to '" << filename << "'";
1746 sstr << "Failed to save screenshot '" << filename << "'";
1748 m_chat_queue.push(narrow_to_wide(sstr.str()));
1749 infostream << sstr.str() << std::endl;
1757 // IGameDef interface
1759 IItemDefManager* Client::getItemDefManager()
1763 INodeDefManager* Client::getNodeDefManager()
1767 ICraftDefManager* Client::getCraftDefManager()
1770 //return m_craftdef;
1772 ITextureSource* Client::getTextureSource()
1776 IShaderSource* Client::getShaderSource()
1780 scene::ISceneManager* Client::getSceneManager()
1782 return m_device->getSceneManager();
1784 u16 Client::allocateUnknownNodeId(const std::string &name)
1786 errorstream << "Client::allocateUnknownNodeId(): "
1787 << "Client cannot allocate node IDs" << std::endl;
1788 FATAL_ERROR("Client allocated unknown node");
1790 return CONTENT_IGNORE;
1792 ISoundManager* Client::getSoundManager()
1796 MtEventManager* Client::getEventManager()
1801 ParticleManager* Client::getParticleManager()
1803 return &m_particle_manager;
1806 scene::IAnimatedMesh* Client::getMesh(const std::string &filename)
1808 std::map<std::string, std::string>::const_iterator i =
1809 m_mesh_data.find(filename);
1810 if(i == m_mesh_data.end()){
1811 errorstream<<"Client::getMesh(): Mesh not found: \""<<filename<<"\""
1815 const std::string &data = i->second;
1816 scene::ISceneManager *smgr = m_device->getSceneManager();
1818 // Create the mesh, remove it from cache and return it
1819 // This allows unique vertex colors and other properties for each instance
1820 Buffer<char> data_rw(data.c_str(), data.size()); // Const-incorrect Irrlicht
1821 io::IFileSystem *irrfs = m_device->getFileSystem();
1822 io::IReadFile *rfile = irrfs->createMemoryReadFile(
1823 *data_rw, data_rw.getSize(), filename.c_str());
1824 FATAL_ERROR_IF(!rfile, "Could not create/open RAM file");
1826 scene::IAnimatedMesh *mesh = smgr->getMesh(rfile);
1828 // NOTE: By playing with Irrlicht refcounts, maybe we could cache a bunch
1829 // of uniquely named instances and re-use them
1831 smgr->getMeshCache()->removeMesh(mesh);