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"
53 extern gui::IGUIEnvironment* guienv;
59 QueuedMeshUpdate::QueuedMeshUpdate():
62 ack_block_to_server(false)
66 QueuedMeshUpdate::~QueuedMeshUpdate()
76 MeshUpdateQueue::MeshUpdateQueue()
80 MeshUpdateQueue::~MeshUpdateQueue()
82 JMutexAutoLock lock(m_mutex);
84 for(std::vector<QueuedMeshUpdate*>::iterator
86 i != m_queue.end(); i++)
88 QueuedMeshUpdate *q = *i;
94 peer_id=0 adds with nobody to send to
96 void MeshUpdateQueue::addBlock(v3s16 p, MeshMakeData *data, bool ack_block_to_server, bool urgent)
98 DSTACK(__FUNCTION_NAME);
100 assert(data); // pre-condition
102 JMutexAutoLock lock(m_mutex);
108 Find if block is already in queue.
109 If it is, update the data and quit.
111 for(std::vector<QueuedMeshUpdate*>::iterator
113 i != m_queue.end(); i++)
115 QueuedMeshUpdate *q = *i;
121 if(ack_block_to_server)
122 q->ack_block_to_server = true;
130 QueuedMeshUpdate *q = new QueuedMeshUpdate;
133 q->ack_block_to_server = ack_block_to_server;
134 m_queue.push_back(q);
137 // Returned pointer must be deleted
138 // Returns NULL if queue is empty
139 QueuedMeshUpdate * MeshUpdateQueue::pop()
141 JMutexAutoLock lock(m_mutex);
143 bool must_be_urgent = !m_urgents.empty();
144 for(std::vector<QueuedMeshUpdate*>::iterator
146 i != m_queue.end(); i++)
148 QueuedMeshUpdate *q = *i;
149 if(must_be_urgent && m_urgents.count(q->p) == 0)
152 m_urgents.erase(q->p);
162 void * MeshUpdateThread::Thread()
166 log_register_thread("MeshUpdateThread");
168 DSTACK(__FUNCTION_NAME);
170 BEGIN_DEBUG_EXCEPTION_HANDLER
172 porting::setThreadName("MeshUpdateThread");
174 while(!StopRequested())
176 QueuedMeshUpdate *q = m_queue_in.pop();
183 ScopeProfiler sp(g_profiler, "Client: Mesh making");
185 MapBlockMesh *mesh_new = new MapBlockMesh(q->data, m_camera_offset);
186 if(mesh_new->getMesh()->getMeshBufferCount() == 0)
195 r.ack_block_to_server = q->ack_block_to_server;
197 m_queue_out.push_back(r);
202 END_DEBUG_EXCEPTION_HANDLER(errorstream)
212 IrrlichtDevice *device,
213 const char *playername,
214 std::string password,
215 MapDrawControl &control,
216 IWritableTextureSource *tsrc,
217 IWritableShaderSource *shsrc,
218 IWritableItemDefManager *itemdef,
219 IWritableNodeDefManager *nodedef,
220 ISoundManager *sound,
221 MtEventManager *event,
224 m_packetcounter_timer(0.0),
225 m_connection_reinit_timer(0.1),
226 m_avg_rtt_timer(0.0),
227 m_playerpos_send_timer(0.0),
228 m_ignore_damage_timer(0.0),
235 m_mesh_update_thread(this),
237 new ClientMap(this, this, control,
238 device->getSceneManager()->getRootSceneNode(),
239 device->getSceneManager(), 666),
240 device->getSceneManager(),
243 m_particle_manager(&m_env),
244 m_con(PROTOCOL_ID, 512, CONNECTION_TIMEOUT, ipv6, this),
246 m_server_ser_ver(SER_FMT_VER_INVALID),
248 m_inventory_updated(false),
249 m_inventory_from_server(NULL),
250 m_inventory_from_server_age(0.0),
251 m_show_highlighted(false),
255 m_highlighted_pos(0,0,0),
257 m_password(password),
258 m_access_denied(false),
259 m_itemdef_received(false),
260 m_nodedef_received(false),
261 m_media_downloader(new ClientMediaDownloader()),
262 m_time_of_day_set(false),
263 m_last_time_of_day_f(-1),
264 m_time_of_day_update_timer(0),
265 m_recommended_send_interval(0.1),
266 m_removed_sounds_check_timer(0),
271 m_env.addPlayer(new LocalPlayer(this, playername));
273 m_cache_save_interval = g_settings->getU16("server_map_save_interval");
275 m_cache_smooth_lighting = g_settings->getBool("smooth_lighting");
276 m_cache_enable_shaders = g_settings->getBool("enable_shaders");
281 //request all client managed threads to stop
282 m_mesh_update_thread.Stop();
283 // Save local server map
285 infostream << "Local map saving ended." << std::endl;
286 m_localdb->endSave();
290 bool Client::isShutdown()
293 if (!m_mesh_update_thread.IsRunning()) return true;
302 m_mesh_update_thread.Stop();
303 m_mesh_update_thread.Wait();
304 while(!m_mesh_update_thread.m_queue_out.empty()) {
305 MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_frontNoEx();
310 delete m_inventory_from_server;
312 // Delete detached inventories
313 for(std::map<std::string, Inventory*>::iterator
314 i = m_detached_inventories.begin();
315 i != m_detached_inventories.end(); i++){
319 // cleanup 3d model meshes on client shutdown
320 while (m_device->getSceneManager()->getMeshCache()->getMeshCount() != 0) {
321 scene::IAnimatedMesh * mesh =
322 m_device->getSceneManager()->getMeshCache()->getMeshByIndex(0);
325 m_device->getSceneManager()->getMeshCache()->removeMesh(mesh);
329 void Client::connect(Address address,
330 const std::string &address_name,
331 bool is_local_server)
333 DSTACK(__FUNCTION_NAME);
335 initLocalMapSaving(address, address_name, is_local_server);
337 m_con.SetTimeoutMs(0);
338 m_con.Connect(address);
341 void Client::step(float dtime)
343 DSTACK(__FUNCTION_NAME);
349 if(m_ignore_damage_timer > dtime)
350 m_ignore_damage_timer -= dtime;
352 m_ignore_damage_timer = 0.0;
354 m_animation_time += dtime;
355 if(m_animation_time > 60.0)
356 m_animation_time -= 60.0;
358 m_time_of_day_update_timer += dtime;
366 float &counter = m_packetcounter_timer;
372 infostream << "Client packetcounter (" << m_packetcounter_timer
374 m_packetcounter.print(infostream);
375 m_packetcounter.clear();
379 // UGLY hack to fix 2 second startup delay caused by non existent
380 // server client startup synchronization in local server or singleplayer mode
381 static bool initial_step = true;
383 initial_step = false;
385 else if(m_state == LC_Created) {
386 float &counter = m_connection_reinit_timer;
391 Player *myplayer = m_env.getLocalPlayer();
392 FATAL_ERROR_IF(myplayer == NULL, "Local player not found in environment.");
394 // Send TOSERVER_INIT
395 // [0] u16 TOSERVER_INIT
396 // [2] u8 SER_FMT_VER_HIGHEST_READ
397 // [3] u8[20] player_name
398 // [23] u8[28] password (new in some version)
399 // [51] u16 minimum supported network protocol version (added sometime)
400 // [53] u16 maximum supported network protocol version (added later than the previous one)
402 char pName[PLAYERNAME_SIZE];
403 char pPassword[PASSWORD_SIZE];
404 memset(pName, 0, PLAYERNAME_SIZE * sizeof(char));
405 memset(pPassword, 0, PASSWORD_SIZE * sizeof(char));
407 snprintf(pName, PLAYERNAME_SIZE, "%s", myplayer->getName());
408 snprintf(pPassword, PASSWORD_SIZE, "%s", m_password.c_str());
410 sendLegacyInit(pName, pPassword);
413 // Not connected, return
418 Do stuff if connected
422 Run Map's timers and unload unused data
424 const float map_timer_and_unload_dtime = 5.25;
425 if(m_map_timer_and_unload_interval.step(dtime, map_timer_and_unload_dtime)) {
426 ScopeProfiler sp(g_profiler, "Client: map timer and unload");
427 std::vector<v3s16> deleted_blocks;
428 m_env.getMap().timerUpdate(map_timer_and_unload_dtime,
429 g_settings->getFloat("client_unload_unused_data_timeout"),
434 NOTE: This loop is intentionally iterated the way it is.
437 std::vector<v3s16>::iterator i = deleted_blocks.begin();
438 std::vector<v3s16> sendlist;
440 if(sendlist.size() == 255 || i == deleted_blocks.end()) {
451 sendDeletedBlocks(sendlist);
453 if(i == deleted_blocks.end())
459 sendlist.push_back(*i);
467 // Control local player (0ms)
468 LocalPlayer *player = m_env.getLocalPlayer();
469 assert(player != NULL);
470 player->applyControl(dtime);
479 ClientEnvEvent event = m_env.getClientEvent();
480 if(event.type == CEE_NONE) {
483 else if(event.type == CEE_PLAYER_DAMAGE) {
484 if(m_ignore_damage_timer <= 0) {
485 u8 damage = event.player_damage.amount;
487 if(event.player_damage.send_to_server)
490 // Add to ClientEvent queue
492 event.type = CE_PLAYER_DAMAGE;
493 event.player_damage.amount = damage;
494 m_client_event_queue.push(event);
497 else if(event.type == CEE_PLAYER_BREATH) {
498 u16 breath = event.player_breath.amount;
506 float &counter = m_avg_rtt_timer;
510 // connectedAndInitialized() is true, peer exists.
511 float avg_rtt = getRTT();
512 infostream << "Client: avg_rtt=" << avg_rtt << std::endl;
516 Send player position to server
519 float &counter = m_playerpos_send_timer;
521 if((m_state == LC_Ready) && (counter >= m_recommended_send_interval))
529 Replace updated meshes
532 int num_processed_meshes = 0;
533 while(!m_mesh_update_thread.m_queue_out.empty())
535 num_processed_meshes++;
536 MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_frontNoEx();
537 MapBlock *block = m_env.getMap().getBlockNoCreateNoEx(r.p);
539 // Delete the old mesh
540 if(block->mesh != NULL)
542 // TODO: Remove hardware buffers of meshbuffers of block->mesh
547 // Replace with the new mesh
548 block->mesh = r.mesh;
553 if(r.ack_block_to_server) {
563 if(num_processed_meshes > 0)
564 g_profiler->graphAdd("num_processed_meshes", num_processed_meshes);
570 if (m_media_downloader && m_media_downloader->isStarted()) {
571 m_media_downloader->step(this);
572 if (m_media_downloader->isDone()) {
574 delete m_media_downloader;
575 m_media_downloader = NULL;
580 If the server didn't update the inventory in a while, revert
581 the local inventory (so the player notices the lag problem
582 and knows something is wrong).
584 if(m_inventory_from_server)
586 float interval = 10.0;
587 float count_before = floor(m_inventory_from_server_age / interval);
589 m_inventory_from_server_age += dtime;
591 float count_after = floor(m_inventory_from_server_age / interval);
593 if(count_after != count_before)
595 // Do this every <interval> seconds after TOCLIENT_INVENTORY
596 // Reset the locally changed inventory to the authoritative inventory
597 Player *player = m_env.getLocalPlayer();
598 player->inventory = *m_inventory_from_server;
599 m_inventory_updated = true;
604 Update positions of sounds attached to objects
607 for(std::map<int, u16>::iterator
608 i = m_sounds_to_objects.begin();
609 i != m_sounds_to_objects.end(); i++)
611 int client_id = i->first;
612 u16 object_id = i->second;
613 ClientActiveObject *cao = m_env.getActiveObject(object_id);
616 v3f pos = cao->getPosition();
617 m_sound->updateSoundPosition(client_id, pos);
622 Handle removed remotely initiated sounds
624 m_removed_sounds_check_timer += dtime;
625 if(m_removed_sounds_check_timer >= 2.32) {
626 m_removed_sounds_check_timer = 0;
627 // Find removed sounds and clear references to them
628 std::vector<s32> removed_server_ids;
629 for(std::map<s32, int>::iterator
630 i = m_sounds_server_to_client.begin();
631 i != m_sounds_server_to_client.end();) {
632 s32 server_id = i->first;
633 int client_id = i->second;
635 if(!m_sound->soundExists(client_id)) {
636 m_sounds_server_to_client.erase(server_id);
637 m_sounds_client_to_server.erase(client_id);
638 m_sounds_to_objects.erase(client_id);
639 removed_server_ids.push_back(server_id);
644 if(!removed_server_ids.empty()) {
645 sendRemovedSounds(removed_server_ids);
650 if (m_localdb && m_localdb_save_interval.step(dtime,
651 m_cache_save_interval)) {
652 m_localdb->endSave();
653 m_localdb->beginSave();
657 bool Client::loadMedia(const std::string &data, const std::string &filename)
659 // Silly irrlicht's const-incorrectness
660 Buffer<char> data_rw(data.c_str(), data.size());
664 const char *image_ext[] = {
665 ".png", ".jpg", ".bmp", ".tga",
666 ".pcx", ".ppm", ".psd", ".wal", ".rgb",
669 name = removeStringEnd(filename, image_ext);
672 verbosestream<<"Client: Attempting to load image "
673 <<"file \""<<filename<<"\""<<std::endl;
675 io::IFileSystem *irrfs = m_device->getFileSystem();
676 video::IVideoDriver *vdrv = m_device->getVideoDriver();
678 // Create an irrlicht memory file
679 io::IReadFile *rfile = irrfs->createMemoryReadFile(
680 *data_rw, data_rw.getSize(), "_tempreadfile");
682 FATAL_ERROR_IF(!rfile, "Could not create irrlicht memory file.");
685 video::IImage *img = vdrv->createImageFromFile(rfile);
687 errorstream<<"Client: Cannot create image from data of "
688 <<"file \""<<filename<<"\""<<std::endl;
693 m_tsrc->insertSourceImage(filename, img);
700 const char *sound_ext[] = {
701 ".0.ogg", ".1.ogg", ".2.ogg", ".3.ogg", ".4.ogg",
702 ".5.ogg", ".6.ogg", ".7.ogg", ".8.ogg", ".9.ogg",
705 name = removeStringEnd(filename, sound_ext);
708 verbosestream<<"Client: Attempting to load sound "
709 <<"file \""<<filename<<"\""<<std::endl;
710 m_sound->loadSoundData(name, data);
714 const char *model_ext[] = {
715 ".x", ".b3d", ".md2", ".obj",
718 name = removeStringEnd(filename, model_ext);
721 verbosestream<<"Client: Storing model into memory: "
722 <<"\""<<filename<<"\""<<std::endl;
723 if(m_mesh_data.count(filename))
724 errorstream<<"Multiple models with name \""<<filename.c_str()
725 <<"\" found; replacing previous model"<<std::endl;
726 m_mesh_data[filename] = data;
730 errorstream<<"Client: Don't know how to load file \""
731 <<filename<<"\""<<std::endl;
735 // Virtual methods from con::PeerHandler
736 void Client::peerAdded(con::Peer *peer)
738 infostream<<"Client::peerAdded(): peer->id="
739 <<peer->id<<std::endl;
741 void Client::deletingPeer(con::Peer *peer, bool timeout)
743 infostream<<"Client::deletingPeer(): "
744 "Server Peer is getting deleted "
745 <<"(timeout="<<timeout<<")"<<std::endl;
750 u16 number of files requested
756 void Client::request_media(const std::vector<std::string> &file_requests)
758 std::ostringstream os(std::ios_base::binary);
759 writeU16(os, TOSERVER_REQUEST_MEDIA);
760 size_t file_requests_size = file_requests.size();
762 FATAL_ERROR_IF(file_requests_size > 0xFFFF, "Unsupported number of file requests");
764 // Packet dynamicly resized
765 NetworkPacket pkt(TOSERVER_REQUEST_MEDIA, 2 + 0);
767 pkt << (u16) (file_requests_size & 0xFFFF);
769 for(std::vector<std::string>::const_iterator i = file_requests.begin();
770 i != file_requests.end(); ++i) {
776 infostream << "Client: Sending media request list to server ("
777 << file_requests.size() << " files. packet size)" << std::endl;
780 void Client::received_media()
782 NetworkPacket pkt(TOSERVER_RECEIVED_MEDIA, 0);
784 infostream << "Client: Notifying server that we received all media"
788 void Client::initLocalMapSaving(const Address &address,
789 const std::string &hostname,
790 bool is_local_server)
792 if (!g_settings->getBool("enable_local_map_saving") || is_local_server) {
796 const std::string world_path = porting::path_user
797 + DIR_DELIM + "worlds"
798 + DIR_DELIM + "server_"
799 + hostname + "_" + to_string(address.getPort());
801 fs::CreateAllDirs(world_path);
803 m_localdb = new Database_SQLite3(world_path);
804 m_localdb->beginSave();
805 actionstream << "Local map saving started, map will be saved at '" << world_path << "'" << std::endl;
808 void Client::ReceiveAll()
810 DSTACK(__FUNCTION_NAME);
811 u32 start_ms = porting::getTimeMs();
814 // Limit time even if there would be huge amounts of data to
816 if(porting::getTimeMs() > start_ms + 100)
821 g_profiler->graphAdd("client_received_packets", 1);
823 catch(con::NoIncomingDataException &e) {
826 catch(con::InvalidIncomingDataException &e) {
827 infostream<<"Client::ReceiveAll(): "
828 "InvalidIncomingDataException: what()="
829 <<e.what()<<std::endl;
834 void Client::Receive()
836 DSTACK(__FUNCTION_NAME);
842 inline void Client::handleCommand(NetworkPacket* pkt)
844 const ToClientCommandHandler& opHandle = toClientCommandTable[pkt->getCommand()];
845 (this->*opHandle.handler)(pkt);
849 sender_peer_id given to this shall be quaranteed to be a valid peer
851 void Client::ProcessData(NetworkPacket *pkt)
853 DSTACK(__FUNCTION_NAME);
855 ToClientCommand command = (ToClientCommand) pkt->getCommand();
856 u32 sender_peer_id = pkt->getPeerId();
858 //infostream<<"Client: received command="<<command<<std::endl;
859 m_packetcounter.add((u16)command);
862 If this check is removed, be sure to change the queue
863 system to know the ids
865 if(sender_peer_id != PEER_ID_SERVER) {
866 infostream << "Client::ProcessData(): Discarding data not "
867 "coming from server: peer_id=" << sender_peer_id
872 // Command must be handled into ToClientCommandHandler
873 if (command >= TOCLIENT_NUM_MSG_TYPES) {
874 infostream << "Client: Ignoring unknown command "
875 << command << std::endl;
879 * Those packets are handled before m_server_ser_ver is set, it's normal
880 * But we must use the new ToClientConnectionState in the future,
883 if(toClientCommandTable[command].state == TOCLIENT_STATE_NOT_CONNECTED) {
888 if(m_server_ser_ver == SER_FMT_VER_INVALID) {
889 infostream << "Client: Server serialization"
890 " format invalid or not initialized."
891 " Skipping incoming command=" << command << std::endl;
896 Handle runtime commands
902 void Client::Send(NetworkPacket* pkt)
904 m_con.Send(PEER_ID_SERVER,
905 serverCommandFactoryTable[pkt->getCommand()].channel,
907 serverCommandFactoryTable[pkt->getCommand()].reliable);
910 void Client::interact(u8 action, const PointedThing& pointed)
912 if(m_state != LC_Ready) {
913 errorstream << "Client::interact() "
914 "Canceled (not connected)"
923 [5] u32 length of the next item
924 [9] serialized PointedThing
926 0: start digging (from undersurface) or use
927 1: stop digging (all parameters ignored)
929 3: place block or item (to abovesurface)
933 NetworkPacket pkt(TOSERVER_INTERACT, 1 + 2 + 0);
936 pkt << (u16)getPlayerItem();
938 std::ostringstream tmp_os(std::ios::binary);
939 pointed.serialize(tmp_os);
941 pkt.putLongString(tmp_os.str());
946 void Client::sendLegacyInit(const char* playerName, const char* playerPassword)
948 NetworkPacket pkt(TOSERVER_INIT_LEGACY,
949 1 + PLAYERNAME_SIZE + PASSWORD_SIZE + 2 + 2);
951 pkt << (u8) SER_FMT_VER_HIGHEST_READ;
952 pkt.putRawString(playerName,PLAYERNAME_SIZE);
953 pkt.putRawString(playerPassword, PASSWORD_SIZE);
954 pkt << (u16) CLIENT_PROTOCOL_VERSION_MIN << (u16) CLIENT_PROTOCOL_VERSION_MAX;
959 void Client::sendDeletedBlocks(std::vector<v3s16> &blocks)
961 NetworkPacket pkt(TOSERVER_DELETEDBLOCKS, 1 + sizeof(v3s16) * blocks.size());
963 pkt << (u8) blocks.size();
966 for(std::vector<v3s16>::iterator
968 j != blocks.end(); ++j) {
976 void Client::sendGotBlocks(v3s16 block)
978 NetworkPacket pkt(TOSERVER_GOTBLOCKS, 1 + 6);
979 pkt << (u8) 1 << block;
983 void Client::sendRemovedSounds(std::vector<s32> &soundList)
985 size_t server_ids = soundList.size();
986 assert(server_ids <= 0xFFFF);
988 NetworkPacket pkt(TOSERVER_REMOVED_SOUNDS, 2 + server_ids * 4);
990 pkt << (u16) (server_ids & 0xFFFF);
992 for(std::vector<s32>::iterator i = soundList.begin();
993 i != soundList.end(); i++)
999 void Client::sendNodemetaFields(v3s16 p, const std::string &formname,
1000 const std::map<std::string, std::string> &fields)
1002 size_t fields_size = fields.size();
1004 FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of nodemeta fields");
1006 NetworkPacket pkt(TOSERVER_NODEMETA_FIELDS, 0);
1008 pkt << p << formname << (u16) (fields_size & 0xFFFF);
1010 for(std::map<std::string, std::string>::const_iterator
1011 i = fields.begin(); i != fields.end(); i++) {
1012 const std::string &name = i->first;
1013 const std::string &value = i->second;
1015 pkt.putLongString(value);
1021 void Client::sendInventoryFields(const std::string &formname,
1022 const std::map<std::string, std::string> &fields)
1024 size_t fields_size = fields.size();
1025 FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of inventory fields");
1027 NetworkPacket pkt(TOSERVER_INVENTORY_FIELDS, 0);
1028 pkt << formname << (u16) (fields_size & 0xFFFF);
1030 for(std::map<std::string, std::string>::const_iterator
1031 i = fields.begin(); i != fields.end(); i++) {
1032 const std::string &name = i->first;
1033 const std::string &value = i->second;
1035 pkt.putLongString(value);
1041 void Client::sendInventoryAction(InventoryAction *a)
1043 std::ostringstream os(std::ios_base::binary);
1048 std::string s = os.str();
1050 NetworkPacket pkt(TOSERVER_INVENTORY_ACTION, s.size());
1051 pkt.putRawString(s.c_str(),s.size());
1056 void Client::sendChatMessage(const std::wstring &message)
1058 NetworkPacket pkt(TOSERVER_CHAT_MESSAGE, 2 + message.size() * sizeof(u16));
1065 void Client::sendChangePassword(const std::wstring &oldpassword,
1066 const std::wstring &newpassword)
1068 Player *player = m_env.getLocalPlayer();
1072 std::string playername = player->getName();
1073 std::string oldpwd = translatePassword(playername, oldpassword);
1074 std::string newpwd = translatePassword(playername, newpassword);
1076 NetworkPacket pkt(TOSERVER_PASSWORD_LEGACY, 2 * PASSWORD_SIZE);
1078 for(u8 i = 0; i < PASSWORD_SIZE; i++) {
1079 pkt << (u8) (i < oldpwd.length() ? oldpwd[i] : 0);
1082 for(u8 i = 0; i < PASSWORD_SIZE; i++) {
1083 pkt << (u8) (i < newpwd.length() ? newpwd[i] : 0);
1090 void Client::sendDamage(u8 damage)
1092 DSTACK(__FUNCTION_NAME);
1094 NetworkPacket pkt(TOSERVER_DAMAGE, sizeof(u8));
1099 void Client::sendBreath(u16 breath)
1101 DSTACK(__FUNCTION_NAME);
1103 NetworkPacket pkt(TOSERVER_BREATH, sizeof(u16));
1108 void Client::sendRespawn()
1110 DSTACK(__FUNCTION_NAME);
1112 NetworkPacket pkt(TOSERVER_RESPAWN, 0);
1116 void Client::sendReady()
1118 DSTACK(__FUNCTION_NAME);
1120 NetworkPacket pkt(TOSERVER_CLIENT_READY,
1121 1 + 1 + 1 + 1 + 2 + sizeof(char) * strlen(g_version_hash));
1123 pkt << (u8) VERSION_MAJOR << (u8) VERSION_MINOR << (u8) VERSION_PATCH
1124 << (u8) 0 << (u16) strlen(g_version_hash);
1126 pkt.putRawString(g_version_hash, (u16) strlen(g_version_hash));
1130 void Client::sendPlayerPos()
1132 LocalPlayer *myplayer = m_env.getLocalPlayer();
1133 if(myplayer == NULL)
1136 // Save bandwidth by only updating position when something changed
1137 if(myplayer->last_position == myplayer->getPosition() &&
1138 myplayer->last_speed == myplayer->getSpeed() &&
1139 myplayer->last_pitch == myplayer->getPitch() &&
1140 myplayer->last_yaw == myplayer->getYaw() &&
1141 myplayer->last_keyPressed == myplayer->keyPressed)
1144 myplayer->last_position = myplayer->getPosition();
1145 myplayer->last_speed = myplayer->getSpeed();
1146 myplayer->last_pitch = myplayer->getPitch();
1147 myplayer->last_yaw = myplayer->getYaw();
1148 myplayer->last_keyPressed = myplayer->keyPressed;
1152 //JMutexAutoLock lock(m_con_mutex); //bulk comment-out
1153 our_peer_id = m_con.GetPeerID();
1156 // Set peer id if not set already
1157 if(myplayer->peer_id == PEER_ID_INEXISTENT)
1158 myplayer->peer_id = our_peer_id;
1160 assert(myplayer->peer_id == our_peer_id);
1162 v3f pf = myplayer->getPosition();
1163 v3f sf = myplayer->getSpeed();
1164 s32 pitch = myplayer->getPitch() * 100;
1165 s32 yaw = myplayer->getYaw() * 100;
1166 u32 keyPressed = myplayer->keyPressed;
1168 v3s32 position(pf.X*100, pf.Y*100, pf.Z*100);
1169 v3s32 speed(sf.X*100, sf.Y*100, sf.Z*100);
1172 [0] v3s32 position*100
1173 [12] v3s32 speed*100
1174 [12+12] s32 pitch*100
1175 [12+12+4] s32 yaw*100
1176 [12+12+4+4] u32 keyPressed
1179 NetworkPacket pkt(TOSERVER_PLAYERPOS, 12 + 12 + 4 + 4 + 4);
1181 pkt << position << speed << pitch << yaw << keyPressed;
1186 void Client::sendPlayerItem(u16 item)
1188 Player *myplayer = m_env.getLocalPlayer();
1189 if(myplayer == NULL)
1192 u16 our_peer_id = m_con.GetPeerID();
1194 // Set peer id if not set already
1195 if(myplayer->peer_id == PEER_ID_INEXISTENT)
1196 myplayer->peer_id = our_peer_id;
1197 assert(myplayer->peer_id == our_peer_id);
1199 NetworkPacket pkt(TOSERVER_PLAYERITEM, 2);
1206 void Client::removeNode(v3s16 p)
1208 std::map<v3s16, MapBlock*> modified_blocks;
1211 m_env.getMap().removeNodeAndUpdate(p, modified_blocks);
1213 catch(InvalidPositionException &e) {
1216 for(std::map<v3s16, MapBlock *>::iterator
1217 i = modified_blocks.begin();
1218 i != modified_blocks.end(); ++i) {
1219 addUpdateMeshTaskWithEdge(i->first, false, true);
1223 void Client::addNode(v3s16 p, MapNode n, bool remove_metadata)
1225 //TimeTaker timer1("Client::addNode()");
1227 std::map<v3s16, MapBlock*> modified_blocks;
1230 //TimeTaker timer3("Client::addNode(): addNodeAndUpdate");
1231 m_env.getMap().addNodeAndUpdate(p, n, modified_blocks, remove_metadata);
1233 catch(InvalidPositionException &e) {
1236 for(std::map<v3s16, MapBlock *>::iterator
1237 i = modified_blocks.begin();
1238 i != modified_blocks.end(); ++i) {
1239 addUpdateMeshTaskWithEdge(i->first, false, true);
1243 void Client::setPlayerControl(PlayerControl &control)
1245 LocalPlayer *player = m_env.getLocalPlayer();
1246 assert(player != NULL);
1247 player->control = control;
1250 void Client::selectPlayerItem(u16 item)
1252 m_playeritem = item;
1253 m_inventory_updated = true;
1254 sendPlayerItem(item);
1257 // Returns true if the inventory of the local player has been
1258 // updated from the server. If it is true, it is set to false.
1259 bool Client::getLocalInventoryUpdated()
1261 bool updated = m_inventory_updated;
1262 m_inventory_updated = false;
1266 // Copies the inventory of the local player to parameter
1267 void Client::getLocalInventory(Inventory &dst)
1269 Player *player = m_env.getLocalPlayer();
1270 assert(player != NULL);
1271 dst = player->inventory;
1274 Inventory* Client::getInventory(const InventoryLocation &loc)
1277 case InventoryLocation::UNDEFINED:
1280 case InventoryLocation::CURRENT_PLAYER:
1282 Player *player = m_env.getLocalPlayer();
1283 assert(player != NULL);
1284 return &player->inventory;
1287 case InventoryLocation::PLAYER:
1289 Player *player = m_env.getPlayer(loc.name.c_str());
1292 return &player->inventory;
1295 case InventoryLocation::NODEMETA:
1297 NodeMetadata *meta = m_env.getMap().getNodeMetadata(loc.p);
1300 return meta->getInventory();
1303 case InventoryLocation::DETACHED:
1305 if(m_detached_inventories.count(loc.name) == 0)
1307 return m_detached_inventories[loc.name];
1311 FATAL_ERROR("Invalid inventory location type.");
1317 void Client::inventoryAction(InventoryAction *a)
1320 Send it to the server
1322 sendInventoryAction(a);
1325 Predict some local inventory changes
1327 a->clientApply(this, this);
1333 ClientActiveObject * Client::getSelectedActiveObject(
1335 v3f from_pos_f_on_map,
1336 core::line3d<f32> shootline_on_map
1339 std::vector<DistanceSortedActiveObject> objects;
1341 m_env.getActiveObjects(from_pos_f_on_map, max_d, objects);
1344 // After this, the closest object is the first in the array.
1345 std::sort(objects.begin(), objects.end());
1347 for(unsigned int i=0; i<objects.size(); i++)
1349 ClientActiveObject *obj = objects[i].obj;
1351 core::aabbox3d<f32> *selection_box = obj->getSelectionBox();
1352 if(selection_box == NULL)
1355 v3f pos = obj->getPosition();
1357 core::aabbox3d<f32> offsetted_box(
1358 selection_box->MinEdge + pos,
1359 selection_box->MaxEdge + pos
1362 if(offsetted_box.intersectsWithLine(shootline_on_map))
1371 std::list<std::string> Client::getConnectedPlayerNames()
1373 return m_env.getPlayerNames();
1376 float Client::getAnimationTime()
1378 return m_animation_time;
1381 int Client::getCrackLevel()
1383 return m_crack_level;
1386 void Client::setHighlighted(v3s16 pos, bool show_highlighted)
1388 m_show_highlighted = show_highlighted;
1389 v3s16 old_highlighted_pos = m_highlighted_pos;
1390 m_highlighted_pos = pos;
1391 addUpdateMeshTaskForNode(old_highlighted_pos, false, true);
1392 addUpdateMeshTaskForNode(m_highlighted_pos, false, true);
1395 void Client::setCrack(int level, v3s16 pos)
1397 int old_crack_level = m_crack_level;
1398 v3s16 old_crack_pos = m_crack_pos;
1400 m_crack_level = level;
1403 if(old_crack_level >= 0 && (level < 0 || pos != old_crack_pos))
1406 addUpdateMeshTaskForNode(old_crack_pos, false, true);
1408 if(level >= 0 && (old_crack_level < 0 || pos != old_crack_pos))
1411 addUpdateMeshTaskForNode(pos, false, true);
1417 Player *player = m_env.getLocalPlayer();
1418 assert(player != NULL);
1422 u16 Client::getBreath()
1424 Player *player = m_env.getLocalPlayer();
1425 assert(player != NULL);
1426 return player->getBreath();
1429 bool Client::getChatMessage(std::wstring &message)
1431 if(m_chat_queue.size() == 0)
1433 message = m_chat_queue.front();
1438 void Client::typeChatMessage(const std::wstring &message)
1440 // Discard empty line
1445 sendChatMessage(message);
1448 if (message[0] == L'/')
1450 m_chat_queue.push((std::wstring)L"issued command: " + message);
1454 LocalPlayer *player = m_env.getLocalPlayer();
1455 assert(player != NULL);
1456 std::wstring name = narrow_to_wide(player->getName());
1457 m_chat_queue.push((std::wstring)L"<" + name + L"> " + message);
1461 void Client::addUpdateMeshTask(v3s16 p, bool ack_to_server, bool urgent)
1463 MapBlock *b = m_env.getMap().getBlockNoCreateNoEx(p);
1468 Create a task to update the mesh of the block
1471 MeshMakeData *data = new MeshMakeData(this, m_cache_enable_shaders);
1474 //TimeTaker timer("data fill");
1476 // Debug: 1-6ms, avg=2ms
1478 data->setCrack(m_crack_level, m_crack_pos);
1479 data->setHighlighted(m_highlighted_pos, m_show_highlighted);
1480 data->setSmoothLighting(m_cache_smooth_lighting);
1483 // Add task to queue
1484 m_mesh_update_thread.m_queue_in.addBlock(p, data, ack_to_server, urgent);
1487 void Client::addUpdateMeshTaskWithEdge(v3s16 blockpos, bool ack_to_server, bool urgent)
1490 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1492 catch(InvalidPositionException &e){}
1495 for (int i=0;i<6;i++)
1498 v3s16 p = blockpos + g_6dirs[i];
1499 addUpdateMeshTask(p, false, urgent);
1501 catch(InvalidPositionException &e){}
1505 void Client::addUpdateMeshTaskForNode(v3s16 nodepos, bool ack_to_server, bool urgent)
1509 infostream<<"Client::addUpdateMeshTaskForNode(): "
1510 <<"("<<p.X<<","<<p.Y<<","<<p.Z<<")"
1514 v3s16 blockpos = getNodeBlockPos(nodepos);
1515 v3s16 blockpos_relative = blockpos * MAP_BLOCKSIZE;
1518 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1520 catch(InvalidPositionException &e) {}
1523 if(nodepos.X == blockpos_relative.X){
1525 v3s16 p = blockpos + v3s16(-1,0,0);
1526 addUpdateMeshTask(p, false, urgent);
1528 catch(InvalidPositionException &e){}
1531 if(nodepos.Y == blockpos_relative.Y){
1533 v3s16 p = blockpos + v3s16(0,-1,0);
1534 addUpdateMeshTask(p, false, urgent);
1536 catch(InvalidPositionException &e){}
1539 if(nodepos.Z == blockpos_relative.Z){
1541 v3s16 p = blockpos + v3s16(0,0,-1);
1542 addUpdateMeshTask(p, false, urgent);
1544 catch(InvalidPositionException &e){}
1548 ClientEvent Client::getClientEvent()
1551 if(m_client_event_queue.size() == 0) {
1552 event.type = CE_NONE;
1555 event = m_client_event_queue.front();
1556 m_client_event_queue.pop();
1561 float Client::mediaReceiveProgress()
1563 if (m_media_downloader)
1564 return m_media_downloader->getProgress();
1566 return 1.0; // downloader only exists when not yet done
1569 typedef struct TextureUpdateArgs {
1570 IrrlichtDevice *device;
1571 gui::IGUIEnvironment *guienv;
1574 const wchar_t* text_base;
1575 } TextureUpdateArgs;
1577 void texture_update_progress(void *args, u32 progress, u32 max_progress)
1579 TextureUpdateArgs* targs = (TextureUpdateArgs*) args;
1580 u16 cur_percent = ceil(progress / (double) max_progress * 100.);
1582 // update the loading menu -- if neccessary
1583 bool do_draw = false;
1584 u32 time_ms = targs->last_time_ms;
1585 if (cur_percent != targs->last_percent) {
1586 targs->last_percent = cur_percent;
1587 time_ms = getTimeMs();
1588 // only draw when the user will notice something:
1589 do_draw = (time_ms - targs->last_time_ms > 100);
1593 targs->last_time_ms = time_ms;
1594 std::basic_stringstream<wchar_t> strm;
1595 strm << targs->text_base << " " << targs->last_percent << "%...";
1596 draw_load_screen(strm.str(), targs->device, targs->guienv, 0,
1597 72 + (u16) ((18. / 100.) * (double) targs->last_percent));
1601 void Client::afterContentReceived(IrrlichtDevice *device)
1603 infostream<<"Client::afterContentReceived() started"<<std::endl;
1604 assert(m_itemdef_received); // pre-condition
1605 assert(m_nodedef_received); // pre-condition
1606 assert(mediaReceived()); // pre-condition
1608 const wchar_t* text = wgettext("Loading textures...");
1610 // Rebuild inherited images and recreate textures
1611 infostream<<"- Rebuilding images and textures"<<std::endl;
1612 draw_load_screen(text,device, guienv, 0, 70);
1613 m_tsrc->rebuildImagesAndTextures();
1617 infostream<<"- Rebuilding shaders"<<std::endl;
1618 text = wgettext("Rebuilding shaders...");
1619 draw_load_screen(text, device, guienv, 0, 71);
1620 m_shsrc->rebuildShaders();
1623 // Update node aliases
1624 infostream<<"- Updating node aliases"<<std::endl;
1625 text = wgettext("Initializing nodes...");
1626 draw_load_screen(text, device, guienv, 0, 72);
1627 m_nodedef->updateAliases(m_itemdef);
1628 m_nodedef->setNodeRegistrationStatus(true);
1629 m_nodedef->runNodeResolverCallbacks();
1632 // Update node textures and assign shaders to each tile
1633 infostream<<"- Updating node textures"<<std::endl;
1634 TextureUpdateArgs tu_args;
1635 tu_args.device = device;
1636 tu_args.guienv = guienv;
1637 tu_args.last_time_ms = getTimeMs();
1638 tu_args.last_percent = 0;
1639 tu_args.text_base = wgettext("Initializing nodes");
1640 m_nodedef->updateTextures(this, texture_update_progress, &tu_args);
1641 delete[] tu_args.text_base;
1643 // Preload item textures and meshes if configured to
1644 if(g_settings->getBool("preload_item_visuals"))
1646 verbosestream<<"Updating item textures and meshes"<<std::endl;
1647 text = wgettext("Item textures...");
1648 draw_load_screen(text, device, guienv, 0, 0);
1649 std::set<std::string> names = m_itemdef->getAll();
1650 size_t size = names.size();
1653 for(std::set<std::string>::const_iterator
1654 i = names.begin(); i != names.end(); ++i)
1656 // Asking for these caches the result
1657 m_itemdef->getInventoryTexture(*i, this);
1658 m_itemdef->getWieldMesh(*i, this);
1660 percent = (count * 100 / size * 0.2) + 80;
1661 draw_load_screen(text, device, guienv, 0, percent);
1666 // Start mesh update thread after setting up content definitions
1667 infostream<<"- Starting mesh update thread"<<std::endl;
1668 m_mesh_update_thread.Start();
1672 text = wgettext("Done!");
1673 draw_load_screen(text, device, guienv, 0, 100);
1674 infostream<<"Client::afterContentReceived() done"<<std::endl;
1678 float Client::getRTT(void)
1680 return m_con.getPeerStat(PEER_ID_SERVER,con::AVG_RTT);
1683 float Client::getCurRate(void)
1685 return ( m_con.getLocalStat(con::CUR_INC_RATE) +
1686 m_con.getLocalStat(con::CUR_DL_RATE));
1689 float Client::getAvgRate(void)
1691 return ( m_con.getLocalStat(con::AVG_INC_RATE) +
1692 m_con.getLocalStat(con::AVG_DL_RATE));
1695 void Client::makeScreenshot(IrrlichtDevice *device)
1697 irr::video::IVideoDriver *driver = device->getVideoDriver();
1698 irr::video::IImage* const raw_image = driver->createScreenShot();
1703 time_t t = time(NULL);
1704 struct tm *tm = localtime(&t);
1706 char timetstamp_c[64];
1707 strftime(timetstamp_c, sizeof(timetstamp_c), "%FT%T", tm);
1709 std::string filename_base = g_settings->get("screenshot_path")
1711 + std::string("screenshot_")
1712 + std::string(timetstamp_c);
1713 std::string filename_ext = ".png";
1714 std::string filename;
1716 // Try to find a unique filename
1717 unsigned serial = 0;
1719 while (serial < SCREENSHOT_MAX_SERIAL_TRIES) {
1720 filename = filename_base + (serial > 0 ? ("-" + itos(serial)) : "") + filename_ext;
1721 std::ifstream tmp(filename.c_str());
1723 break; // File did not apparently exist, we'll go with it
1727 if (serial == SCREENSHOT_MAX_SERIAL_TRIES) {
1728 infostream << "Could not find suitable filename for screenshot" << std::endl;
1730 irr::video::IImage* const image =
1731 driver->createImage(video::ECF_R8G8B8, raw_image->getDimension());
1734 raw_image->copyTo(image);
1736 std::ostringstream sstr;
1737 if (driver->writeImageToFile(image, filename.c_str())) {
1738 sstr << "Saved screenshot to '" << filename << "'";
1740 sstr << "Failed to save screenshot '" << filename << "'";
1742 m_chat_queue.push(narrow_to_wide(sstr.str()));
1743 infostream << sstr.str() << std::endl;
1751 // IGameDef interface
1753 IItemDefManager* Client::getItemDefManager()
1757 INodeDefManager* Client::getNodeDefManager()
1761 ICraftDefManager* Client::getCraftDefManager()
1764 //return m_craftdef;
1766 ITextureSource* Client::getTextureSource()
1770 IShaderSource* Client::getShaderSource()
1774 scene::ISceneManager* Client::getSceneManager()
1776 return m_device->getSceneManager();
1778 u16 Client::allocateUnknownNodeId(const std::string &name)
1780 errorstream << "Client::allocateUnknownNodeId(): "
1781 << "Client cannot allocate node IDs" << std::endl;
1782 FATAL_ERROR("Client allocated unknown node");
1784 return CONTENT_IGNORE;
1786 ISoundManager* Client::getSoundManager()
1790 MtEventManager* Client::getEventManager()
1795 ParticleManager* Client::getParticleManager()
1797 return &m_particle_manager;
1800 scene::IAnimatedMesh* Client::getMesh(const std::string &filename)
1802 std::map<std::string, std::string>::const_iterator i =
1803 m_mesh_data.find(filename);
1804 if(i == m_mesh_data.end()){
1805 errorstream<<"Client::getMesh(): Mesh not found: \""<<filename<<"\""
1809 const std::string &data = i->second;
1810 scene::ISceneManager *smgr = m_device->getSceneManager();
1812 // Create the mesh, remove it from cache and return it
1813 // This allows unique vertex colors and other properties for each instance
1814 Buffer<char> data_rw(data.c_str(), data.size()); // Const-incorrect Irrlicht
1815 io::IFileSystem *irrfs = m_device->getFileSystem();
1816 io::IReadFile *rfile = irrfs->createMemoryReadFile(
1817 *data_rw, data_rw.getSize(), filename.c_str());
1818 FATAL_ERROR_IF(!rfile, "Could not create/open RAM file");
1820 scene::IAnimatedMesh *mesh = smgr->getMesh(rfile);
1822 // NOTE: By playing with Irrlicht refcounts, maybe we could cache a bunch
1823 // of uniquely named instances and re-use them
1825 smgr->getMeshCache()->removeMesh(mesh);