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"
53 #include "database-sqlite3.h"
55 extern gui::IGUIEnvironment* guienv;
61 QueuedMeshUpdate::QueuedMeshUpdate():
64 ack_block_to_server(false)
68 QueuedMeshUpdate::~QueuedMeshUpdate()
78 MeshUpdateQueue::MeshUpdateQueue()
82 MeshUpdateQueue::~MeshUpdateQueue()
84 JMutexAutoLock lock(m_mutex);
86 for(std::vector<QueuedMeshUpdate*>::iterator
88 i != m_queue.end(); i++)
90 QueuedMeshUpdate *q = *i;
96 peer_id=0 adds with nobody to send to
98 void MeshUpdateQueue::addBlock(v3s16 p, MeshMakeData *data, bool ack_block_to_server, bool urgent)
100 DSTACK(__FUNCTION_NAME);
104 JMutexAutoLock lock(m_mutex);
110 Find if block is already in queue.
111 If it is, update the data and quit.
113 for(std::vector<QueuedMeshUpdate*>::iterator
115 i != m_queue.end(); i++)
117 QueuedMeshUpdate *q = *i;
123 if(ack_block_to_server)
124 q->ack_block_to_server = true;
132 QueuedMeshUpdate *q = new QueuedMeshUpdate;
135 q->ack_block_to_server = ack_block_to_server;
136 m_queue.push_back(q);
139 // Returned pointer must be deleted
140 // Returns NULL if queue is empty
141 QueuedMeshUpdate * MeshUpdateQueue::pop()
143 JMutexAutoLock lock(m_mutex);
145 bool must_be_urgent = !m_urgents.empty();
146 for(std::vector<QueuedMeshUpdate*>::iterator
148 i != m_queue.end(); i++)
150 QueuedMeshUpdate *q = *i;
151 if(must_be_urgent && m_urgents.count(q->p) == 0)
154 m_urgents.erase(q->p);
164 void * MeshUpdateThread::Thread()
168 log_register_thread("MeshUpdateThread");
170 DSTACK(__FUNCTION_NAME);
172 BEGIN_DEBUG_EXCEPTION_HANDLER
174 porting::setThreadName("MeshUpdateThread");
176 while(!StopRequested())
178 QueuedMeshUpdate *q = m_queue_in.pop();
185 ScopeProfiler sp(g_profiler, "Client: Mesh making");
187 MapBlockMesh *mesh_new = new MapBlockMesh(q->data, m_camera_offset);
188 if(mesh_new->getMesh()->getMeshBufferCount() == 0)
197 r.ack_block_to_server = q->ack_block_to_server;
199 m_queue_out.push_back(r);
204 END_DEBUG_EXCEPTION_HANDLER(errorstream)
214 IrrlichtDevice *device,
215 const char *playername,
216 std::string password,
217 MapDrawControl &control,
218 IWritableTextureSource *tsrc,
219 IWritableShaderSource *shsrc,
220 IWritableItemDefManager *itemdef,
221 IWritableNodeDefManager *nodedef,
222 ISoundManager *sound,
223 MtEventManager *event,
226 m_packetcounter_timer(0.0),
227 m_connection_reinit_timer(0.1),
228 m_avg_rtt_timer(0.0),
229 m_playerpos_send_timer(0.0),
230 m_ignore_damage_timer(0.0),
237 m_mesh_update_thread(this),
239 new ClientMap(this, this, control,
240 device->getSceneManager()->getRootSceneNode(),
241 device->getSceneManager(), 666),
242 device->getSceneManager(),
245 m_particle_manager(&m_env),
246 m_con(PROTOCOL_ID, 512, CONNECTION_TIMEOUT, ipv6, this),
248 m_server_ser_ver(SER_FMT_VER_INVALID),
250 m_inventory_updated(false),
251 m_inventory_from_server(NULL),
252 m_inventory_from_server_age(0.0),
253 m_show_highlighted(false),
257 m_highlighted_pos(0,0,0),
259 m_password(password),
260 m_access_denied(false),
261 m_itemdef_received(false),
262 m_nodedef_received(false),
263 m_media_downloader(new ClientMediaDownloader()),
264 m_time_of_day_set(false),
265 m_last_time_of_day_f(-1),
266 m_time_of_day_update_timer(0),
267 m_recommended_send_interval(0.1),
268 m_removed_sounds_check_timer(0),
275 Player *player = new LocalPlayer(this, playername);
277 m_env.addPlayer(player);
280 m_cache_smooth_lighting = g_settings->getBool("smooth_lighting");
281 m_cache_enable_shaders = g_settings->getBool("enable_shaders");
286 //request all client managed threads to stop
287 m_mesh_update_thread.Stop();
288 if (localdb != NULL) {
289 actionstream << "Local map saving ended" << std::endl;
295 bool Client::isShutdown()
298 if (!m_mesh_update_thread.IsRunning()) return true;
307 m_mesh_update_thread.Stop();
308 m_mesh_update_thread.Wait();
309 while(!m_mesh_update_thread.m_queue_out.empty()) {
310 MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_frontNoEx();
315 delete m_inventory_from_server;
317 // Delete detached inventories
318 for(std::map<std::string, Inventory*>::iterator
319 i = m_detached_inventories.begin();
320 i != m_detached_inventories.end(); i++){
324 // cleanup 3d model meshes on client shutdown
325 while (m_device->getSceneManager()->getMeshCache()->getMeshCount() != 0) {
326 scene::IAnimatedMesh * mesh =
327 m_device->getSceneManager()->getMeshCache()->getMeshByIndex(0);
330 m_device->getSceneManager()->getMeshCache()->removeMesh(mesh);
334 void Client::connect(Address address,
335 const std::string &address_name,
336 bool is_local_server)
338 DSTACK(__FUNCTION_NAME);
340 initLocalMapSaving(address, address_name, is_local_server);
342 m_con.SetTimeoutMs(0);
343 m_con.Connect(address);
346 void Client::step(float dtime)
348 DSTACK(__FUNCTION_NAME);
354 if(m_ignore_damage_timer > dtime)
355 m_ignore_damage_timer -= dtime;
357 m_ignore_damage_timer = 0.0;
359 m_animation_time += dtime;
360 if(m_animation_time > 60.0)
361 m_animation_time -= 60.0;
363 m_time_of_day_update_timer += dtime;
371 float &counter = m_packetcounter_timer;
377 infostream << "Client packetcounter (" << m_packetcounter_timer
379 m_packetcounter.print(infostream);
380 m_packetcounter.clear();
384 // UGLY hack to fix 2 second startup delay caused by non existent
385 // server client startup synchronization in local server or singleplayer mode
386 static bool initial_step = true;
388 initial_step = false;
390 else if(m_state == LC_Created) {
391 float &counter = m_connection_reinit_timer;
396 Player *myplayer = m_env.getLocalPlayer();
397 assert(myplayer != NULL);
398 // Send TOSERVER_INIT
399 // [0] u16 TOSERVER_INIT
400 // [2] u8 SER_FMT_VER_HIGHEST_READ
401 // [3] u8[20] player_name
402 // [23] u8[28] password (new in some version)
403 // [51] u16 minimum supported network protocol version (added sometime)
404 // [53] u16 maximum supported network protocol version (added later than the previous one)
406 char pName[PLAYERNAME_SIZE];
407 char pPassword[PASSWORD_SIZE];
409 snprintf(pName, PLAYERNAME_SIZE, "%s", myplayer->getName());
410 snprintf(pPassword, PASSWORD_SIZE, "%s", m_password.c_str());
412 NetworkPacket* pkt = new NetworkPacket(TOSERVER_INIT,
413 1 + PLAYERNAME_SIZE + PASSWORD_SIZE + 2 + 2);
415 *pkt << (u8) SER_FMT_VER_HIGHEST_READ;
416 pkt->putRawString(pName,PLAYERNAME_SIZE);
417 pkt->putRawString(pPassword, PASSWORD_SIZE);
418 *pkt << (u16) CLIENT_PROTOCOL_VERSION_MIN << (u16) CLIENT_PROTOCOL_VERSION_MAX;
423 // Not connected, return
428 Do stuff if connected
432 Run Map's timers and unload unused data
434 const float map_timer_and_unload_dtime = 5.25;
435 if(m_map_timer_and_unload_interval.step(dtime, map_timer_and_unload_dtime)) {
436 ScopeProfiler sp(g_profiler, "Client: map timer and unload");
437 std::vector<v3s16> deleted_blocks;
438 m_env.getMap().timerUpdate(map_timer_and_unload_dtime,
439 g_settings->getFloat("client_unload_unused_data_timeout"),
444 NOTE: This loop is intentionally iterated the way it is.
447 std::vector<v3s16>::iterator i = deleted_blocks.begin();
448 std::vector<v3s16> sendlist;
450 if(sendlist.size() == 255 || i == deleted_blocks.end()) {
460 NetworkPacket* pkt = new NetworkPacket(TOSERVER_DELETEDBLOCKS, 1 + sizeof(v3s16) * sendlist.size());
462 *pkt << (u8) sendlist.size();
465 for(std::vector<v3s16>::iterator
466 j = sendlist.begin();
467 j != sendlist.end(); ++j) {
474 if(i == deleted_blocks.end())
480 sendlist.push_back(*i);
488 // Control local player (0ms)
489 LocalPlayer *player = m_env.getLocalPlayer();
490 assert(player != NULL);
491 player->applyControl(dtime);
500 ClientEnvEvent event = m_env.getClientEvent();
501 if(event.type == CEE_NONE) {
504 else if(event.type == CEE_PLAYER_DAMAGE) {
505 if(m_ignore_damage_timer <= 0) {
506 u8 damage = event.player_damage.amount;
508 if(event.player_damage.send_to_server)
511 // Add to ClientEvent queue
513 event.type = CE_PLAYER_DAMAGE;
514 event.player_damage.amount = damage;
515 m_client_event_queue.push(event);
518 else if(event.type == CEE_PLAYER_BREATH) {
519 u16 breath = event.player_breath.amount;
527 float &counter = m_avg_rtt_timer;
531 // connectedAndInitialized() is true, peer exists.
532 float avg_rtt = getRTT();
533 infostream << "Client: avg_rtt=" << avg_rtt << std::endl;
537 Send player position to server
540 float &counter = m_playerpos_send_timer;
542 if((m_state == LC_Ready) && (counter >= m_recommended_send_interval))
550 Replace updated meshes
553 int num_processed_meshes = 0;
554 while(!m_mesh_update_thread.m_queue_out.empty())
556 num_processed_meshes++;
557 MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_frontNoEx();
558 MapBlock *block = m_env.getMap().getBlockNoCreateNoEx(r.p);
560 // Delete the old mesh
561 if(block->mesh != NULL)
563 // TODO: Remove hardware buffers of meshbuffers of block->mesh
568 // Replace with the new mesh
569 block->mesh = r.mesh;
574 if(r.ack_block_to_server) {
580 NetworkPacket* pkt = new NetworkPacket(TOSERVER_GOTBLOCKS, 1 + 6);
581 *pkt << (u8) 1 << r.p;
586 if(num_processed_meshes > 0)
587 g_profiler->graphAdd("num_processed_meshes", num_processed_meshes);
593 if (m_media_downloader && m_media_downloader->isStarted()) {
594 m_media_downloader->step(this);
595 if (m_media_downloader->isDone()) {
597 delete m_media_downloader;
598 m_media_downloader = NULL;
603 If the server didn't update the inventory in a while, revert
604 the local inventory (so the player notices the lag problem
605 and knows something is wrong).
607 if(m_inventory_from_server)
609 float interval = 10.0;
610 float count_before = floor(m_inventory_from_server_age / interval);
612 m_inventory_from_server_age += dtime;
614 float count_after = floor(m_inventory_from_server_age / interval);
616 if(count_after != count_before)
618 // Do this every <interval> seconds after TOCLIENT_INVENTORY
619 // Reset the locally changed inventory to the authoritative inventory
620 Player *player = m_env.getLocalPlayer();
621 player->inventory = *m_inventory_from_server;
622 m_inventory_updated = true;
627 Update positions of sounds attached to objects
630 for(std::map<int, u16>::iterator
631 i = m_sounds_to_objects.begin();
632 i != m_sounds_to_objects.end(); i++)
634 int client_id = i->first;
635 u16 object_id = i->second;
636 ClientActiveObject *cao = m_env.getActiveObject(object_id);
639 v3f pos = cao->getPosition();
640 m_sound->updateSoundPosition(client_id, pos);
645 Handle removed remotely initiated sounds
647 m_removed_sounds_check_timer += dtime;
648 if(m_removed_sounds_check_timer >= 2.32) {
649 m_removed_sounds_check_timer = 0;
650 // Find removed sounds and clear references to them
651 std::set<s32> removed_server_ids;
652 for(std::map<s32, int>::iterator
653 i = m_sounds_server_to_client.begin();
654 i != m_sounds_server_to_client.end();) {
655 s32 server_id = i->first;
656 int client_id = i->second;
658 if(!m_sound->soundExists(client_id)) {
659 m_sounds_server_to_client.erase(server_id);
660 m_sounds_client_to_server.erase(client_id);
661 m_sounds_to_objects.erase(client_id);
662 removed_server_ids.insert(server_id);
667 if(!removed_server_ids.empty()) {
668 size_t server_ids = removed_server_ids.size();
669 assert(server_ids <= 0xFFFF);
671 NetworkPacket* pkt = new NetworkPacket(TOSERVER_REMOVED_SOUNDS, 2 + server_ids * 4);
673 *pkt << (u16) (server_ids & 0xFFFF);
675 for(std::set<s32>::iterator i = removed_server_ids.begin();
676 i != removed_server_ids.end(); i++)
684 bool Client::loadMedia(const std::string &data, const std::string &filename)
686 // Silly irrlicht's const-incorrectness
687 Buffer<char> data_rw(data.c_str(), data.size());
691 const char *image_ext[] = {
692 ".png", ".jpg", ".bmp", ".tga",
693 ".pcx", ".ppm", ".psd", ".wal", ".rgb",
696 name = removeStringEnd(filename, image_ext);
699 verbosestream<<"Client: Attempting to load image "
700 <<"file \""<<filename<<"\""<<std::endl;
702 io::IFileSystem *irrfs = m_device->getFileSystem();
703 video::IVideoDriver *vdrv = m_device->getVideoDriver();
705 // Create an irrlicht memory file
706 io::IReadFile *rfile = irrfs->createMemoryReadFile(
707 *data_rw, data_rw.getSize(), "_tempreadfile");
710 video::IImage *img = vdrv->createImageFromFile(rfile);
712 errorstream<<"Client: Cannot create image from data of "
713 <<"file \""<<filename<<"\""<<std::endl;
718 m_tsrc->insertSourceImage(filename, img);
725 const char *sound_ext[] = {
726 ".0.ogg", ".1.ogg", ".2.ogg", ".3.ogg", ".4.ogg",
727 ".5.ogg", ".6.ogg", ".7.ogg", ".8.ogg", ".9.ogg",
730 name = removeStringEnd(filename, sound_ext);
733 verbosestream<<"Client: Attempting to load sound "
734 <<"file \""<<filename<<"\""<<std::endl;
735 m_sound->loadSoundData(name, data);
739 const char *model_ext[] = {
740 ".x", ".b3d", ".md2", ".obj",
743 name = removeStringEnd(filename, model_ext);
746 verbosestream<<"Client: Storing model into memory: "
747 <<"\""<<filename<<"\""<<std::endl;
748 if(m_mesh_data.count(filename))
749 errorstream<<"Multiple models with name \""<<filename.c_str()
750 <<"\" found; replacing previous model"<<std::endl;
751 m_mesh_data[filename] = data;
755 errorstream<<"Client: Don't know how to load file \""
756 <<filename<<"\""<<std::endl;
760 // Virtual methods from con::PeerHandler
761 void Client::peerAdded(con::Peer *peer)
763 infostream<<"Client::peerAdded(): peer->id="
764 <<peer->id<<std::endl;
766 void Client::deletingPeer(con::Peer *peer, bool timeout)
768 infostream<<"Client::deletingPeer(): "
769 "Server Peer is getting deleted "
770 <<"(timeout="<<timeout<<")"<<std::endl;
775 u16 number of files requested
781 void Client::request_media(const std::list<std::string> &file_requests)
783 std::ostringstream os(std::ios_base::binary);
784 writeU16(os, TOSERVER_REQUEST_MEDIA);
785 size_t file_requests_size = file_requests.size();
786 assert(file_requests_size <= 0xFFFF);
788 // Packet dynamicly resized
789 NetworkPacket* pkt = new NetworkPacket(TOSERVER_REQUEST_MEDIA, 2 + 0);
791 *pkt << (u16) (file_requests_size & 0xFFFF);
793 for(std::list<std::string>::const_iterator i = file_requests.begin();
794 i != file_requests.end(); ++i) {
800 infostream<<"Client: Sending media request list to server ("
801 <<file_requests.size()<<" files. packet size)"<<std::endl;
804 void Client::received_media()
806 NetworkPacket* pkt = new NetworkPacket(TOSERVER_RECEIVED_MEDIA, 0);
808 infostream<<"Client: Notifying server that we received all media"
812 void Client::initLocalMapSaving(const Address &address,
813 const std::string &hostname,
814 bool is_local_server)
818 if (!g_settings->getBool("enable_local_map_saving") || is_local_server)
821 const std::string world_path = porting::path_user
822 + DIR_DELIM + "worlds"
823 + DIR_DELIM + "server_"
824 + hostname + "_" + to_string(address.getPort());
826 SubgameSpec gamespec;
828 if (!getWorldExists(world_path)) {
829 gamespec = findSubgame(g_settings->get("default_game"));
830 if (!gamespec.isValid())
831 gamespec = findSubgame("minimal");
833 gamespec = findWorldSubgame(world_path);
836 if (!gamespec.isValid()) {
837 errorstream << "Couldn't find subgame for local map saving." << std::endl;
841 localserver = new Server(world_path, gamespec, false, false);
842 localdb = new Database_SQLite3(&(ServerMap&)localserver->getMap(), world_path);
843 localdb->beginSave();
844 actionstream << "Local map saving started, map will be saved at '" << world_path << "'" << std::endl;
847 void Client::ReceiveAll()
849 DSTACK(__FUNCTION_NAME);
850 u32 start_ms = porting::getTimeMs();
853 // Limit time even if there would be huge amounts of data to
855 if(porting::getTimeMs() > start_ms + 100)
860 g_profiler->graphAdd("client_received_packets", 1);
862 catch(con::NoIncomingDataException &e) {
865 catch(con::InvalidIncomingDataException &e) {
866 infostream<<"Client::ReceiveAll(): "
867 "InvalidIncomingDataException: what()="
868 <<e.what()<<std::endl;
873 void Client::Receive()
875 DSTACK(__FUNCTION_NAME);
876 SharedBuffer<u8> data;
878 u32 datasize = m_con.Receive(sender_peer_id, data);
879 ProcessData(*data, datasize, sender_peer_id);
882 inline void Client::handleCommand(NetworkPacket* pkt)
884 const ToClientCommandHandler& opHandle = toClientCommandTable[pkt->getCommand()];
885 (this->*opHandle.handler)(pkt);
889 sender_peer_id given to this shall be quaranteed to be a valid peer
891 void Client::ProcessData(u8 *data, u32 datasize, u16 sender_peer_id)
893 DSTACK(__FUNCTION_NAME);
895 // Ignore packets that don't even fit a command
897 m_packetcounter.add(60000);
901 NetworkPacket* pkt = new NetworkPacket(data, datasize, sender_peer_id);
903 ToClientCommand command = (ToClientCommand) pkt->getCommand();
905 //infostream<<"Client: received command="<<command<<std::endl;
906 m_packetcounter.add((u16)command);
909 If this check is removed, be sure to change the queue
910 system to know the ids
912 if(sender_peer_id != PEER_ID_SERVER) {
913 infostream << "Client::ProcessData(): Discarding data not "
914 "coming from server: peer_id=" << sender_peer_id
920 // Command must be handled into ToClientCommandHandler
921 if (command >= TOCLIENT_NUM_MSG_TYPES) {
922 infostream << "Client: Ignoring unknown command "
923 << command << std::endl;
927 * Those packets are handled before m_server_ser_ver is set, it's normal
928 * But we must use the new ToClientConnectionState in the future,
931 if(toClientCommandTable[command].state == TOCLIENT_STATE_NOT_CONNECTED) {
937 if(m_server_ser_ver == SER_FMT_VER_INVALID) {
938 infostream << "Client: Server serialization"
939 " format invalid or not initialized."
940 " Skipping incoming command=" << command << std::endl;
946 Handle runtime commands
953 void Client::Send(NetworkPacket* pkt)
955 m_con.Send(PEER_ID_SERVER,
956 serverCommandFactoryTable[pkt->getCommand()].channel,
958 serverCommandFactoryTable[pkt->getCommand()].reliable);
962 void Client::interact(u8 action, const PointedThing& pointed)
964 if(m_state != LC_Ready) {
965 errorstream << "Client::interact() "
966 "cancelled (not connected)"
975 [5] u32 length of the next item
976 [9] serialized PointedThing
978 0: start digging (from undersurface) or use
979 1: stop digging (all parameters ignored)
981 3: place block or item (to abovesurface)
985 NetworkPacket* pkt = new NetworkPacket(TOSERVER_INTERACT, 1 + 2 + 0);
988 *pkt << (u16)getPlayerItem();
990 std::ostringstream tmp_os(std::ios::binary);
991 pointed.serialize(tmp_os);
993 pkt->putLongString(tmp_os.str());
998 void Client::sendNodemetaFields(v3s16 p, const std::string &formname,
999 const std::map<std::string, std::string> &fields)
1001 size_t fields_size = fields.size();
1002 assert(fields_size <= 0xFFFF);
1004 NetworkPacket* pkt = new NetworkPacket(TOSERVER_NODEMETA_FIELDS, 0);
1006 *pkt << p << formname << (u16) (fields_size & 0xFFFF);
1008 for(std::map<std::string, std::string>::const_iterator
1009 i = fields.begin(); i != fields.end(); i++) {
1010 const std::string &name = i->first;
1011 const std::string &value = i->second;
1013 pkt->putLongString(value);
1019 void Client::sendInventoryFields(const std::string &formname,
1020 const std::map<std::string, std::string> &fields)
1022 size_t fields_size = fields.size();
1023 assert(fields_size <= 0xFFFF);
1025 NetworkPacket* pkt = new NetworkPacket(TOSERVER_INVENTORY_FIELDS, 0);
1026 *pkt << formname << (u16) (fields_size & 0xFFFF);
1028 for(std::map<std::string, std::string>::const_iterator
1029 i = fields.begin(); i != fields.end(); i++) {
1030 const std::string &name = i->first;
1031 const std::string &value = i->second;
1033 pkt->putLongString(value);
1039 void Client::sendInventoryAction(InventoryAction *a)
1041 std::ostringstream os(std::ios_base::binary);
1046 std::string s = os.str();
1048 NetworkPacket* pkt = new NetworkPacket(TOSERVER_INVENTORY_ACTION, s.size());
1049 pkt->putRawString(s.c_str(),s.size());
1054 void Client::sendChatMessage(const std::wstring &message)
1056 NetworkPacket* pkt = new NetworkPacket(TOSERVER_CHAT_MESSAGE, 2 + message.size() * sizeof(u16));
1063 void Client::sendChangePassword(const std::wstring &oldpassword,
1064 const std::wstring &newpassword)
1066 Player *player = m_env.getLocalPlayer();
1070 std::string playername = player->getName();
1071 std::string oldpwd = translatePassword(playername, oldpassword);
1072 std::string newpwd = translatePassword(playername, newpassword);
1074 NetworkPacket* pkt = new NetworkPacket(TOSERVER_PASSWORD, 2 * PASSWORD_SIZE);
1076 for(u8 i = 0; i < PASSWORD_SIZE; i++) {
1077 *pkt << (u8) (i < oldpwd.length() ? oldpwd[i] : 0);
1080 for(u8 i = 0; i < PASSWORD_SIZE; i++) {
1081 *pkt << (u8) (i < newpwd.length() ? newpwd[i] : 0);
1088 void Client::sendDamage(u8 damage)
1090 DSTACK(__FUNCTION_NAME);
1092 NetworkPacket* pkt = new NetworkPacket(TOSERVER_DAMAGE, sizeof(u8));
1097 void Client::sendBreath(u16 breath)
1099 DSTACK(__FUNCTION_NAME);
1101 NetworkPacket* pkt = new NetworkPacket(TOSERVER_BREATH, sizeof(u16));
1106 void Client::sendRespawn()
1108 DSTACK(__FUNCTION_NAME);
1110 NetworkPacket* pkt = new NetworkPacket(TOSERVER_RESPAWN, 0);
1114 void Client::sendReady()
1116 DSTACK(__FUNCTION_NAME);
1118 NetworkPacket* pkt = new NetworkPacket(TOSERVER_CLIENT_READY,
1119 1 + 1 + 1 + 1 + 2 + sizeof(char) * strlen(minetest_version_hash));
1121 *pkt << (u8) VERSION_MAJOR << (u8) VERSION_MINOR << (u8) VERSION_PATCH_ORIG
1122 << (u8) 0 << (u16) strlen(minetest_version_hash);
1124 pkt->putRawString(minetest_version_hash, (u16) strlen(minetest_version_hash));
1128 void Client::sendPlayerPos()
1130 LocalPlayer *myplayer = m_env.getLocalPlayer();
1131 if(myplayer == NULL)
1134 // Save bandwidth by only updating position when something changed
1135 if(myplayer->last_position == myplayer->getPosition() &&
1136 myplayer->last_speed == myplayer->getSpeed() &&
1137 myplayer->last_pitch == myplayer->getPitch() &&
1138 myplayer->last_yaw == myplayer->getYaw() &&
1139 myplayer->last_keyPressed == myplayer->keyPressed)
1142 myplayer->last_position = myplayer->getPosition();
1143 myplayer->last_speed = myplayer->getSpeed();
1144 myplayer->last_pitch = myplayer->getPitch();
1145 myplayer->last_yaw = myplayer->getYaw();
1146 myplayer->last_keyPressed = myplayer->keyPressed;
1150 //JMutexAutoLock lock(m_con_mutex); //bulk comment-out
1151 our_peer_id = m_con.GetPeerID();
1154 // Set peer id if not set already
1155 if(myplayer->peer_id == PEER_ID_INEXISTENT)
1156 myplayer->peer_id = our_peer_id;
1157 // Check that an existing peer_id is the same as the connection's
1158 assert(myplayer->peer_id == our_peer_id);
1160 v3f pf = myplayer->getPosition();
1161 v3f sf = myplayer->getSpeed();
1162 s32 pitch = myplayer->getPitch() * 100;
1163 s32 yaw = myplayer->getYaw() * 100;
1164 u32 keyPressed = myplayer->keyPressed;
1166 v3s32 position(pf.X*100, pf.Y*100, pf.Z*100);
1167 v3s32 speed(sf.X*100, sf.Y*100, sf.Z*100);
1170 [0] v3s32 position*100
1171 [12] v3s32 speed*100
1172 [12+12] s32 pitch*100
1173 [12+12+4] s32 yaw*100
1174 [12+12+4+4] u32 keyPressed
1177 NetworkPacket* pkt = new NetworkPacket(TOSERVER_PLAYERPOS, 12 + 12 + 4 + 4 + 4);
1179 *pkt << position << speed << pitch << yaw << keyPressed;
1184 void Client::sendPlayerItem(u16 item)
1186 Player *myplayer = m_env.getLocalPlayer();
1187 if(myplayer == NULL)
1190 u16 our_peer_id = m_con.GetPeerID();
1192 // Set peer id if not set already
1193 if(myplayer->peer_id == PEER_ID_INEXISTENT)
1194 myplayer->peer_id = our_peer_id;
1196 // Check that an existing peer_id is the same as the connection's
1197 assert(myplayer->peer_id == our_peer_id);
1199 NetworkPacket* pkt = new NetworkPacket(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];
1316 void Client::inventoryAction(InventoryAction *a)
1319 Send it to the server
1321 sendInventoryAction(a);
1324 Predict some local inventory changes
1326 a->clientApply(this, this);
1332 ClientActiveObject * Client::getSelectedActiveObject(
1334 v3f from_pos_f_on_map,
1335 core::line3d<f32> shootline_on_map
1338 std::vector<DistanceSortedActiveObject> objects;
1340 m_env.getActiveObjects(from_pos_f_on_map, max_d, objects);
1343 // After this, the closest object is the first in the array.
1344 std::sort(objects.begin(), objects.end());
1346 for(unsigned int i=0; i<objects.size(); i++)
1348 ClientActiveObject *obj = objects[i].obj;
1350 core::aabbox3d<f32> *selection_box = obj->getSelectionBox();
1351 if(selection_box == NULL)
1354 v3f pos = obj->getPosition();
1356 core::aabbox3d<f32> offsetted_box(
1357 selection_box->MinEdge + pos,
1358 selection_box->MaxEdge + pos
1361 if(offsetted_box.intersectsWithLine(shootline_on_map))
1370 std::list<std::string> Client::getConnectedPlayerNames()
1372 return m_env.getPlayerNames();
1375 float Client::getAnimationTime()
1377 return m_animation_time;
1380 int Client::getCrackLevel()
1382 return m_crack_level;
1385 void Client::setHighlighted(v3s16 pos, bool show_highlighted)
1387 m_show_highlighted = show_highlighted;
1388 v3s16 old_highlighted_pos = m_highlighted_pos;
1389 m_highlighted_pos = pos;
1390 addUpdateMeshTaskForNode(old_highlighted_pos, false, true);
1391 addUpdateMeshTaskForNode(m_highlighted_pos, false, true);
1394 void Client::setCrack(int level, v3s16 pos)
1396 int old_crack_level = m_crack_level;
1397 v3s16 old_crack_pos = m_crack_pos;
1399 m_crack_level = level;
1402 if(old_crack_level >= 0 && (level < 0 || pos != old_crack_pos))
1405 addUpdateMeshTaskForNode(old_crack_pos, false, true);
1407 if(level >= 0 && (old_crack_level < 0 || pos != old_crack_pos))
1410 addUpdateMeshTaskForNode(pos, false, true);
1416 Player *player = m_env.getLocalPlayer();
1417 assert(player != NULL);
1421 u16 Client::getBreath()
1423 Player *player = m_env.getLocalPlayer();
1424 assert(player != NULL);
1425 return player->getBreath();
1428 bool Client::getChatMessage(std::wstring &message)
1430 if(m_chat_queue.size() == 0)
1432 message = m_chat_queue.front();
1437 void Client::typeChatMessage(const std::wstring &message)
1439 // Discard empty line
1444 sendChatMessage(message);
1447 if (message[0] == L'/')
1449 m_chat_queue.push((std::wstring)L"issued command: " + message);
1453 LocalPlayer *player = m_env.getLocalPlayer();
1454 assert(player != NULL);
1455 std::wstring name = narrow_to_wide(player->getName());
1456 m_chat_queue.push((std::wstring)L"<" + name + L"> " + message);
1460 void Client::addUpdateMeshTask(v3s16 p, bool ack_to_server, bool urgent)
1462 MapBlock *b = m_env.getMap().getBlockNoCreateNoEx(p);
1467 Create a task to update the mesh of the block
1470 MeshMakeData *data = new MeshMakeData(this, m_cache_enable_shaders);
1473 //TimeTaker timer("data fill");
1475 // Debug: 1-6ms, avg=2ms
1477 data->setCrack(m_crack_level, m_crack_pos);
1478 data->setHighlighted(m_highlighted_pos, m_show_highlighted);
1479 data->setSmoothLighting(m_cache_smooth_lighting);
1482 // Add task to queue
1483 m_mesh_update_thread.m_queue_in.addBlock(p, data, ack_to_server, urgent);
1486 void Client::addUpdateMeshTaskWithEdge(v3s16 blockpos, bool ack_to_server, bool urgent)
1489 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1491 catch(InvalidPositionException &e){}
1494 for (int i=0;i<6;i++)
1497 v3s16 p = blockpos + g_6dirs[i];
1498 addUpdateMeshTask(p, false, urgent);
1500 catch(InvalidPositionException &e){}
1504 void Client::addUpdateMeshTaskForNode(v3s16 nodepos, bool ack_to_server, bool urgent)
1508 infostream<<"Client::addUpdateMeshTaskForNode(): "
1509 <<"("<<p.X<<","<<p.Y<<","<<p.Z<<")"
1513 v3s16 blockpos = getNodeBlockPos(nodepos);
1514 v3s16 blockpos_relative = blockpos * MAP_BLOCKSIZE;
1517 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1519 catch(InvalidPositionException &e) {}
1522 if(nodepos.X == blockpos_relative.X){
1524 v3s16 p = blockpos + v3s16(-1,0,0);
1525 addUpdateMeshTask(p, false, urgent);
1527 catch(InvalidPositionException &e){}
1530 if(nodepos.Y == blockpos_relative.Y){
1532 v3s16 p = blockpos + v3s16(0,-1,0);
1533 addUpdateMeshTask(p, false, urgent);
1535 catch(InvalidPositionException &e){}
1538 if(nodepos.Z == blockpos_relative.Z){
1540 v3s16 p = blockpos + v3s16(0,0,-1);
1541 addUpdateMeshTask(p, false, urgent);
1543 catch(InvalidPositionException &e){}
1547 ClientEvent Client::getClientEvent()
1550 if(m_client_event_queue.size() == 0) {
1551 event.type = CE_NONE;
1554 event = m_client_event_queue.front();
1555 m_client_event_queue.pop();
1560 float Client::mediaReceiveProgress()
1562 if (m_media_downloader)
1563 return m_media_downloader->getProgress();
1565 return 1.0; // downloader only exists when not yet done
1568 void Client::afterContentReceived(IrrlichtDevice *device, gui::IGUIFont* font)
1570 infostream<<"Client::afterContentReceived() started"<<std::endl;
1571 assert(m_itemdef_received);
1572 assert(m_nodedef_received);
1573 assert(mediaReceived());
1575 const wchar_t* text = wgettext("Loading textures...");
1577 // Rebuild inherited images and recreate textures
1578 infostream<<"- Rebuilding images and textures"<<std::endl;
1579 draw_load_screen(text,device, guienv, 0, 70);
1580 m_tsrc->rebuildImagesAndTextures();
1584 infostream<<"- Rebuilding shaders"<<std::endl;
1585 text = wgettext("Rebuilding shaders...");
1586 draw_load_screen(text, device, guienv, 0, 75);
1587 m_shsrc->rebuildShaders();
1590 // Update node aliases
1591 infostream<<"- Updating node aliases"<<std::endl;
1592 text = wgettext("Initializing nodes...");
1593 draw_load_screen(text, device, guienv, 0, 80);
1594 m_nodedef->updateAliases(m_itemdef);
1595 m_nodedef->setNodeRegistrationStatus(true);
1596 m_nodedef->runNodeResolverCallbacks();
1599 // Update node textures and assign shaders to each tile
1600 infostream<<"- Updating node textures"<<std::endl;
1601 m_nodedef->updateTextures(this);
1603 // Preload item textures and meshes if configured to
1604 if(g_settings->getBool("preload_item_visuals"))
1606 verbosestream<<"Updating item textures and meshes"<<std::endl;
1607 text = wgettext("Item textures...");
1608 draw_load_screen(text, device, guienv, 0, 0);
1609 std::set<std::string> names = m_itemdef->getAll();
1610 size_t size = names.size();
1613 for(std::set<std::string>::const_iterator
1614 i = names.begin(); i != names.end(); ++i)
1616 // Asking for these caches the result
1617 m_itemdef->getInventoryTexture(*i, this);
1618 m_itemdef->getWieldMesh(*i, this);
1620 percent = (count * 100 / size * 0.2) + 80;
1621 draw_load_screen(text, device, guienv, 0, percent);
1626 // Start mesh update thread after setting up content definitions
1627 infostream<<"- Starting mesh update thread"<<std::endl;
1628 m_mesh_update_thread.Start();
1632 text = wgettext("Done!");
1633 draw_load_screen(text, device, guienv, 0, 100);
1634 infostream<<"Client::afterContentReceived() done"<<std::endl;
1638 float Client::getRTT(void)
1640 return m_con.getPeerStat(PEER_ID_SERVER,con::AVG_RTT);
1643 float Client::getCurRate(void)
1645 return ( m_con.getLocalStat(con::CUR_INC_RATE) +
1646 m_con.getLocalStat(con::CUR_DL_RATE));
1649 float Client::getAvgRate(void)
1651 return ( m_con.getLocalStat(con::AVG_INC_RATE) +
1652 m_con.getLocalStat(con::AVG_DL_RATE));
1655 void Client::makeScreenshot(IrrlichtDevice *device)
1657 irr::video::IVideoDriver *driver = device->getVideoDriver();
1658 irr::video::IImage* const raw_image = driver->createScreenShot();
1660 irr::video::IImage* const image = driver->createImage(video::ECF_R8G8B8,
1661 raw_image->getDimension());
1664 raw_image->copyTo(image);
1665 irr::c8 filename[256];
1666 snprintf(filename, sizeof(filename), "%s" DIR_DELIM "screenshot_%u.png",
1667 g_settings->get("screenshot_path").c_str(),
1668 device->getTimer()->getRealTime());
1669 std::ostringstream sstr;
1670 if (driver->writeImageToFile(image, filename)) {
1671 sstr << "Saved screenshot to '" << filename << "'";
1673 sstr << "Failed to save screenshot '" << filename << "'";
1675 m_chat_queue.push(narrow_to_wide(sstr.str()));
1676 infostream << sstr.str() << std::endl;
1683 // IGameDef interface
1685 IItemDefManager* Client::getItemDefManager()
1689 INodeDefManager* Client::getNodeDefManager()
1693 ICraftDefManager* Client::getCraftDefManager()
1696 //return m_craftdef;
1698 ITextureSource* Client::getTextureSource()
1702 IShaderSource* Client::getShaderSource()
1706 scene::ISceneManager* Client::getSceneManager()
1708 return m_device->getSceneManager();
1710 u16 Client::allocateUnknownNodeId(const std::string &name)
1712 errorstream<<"Client::allocateUnknownNodeId(): "
1713 <<"Client cannot allocate node IDs"<<std::endl;
1715 return CONTENT_IGNORE;
1717 ISoundManager* Client::getSoundManager()
1721 MtEventManager* Client::getEventManager()
1726 ParticleManager* Client::getParticleManager()
1728 return &m_particle_manager;
1731 scene::IAnimatedMesh* Client::getMesh(const std::string &filename)
1733 std::map<std::string, std::string>::const_iterator i =
1734 m_mesh_data.find(filename);
1735 if(i == m_mesh_data.end()){
1736 errorstream<<"Client::getMesh(): Mesh not found: \""<<filename<<"\""
1740 const std::string &data = i->second;
1741 scene::ISceneManager *smgr = m_device->getSceneManager();
1743 // Create the mesh, remove it from cache and return it
1744 // This allows unique vertex colors and other properties for each instance
1745 Buffer<char> data_rw(data.c_str(), data.size()); // Const-incorrect Irrlicht
1746 io::IFileSystem *irrfs = m_device->getFileSystem();
1747 io::IReadFile *rfile = irrfs->createMemoryReadFile(
1748 *data_rw, data_rw.getSize(), filename.c_str());
1751 scene::IAnimatedMesh *mesh = smgr->getMesh(rfile);
1753 // NOTE: By playing with Irrlicht refcounts, maybe we could cache a bunch
1754 // of uniquely named instances and re-use them
1756 smgr->getMeshCache()->removeMesh(mesh);