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;
422 /*SharedBuffer<u8> data(2 + 1 + PLAYERNAME_SIZE + PASSWORD_SIZE + 2 + 2);
423 writeU16(&data[0], TOSERVER_INIT);
424 writeU8(&data[2], SER_FMT_VER_HIGHEST_READ);
426 memset((char*)&data[3], 0, PLAYERNAME_SIZE);
427 snprintf((char*)&data[3], PLAYERNAME_SIZE, "%s", myplayer->getName());
429 memset((char*)&data[23], 0, PASSWORD_SIZE);
430 snprintf((char*)&data[23], PASSWORD_SIZE, "%s", m_password.c_str());
432 writeU16(&data[51], CLIENT_PROTOCOL_VERSION_MIN);
433 writeU16(&data[53], CLIENT_PROTOCOL_VERSION_MAX);
435 // Send as unreliable
436 Send(1, data, false);*/
439 // Not connected, return
444 Do stuff if connected
448 Run Map's timers and unload unused data
450 const float map_timer_and_unload_dtime = 5.25;
451 if(m_map_timer_and_unload_interval.step(dtime, map_timer_and_unload_dtime)) {
452 ScopeProfiler sp(g_profiler, "Client: map timer and unload");
453 std::list<v3s16> deleted_blocks;
454 m_env.getMap().timerUpdate(map_timer_and_unload_dtime,
455 g_settings->getFloat("client_unload_unused_data_timeout"),
460 NOTE: This loop is intentionally iterated the way it is.
463 std::list<v3s16>::iterator i = deleted_blocks.begin();
464 std::list<v3s16> sendlist;
466 if(sendlist.size() == 255 || i == deleted_blocks.end()) {
476 NetworkPacket* pkt = new NetworkPacket(TOSERVER_DELETEDBLOCKS, 1 + sizeof(v3s16) * sendlist.size());
478 *pkt << (u8) sendlist.size();
481 for(std::list<v3s16>::iterator
482 j = sendlist.begin();
483 j != sendlist.end(); ++j) {
490 if(i == deleted_blocks.end())
496 sendlist.push_back(*i);
504 // Control local player (0ms)
505 LocalPlayer *player = m_env.getLocalPlayer();
506 assert(player != NULL);
507 player->applyControl(dtime);
516 ClientEnvEvent event = m_env.getClientEvent();
517 if(event.type == CEE_NONE) {
520 else if(event.type == CEE_PLAYER_DAMAGE) {
521 if(m_ignore_damage_timer <= 0) {
522 u8 damage = event.player_damage.amount;
524 if(event.player_damage.send_to_server)
527 // Add to ClientEvent queue
529 event.type = CE_PLAYER_DAMAGE;
530 event.player_damage.amount = damage;
531 m_client_event_queue.push_back(event);
534 else if(event.type == CEE_PLAYER_BREATH) {
535 u16 breath = event.player_breath.amount;
543 float &counter = m_avg_rtt_timer;
547 // connectedAndInitialized() is true, peer exists.
548 float avg_rtt = getRTT();
549 infostream << "Client: avg_rtt=" << avg_rtt << std::endl;
553 Send player position to server
556 float &counter = m_playerpos_send_timer;
558 if((m_state == LC_Ready) && (counter >= m_recommended_send_interval))
566 Replace updated meshes
569 int num_processed_meshes = 0;
570 while(!m_mesh_update_thread.m_queue_out.empty())
572 num_processed_meshes++;
573 MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_frontNoEx();
574 MapBlock *block = m_env.getMap().getBlockNoCreateNoEx(r.p);
576 // Delete the old mesh
577 if(block->mesh != NULL)
579 // TODO: Remove hardware buffers of meshbuffers of block->mesh
584 // Replace with the new mesh
585 block->mesh = r.mesh;
590 if(r.ack_block_to_server) {
596 NetworkPacket* pkt = new NetworkPacket(TOSERVER_GOTBLOCKS, 1 + 6);
597 *pkt << (u8) 1 << r.p;
602 if(num_processed_meshes > 0)
603 g_profiler->graphAdd("num_processed_meshes", num_processed_meshes);
609 if (m_media_downloader && m_media_downloader->isStarted()) {
610 m_media_downloader->step(this);
611 if (m_media_downloader->isDone()) {
613 delete m_media_downloader;
614 m_media_downloader = NULL;
619 If the server didn't update the inventory in a while, revert
620 the local inventory (so the player notices the lag problem
621 and knows something is wrong).
623 if(m_inventory_from_server)
625 float interval = 10.0;
626 float count_before = floor(m_inventory_from_server_age / interval);
628 m_inventory_from_server_age += dtime;
630 float count_after = floor(m_inventory_from_server_age / interval);
632 if(count_after != count_before)
634 // Do this every <interval> seconds after TOCLIENT_INVENTORY
635 // Reset the locally changed inventory to the authoritative inventory
636 Player *player = m_env.getLocalPlayer();
637 player->inventory = *m_inventory_from_server;
638 m_inventory_updated = true;
643 Update positions of sounds attached to objects
646 for(std::map<int, u16>::iterator
647 i = m_sounds_to_objects.begin();
648 i != m_sounds_to_objects.end(); i++)
650 int client_id = i->first;
651 u16 object_id = i->second;
652 ClientActiveObject *cao = m_env.getActiveObject(object_id);
655 v3f pos = cao->getPosition();
656 m_sound->updateSoundPosition(client_id, pos);
661 Handle removed remotely initiated sounds
663 m_removed_sounds_check_timer += dtime;
664 if(m_removed_sounds_check_timer >= 2.32) {
665 m_removed_sounds_check_timer = 0;
666 // Find removed sounds and clear references to them
667 std::set<s32> removed_server_ids;
668 for(std::map<s32, int>::iterator
669 i = m_sounds_server_to_client.begin();
670 i != m_sounds_server_to_client.end();) {
671 s32 server_id = i->first;
672 int client_id = i->second;
674 if(!m_sound->soundExists(client_id)) {
675 m_sounds_server_to_client.erase(server_id);
676 m_sounds_client_to_server.erase(client_id);
677 m_sounds_to_objects.erase(client_id);
678 removed_server_ids.insert(server_id);
683 if(!removed_server_ids.empty()) {
684 size_t server_ids = removed_server_ids.size();
685 assert(server_ids <= 0xFFFF);
687 NetworkPacket* pkt = new NetworkPacket(TOSERVER_REMOVED_SOUNDS, 2 + server_ids * 4);
689 *pkt << (u16) (server_ids & 0xFFFF);
691 for(std::set<s32>::iterator i = removed_server_ids.begin();
692 i != removed_server_ids.end(); i++)
700 bool Client::loadMedia(const std::string &data, const std::string &filename)
702 // Silly irrlicht's const-incorrectness
703 Buffer<char> data_rw(data.c_str(), data.size());
707 const char *image_ext[] = {
708 ".png", ".jpg", ".bmp", ".tga",
709 ".pcx", ".ppm", ".psd", ".wal", ".rgb",
712 name = removeStringEnd(filename, image_ext);
715 verbosestream<<"Client: Attempting to load image "
716 <<"file \""<<filename<<"\""<<std::endl;
718 io::IFileSystem *irrfs = m_device->getFileSystem();
719 video::IVideoDriver *vdrv = m_device->getVideoDriver();
721 // Create an irrlicht memory file
722 io::IReadFile *rfile = irrfs->createMemoryReadFile(
723 *data_rw, data_rw.getSize(), "_tempreadfile");
726 video::IImage *img = vdrv->createImageFromFile(rfile);
728 errorstream<<"Client: Cannot create image from data of "
729 <<"file \""<<filename<<"\""<<std::endl;
734 m_tsrc->insertSourceImage(filename, img);
741 const char *sound_ext[] = {
742 ".0.ogg", ".1.ogg", ".2.ogg", ".3.ogg", ".4.ogg",
743 ".5.ogg", ".6.ogg", ".7.ogg", ".8.ogg", ".9.ogg",
746 name = removeStringEnd(filename, sound_ext);
749 verbosestream<<"Client: Attempting to load sound "
750 <<"file \""<<filename<<"\""<<std::endl;
751 m_sound->loadSoundData(name, data);
755 const char *model_ext[] = {
756 ".x", ".b3d", ".md2", ".obj",
759 name = removeStringEnd(filename, model_ext);
762 verbosestream<<"Client: Storing model into memory: "
763 <<"\""<<filename<<"\""<<std::endl;
764 if(m_mesh_data.count(filename))
765 errorstream<<"Multiple models with name \""<<filename.c_str()
766 <<"\" found; replacing previous model"<<std::endl;
767 m_mesh_data[filename] = data;
771 errorstream<<"Client: Don't know how to load file \""
772 <<filename<<"\""<<std::endl;
776 // Virtual methods from con::PeerHandler
777 void Client::peerAdded(con::Peer *peer)
779 infostream<<"Client::peerAdded(): peer->id="
780 <<peer->id<<std::endl;
782 void Client::deletingPeer(con::Peer *peer, bool timeout)
784 infostream<<"Client::deletingPeer(): "
785 "Server Peer is getting deleted "
786 <<"(timeout="<<timeout<<")"<<std::endl;
791 u16 number of files requested
797 void Client::request_media(const std::list<std::string> &file_requests)
799 std::ostringstream os(std::ios_base::binary);
800 writeU16(os, TOSERVER_REQUEST_MEDIA);
801 size_t file_requests_size = file_requests.size();
802 assert(file_requests_size <= 0xFFFF);
804 // Packet dynamicly resized
805 NetworkPacket* pkt = new NetworkPacket(TOSERVER_REQUEST_MEDIA, 2 + 0);
807 *pkt << (u16) (file_requests_size & 0xFFFF);
809 for(std::list<std::string>::const_iterator i = file_requests.begin();
810 i != file_requests.end(); ++i) {
816 infostream<<"Client: Sending media request list to server ("
817 <<file_requests.size()<<" files. packet size)"<<std::endl;
820 void Client::received_media()
822 NetworkPacket* pkt = new NetworkPacket(TOSERVER_RECEIVED_MEDIA, 0);
824 infostream<<"Client: Notifying server that we received all media"
828 void Client::initLocalMapSaving(const Address &address,
829 const std::string &hostname,
830 bool is_local_server)
834 if (!g_settings->getBool("enable_local_map_saving") || is_local_server)
837 const std::string world_path = porting::path_user
838 + DIR_DELIM + "worlds"
839 + DIR_DELIM + "server_"
840 + hostname + "_" + to_string(address.getPort());
842 SubgameSpec gamespec;
844 if (!getWorldExists(world_path)) {
845 gamespec = findSubgame(g_settings->get("default_game"));
846 if (!gamespec.isValid())
847 gamespec = findSubgame("minimal");
849 gamespec = findWorldSubgame(world_path);
852 if (!gamespec.isValid()) {
853 errorstream << "Couldn't find subgame for local map saving." << std::endl;
857 localserver = new Server(world_path, gamespec, false, false);
858 localdb = new Database_SQLite3(&(ServerMap&)localserver->getMap(), world_path);
859 localdb->beginSave();
860 actionstream << "Local map saving started, map will be saved at '" << world_path << "'" << std::endl;
863 void Client::ReceiveAll()
865 DSTACK(__FUNCTION_NAME);
866 u32 start_ms = porting::getTimeMs();
869 // Limit time even if there would be huge amounts of data to
871 if(porting::getTimeMs() > start_ms + 100)
876 g_profiler->graphAdd("client_received_packets", 1);
878 catch(con::NoIncomingDataException &e) {
881 catch(con::InvalidIncomingDataException &e) {
882 infostream<<"Client::ReceiveAll(): "
883 "InvalidIncomingDataException: what()="
884 <<e.what()<<std::endl;
889 void Client::Receive()
891 DSTACK(__FUNCTION_NAME);
892 SharedBuffer<u8> data;
894 u32 datasize = m_con.Receive(sender_peer_id, data);
895 ProcessData(*data, datasize, sender_peer_id);
898 inline void Client::handleCommand(NetworkPacket* pkt)
900 const ToClientCommandHandler& opHandle = toClientCommandTable[pkt->getCommand()];
901 (this->*opHandle.handler)(pkt);
905 sender_peer_id given to this shall be quaranteed to be a valid peer
907 void Client::ProcessData(u8 *data, u32 datasize, u16 sender_peer_id)
909 DSTACK(__FUNCTION_NAME);
911 // Ignore packets that don't even fit a command
913 m_packetcounter.add(60000);
917 NetworkPacket* pkt = new NetworkPacket(data, datasize, sender_peer_id);
919 ToClientCommand command = (ToClientCommand) pkt->getCommand();
921 //infostream<<"Client: received command="<<command<<std::endl;
922 m_packetcounter.add((u16)command);
925 If this check is removed, be sure to change the queue
926 system to know the ids
928 if(sender_peer_id != PEER_ID_SERVER) {
929 infostream << "Client::ProcessData(): Discarding data not "
930 "coming from server: peer_id=" << sender_peer_id
936 // Command must be handled into ToClientCommandHandler
937 if (command >= TOCLIENT_NUM_MSG_TYPES) {
938 infostream << "Client: Ignoring unknown command "
939 << command << std::endl;
943 * Those packets are handled before m_server_ser_ver is set, it's normal
944 * But we must use the new ToClientConnectionState in the future,
947 if(toClientCommandTable[command].state == TOCLIENT_STATE_NOT_CONNECTED) {
953 if(m_server_ser_ver == SER_FMT_VER_INVALID) {
954 infostream << "Client: Server serialization"
955 " format invalid or not initialized."
956 " Skipping incoming command=" << command << std::endl;
962 Handle runtime commands
969 void Client::Send(NetworkPacket* pkt)
971 m_con.Send(PEER_ID_SERVER,
972 serverCommandFactoryTable[pkt->getCommand()].channel,
974 serverCommandFactoryTable[pkt->getCommand()].reliable);
977 void Client::interact(u8 action, const PointedThing& pointed)
979 if(m_state != LC_Ready) {
980 errorstream << "Client::interact() "
981 "cancelled (not connected)"
990 [5] u32 length of the next item
991 [9] serialized PointedThing
993 0: start digging (from undersurface) or use
994 1: stop digging (all parameters ignored)
996 3: place block or item (to abovesurface)
1000 NetworkPacket* pkt = new NetworkPacket(TOSERVER_INTERACT, 1 + 2 + 0);
1003 *pkt << (u16)getPlayerItem();
1005 std::ostringstream tmp_os(std::ios::binary);
1006 pointed.serialize(tmp_os);
1008 pkt->putLongString(tmp_os.str());
1013 void Client::sendNodemetaFields(v3s16 p, const std::string &formname,
1014 const std::map<std::string, std::string> &fields)
1016 size_t fields_size = fields.size();
1017 assert(fields_size <= 0xFFFF);
1019 NetworkPacket* pkt = new NetworkPacket(TOSERVER_NODEMETA_FIELDS, 0);
1021 *pkt << p << formname << (u16) (fields_size & 0xFFFF);
1023 for(std::map<std::string, std::string>::const_iterator
1024 i = fields.begin(); i != fields.end(); i++) {
1025 const std::string &name = i->first;
1026 const std::string &value = i->second;
1028 pkt->putLongString(value);
1034 void Client::sendInventoryFields(const std::string &formname,
1035 const std::map<std::string, std::string> &fields)
1037 size_t fields_size = fields.size();
1038 assert(fields_size <= 0xFFFF);
1040 NetworkPacket* pkt = new NetworkPacket(TOSERVER_INVENTORY_FIELDS, 0);
1041 *pkt << formname << (u16) (fields_size & 0xFFFF);
1043 for(std::map<std::string, std::string>::const_iterator
1044 i = fields.begin(); i != fields.end(); i++) {
1045 const std::string &name = i->first;
1046 const std::string &value = i->second;
1048 pkt->putLongString(value);
1054 void Client::sendInventoryAction(InventoryAction *a)
1056 std::ostringstream os(std::ios_base::binary);
1061 std::string s = os.str();
1063 NetworkPacket* pkt = new NetworkPacket(TOSERVER_INVENTORY_ACTION, s.size());
1064 pkt->putRawString(s.c_str(),s.size());
1069 void Client::sendChatMessage(const std::wstring &message)
1071 NetworkPacket* pkt = new NetworkPacket(TOSERVER_CHAT_MESSAGE, 2 + message.size() * sizeof(u16));
1078 void Client::sendChangePassword(const std::wstring &oldpassword,
1079 const std::wstring &newpassword)
1081 Player *player = m_env.getLocalPlayer();
1085 std::string playername = player->getName();
1086 std::string oldpwd = translatePassword(playername, oldpassword);
1087 std::string newpwd = translatePassword(playername, newpassword);
1089 NetworkPacket* pkt = new NetworkPacket(TOSERVER_PASSWORD, 2 * PASSWORD_SIZE);
1091 for(u8 i = 0; i < PASSWORD_SIZE; i++) {
1092 *pkt << (u8) (i < oldpwd.length() ? oldpwd[i] : 0);
1095 for(u8 i = 0; i < PASSWORD_SIZE; i++) {
1096 *pkt << (u8) (i < newpwd.length() ? newpwd[i] : 0);
1103 void Client::sendDamage(u8 damage)
1105 DSTACK(__FUNCTION_NAME);
1107 NetworkPacket* pkt = new NetworkPacket(TOSERVER_DAMAGE, sizeof(u8));
1112 void Client::sendBreath(u16 breath)
1114 DSTACK(__FUNCTION_NAME);
1116 NetworkPacket* pkt = new NetworkPacket(TOSERVER_BREATH, sizeof(u16));
1121 void Client::sendRespawn()
1123 DSTACK(__FUNCTION_NAME);
1125 NetworkPacket* pkt = new NetworkPacket(TOSERVER_RESPAWN, 0);
1129 void Client::sendReady()
1131 DSTACK(__FUNCTION_NAME);
1133 NetworkPacket* pkt = new NetworkPacket(TOSERVER_CLIENT_READY,
1134 1 + 1 + 1 + 1 + 2 + sizeof(char) * strlen(minetest_version_hash));
1136 *pkt << (u8) VERSION_MAJOR << (u8) VERSION_MINOR << (u8) VERSION_PATCH_ORIG
1137 << (u8) 0 << (u16) strlen(minetest_version_hash);
1139 pkt->putRawString(minetest_version_hash, (u16) strlen(minetest_version_hash));
1143 void Client::sendPlayerPos()
1145 LocalPlayer *myplayer = m_env.getLocalPlayer();
1146 if(myplayer == NULL)
1149 // Save bandwidth by only updating position when something changed
1150 if(myplayer->last_position == myplayer->getPosition() &&
1151 myplayer->last_speed == myplayer->getSpeed() &&
1152 myplayer->last_pitch == myplayer->getPitch() &&
1153 myplayer->last_yaw == myplayer->getYaw() &&
1154 myplayer->last_keyPressed == myplayer->keyPressed)
1157 myplayer->last_position = myplayer->getPosition();
1158 myplayer->last_speed = myplayer->getSpeed();
1159 myplayer->last_pitch = myplayer->getPitch();
1160 myplayer->last_yaw = myplayer->getYaw();
1161 myplayer->last_keyPressed = myplayer->keyPressed;
1165 //JMutexAutoLock lock(m_con_mutex); //bulk comment-out
1166 our_peer_id = m_con.GetPeerID();
1169 // Set peer id if not set already
1170 if(myplayer->peer_id == PEER_ID_INEXISTENT)
1171 myplayer->peer_id = our_peer_id;
1172 // Check that an existing peer_id is the same as the connection's
1173 assert(myplayer->peer_id == our_peer_id);
1175 v3f pf = myplayer->getPosition();
1176 v3f sf = myplayer->getSpeed();
1177 s32 pitch = myplayer->getPitch() * 100;
1178 s32 yaw = myplayer->getYaw() * 100;
1179 u32 keyPressed = myplayer->keyPressed;
1181 v3s32 position(pf.X*100, pf.Y*100, pf.Z*100);
1182 v3s32 speed(sf.X*100, sf.Y*100, sf.Z*100);
1185 [0] v3s32 position*100
1186 [12] v3s32 speed*100
1187 [12+12] s32 pitch*100
1188 [12+12+4] s32 yaw*100
1189 [12+12+4+4] u32 keyPressed
1192 NetworkPacket* pkt = new NetworkPacket(TOSERVER_PLAYERPOS, 12 + 12 + 4 + 4 + 4);
1194 *pkt << position << speed << pitch << yaw << keyPressed;
1199 void Client::sendPlayerItem(u16 item)
1201 Player *myplayer = m_env.getLocalPlayer();
1202 if(myplayer == NULL)
1205 u16 our_peer_id = m_con.GetPeerID();
1207 // Set peer id if not set already
1208 if(myplayer->peer_id == PEER_ID_INEXISTENT)
1209 myplayer->peer_id = our_peer_id;
1211 // Check that an existing peer_id is the same as the connection's
1212 assert(myplayer->peer_id == our_peer_id);
1214 NetworkPacket* pkt = new NetworkPacket(TOSERVER_PLAYERITEM, 2);
1221 void Client::removeNode(v3s16 p)
1223 std::map<v3s16, MapBlock*> modified_blocks;
1226 m_env.getMap().removeNodeAndUpdate(p, modified_blocks);
1228 catch(InvalidPositionException &e) {
1231 for(std::map<v3s16, MapBlock *>::iterator
1232 i = modified_blocks.begin();
1233 i != modified_blocks.end(); ++i) {
1234 addUpdateMeshTaskWithEdge(i->first, false, true);
1238 void Client::addNode(v3s16 p, MapNode n, bool remove_metadata)
1240 //TimeTaker timer1("Client::addNode()");
1242 std::map<v3s16, MapBlock*> modified_blocks;
1245 //TimeTaker timer3("Client::addNode(): addNodeAndUpdate");
1246 m_env.getMap().addNodeAndUpdate(p, n, modified_blocks, remove_metadata);
1248 catch(InvalidPositionException &e) {
1251 for(std::map<v3s16, MapBlock *>::iterator
1252 i = modified_blocks.begin();
1253 i != modified_blocks.end(); ++i) {
1254 addUpdateMeshTaskWithEdge(i->first, false, true);
1258 void Client::setPlayerControl(PlayerControl &control)
1260 LocalPlayer *player = m_env.getLocalPlayer();
1261 assert(player != NULL);
1262 player->control = control;
1265 void Client::selectPlayerItem(u16 item)
1267 m_playeritem = item;
1268 m_inventory_updated = true;
1269 sendPlayerItem(item);
1272 // Returns true if the inventory of the local player has been
1273 // updated from the server. If it is true, it is set to false.
1274 bool Client::getLocalInventoryUpdated()
1276 bool updated = m_inventory_updated;
1277 m_inventory_updated = false;
1281 // Copies the inventory of the local player to parameter
1282 void Client::getLocalInventory(Inventory &dst)
1284 Player *player = m_env.getLocalPlayer();
1285 assert(player != NULL);
1286 dst = player->inventory;
1289 Inventory* Client::getInventory(const InventoryLocation &loc)
1292 case InventoryLocation::UNDEFINED:
1295 case InventoryLocation::CURRENT_PLAYER:
1297 Player *player = m_env.getLocalPlayer();
1298 assert(player != NULL);
1299 return &player->inventory;
1302 case InventoryLocation::PLAYER:
1304 Player *player = m_env.getPlayer(loc.name.c_str());
1307 return &player->inventory;
1310 case InventoryLocation::NODEMETA:
1312 NodeMetadata *meta = m_env.getMap().getNodeMetadata(loc.p);
1315 return meta->getInventory();
1318 case InventoryLocation::DETACHED:
1320 if(m_detached_inventories.count(loc.name) == 0)
1322 return m_detached_inventories[loc.name];
1331 void Client::inventoryAction(InventoryAction *a)
1334 Send it to the server
1336 sendInventoryAction(a);
1339 Predict some local inventory changes
1341 a->clientApply(this, this);
1347 ClientActiveObject * Client::getSelectedActiveObject(
1349 v3f from_pos_f_on_map,
1350 core::line3d<f32> shootline_on_map
1353 std::vector<DistanceSortedActiveObject> objects;
1355 m_env.getActiveObjects(from_pos_f_on_map, max_d, objects);
1358 // After this, the closest object is the first in the array.
1359 std::sort(objects.begin(), objects.end());
1361 for(unsigned int i=0; i<objects.size(); i++)
1363 ClientActiveObject *obj = objects[i].obj;
1365 core::aabbox3d<f32> *selection_box = obj->getSelectionBox();
1366 if(selection_box == NULL)
1369 v3f pos = obj->getPosition();
1371 core::aabbox3d<f32> offsetted_box(
1372 selection_box->MinEdge + pos,
1373 selection_box->MaxEdge + pos
1376 if(offsetted_box.intersectsWithLine(shootline_on_map))
1385 std::list<std::string> Client::getConnectedPlayerNames()
1387 return m_env.getPlayerNames();
1390 float Client::getAnimationTime()
1392 return m_animation_time;
1395 int Client::getCrackLevel()
1397 return m_crack_level;
1400 void Client::setHighlighted(v3s16 pos, bool show_highlighted)
1402 m_show_highlighted = show_highlighted;
1403 v3s16 old_highlighted_pos = m_highlighted_pos;
1404 m_highlighted_pos = pos;
1405 addUpdateMeshTaskForNode(old_highlighted_pos, false, true);
1406 addUpdateMeshTaskForNode(m_highlighted_pos, false, true);
1409 void Client::setCrack(int level, v3s16 pos)
1411 int old_crack_level = m_crack_level;
1412 v3s16 old_crack_pos = m_crack_pos;
1414 m_crack_level = level;
1417 if(old_crack_level >= 0 && (level < 0 || pos != old_crack_pos))
1420 addUpdateMeshTaskForNode(old_crack_pos, false, true);
1422 if(level >= 0 && (old_crack_level < 0 || pos != old_crack_pos))
1425 addUpdateMeshTaskForNode(pos, false, true);
1431 Player *player = m_env.getLocalPlayer();
1432 assert(player != NULL);
1436 u16 Client::getBreath()
1438 Player *player = m_env.getLocalPlayer();
1439 assert(player != NULL);
1440 return player->getBreath();
1443 bool Client::getChatMessage(std::wstring &message)
1445 if(m_chat_queue.size() == 0)
1447 message = m_chat_queue.pop_front();
1451 void Client::typeChatMessage(const std::wstring &message)
1453 // Discard empty line
1458 sendChatMessage(message);
1461 if (message[0] == L'/')
1463 m_chat_queue.push_back((std::wstring)L"issued command: " + message);
1467 LocalPlayer *player = m_env.getLocalPlayer();
1468 assert(player != NULL);
1469 std::wstring name = narrow_to_wide(player->getName());
1470 m_chat_queue.push_back((std::wstring)L"<" + name + L"> " + message);
1474 void Client::addUpdateMeshTask(v3s16 p, bool ack_to_server, bool urgent)
1476 MapBlock *b = m_env.getMap().getBlockNoCreateNoEx(p);
1481 Create a task to update the mesh of the block
1484 MeshMakeData *data = new MeshMakeData(this, m_cache_enable_shaders);
1487 //TimeTaker timer("data fill");
1489 // Debug: 1-6ms, avg=2ms
1491 data->setCrack(m_crack_level, m_crack_pos);
1492 data->setHighlighted(m_highlighted_pos, m_show_highlighted);
1493 data->setSmoothLighting(m_cache_smooth_lighting);
1496 // Add task to queue
1497 m_mesh_update_thread.m_queue_in.addBlock(p, data, ack_to_server, urgent);
1500 void Client::addUpdateMeshTaskWithEdge(v3s16 blockpos, bool ack_to_server, bool urgent)
1503 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1505 catch(InvalidPositionException &e){}
1508 for (int i=0;i<6;i++)
1511 v3s16 p = blockpos + g_6dirs[i];
1512 addUpdateMeshTask(p, false, urgent);
1514 catch(InvalidPositionException &e){}
1518 void Client::addUpdateMeshTaskForNode(v3s16 nodepos, bool ack_to_server, bool urgent)
1522 infostream<<"Client::addUpdateMeshTaskForNode(): "
1523 <<"("<<p.X<<","<<p.Y<<","<<p.Z<<")"
1527 v3s16 blockpos = getNodeBlockPos(nodepos);
1528 v3s16 blockpos_relative = blockpos * MAP_BLOCKSIZE;
1531 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1533 catch(InvalidPositionException &e) {}
1536 if(nodepos.X == blockpos_relative.X){
1538 v3s16 p = blockpos + v3s16(-1,0,0);
1539 addUpdateMeshTask(p, false, urgent);
1541 catch(InvalidPositionException &e){}
1544 if(nodepos.Y == blockpos_relative.Y){
1546 v3s16 p = blockpos + v3s16(0,-1,0);
1547 addUpdateMeshTask(p, false, urgent);
1549 catch(InvalidPositionException &e){}
1552 if(nodepos.Z == blockpos_relative.Z){
1554 v3s16 p = blockpos + v3s16(0,0,-1);
1555 addUpdateMeshTask(p, false, urgent);
1557 catch(InvalidPositionException &e){}
1561 ClientEvent Client::getClientEvent()
1563 if(m_client_event_queue.size() == 0)
1566 event.type = CE_NONE;
1569 return m_client_event_queue.pop_front();
1572 float Client::mediaReceiveProgress()
1574 if (m_media_downloader)
1575 return m_media_downloader->getProgress();
1577 return 1.0; // downloader only exists when not yet done
1580 void Client::afterContentReceived(IrrlichtDevice *device, gui::IGUIFont* font)
1582 infostream<<"Client::afterContentReceived() started"<<std::endl;
1583 assert(m_itemdef_received);
1584 assert(m_nodedef_received);
1585 assert(mediaReceived());
1587 const wchar_t* text = wgettext("Loading textures...");
1589 // Rebuild inherited images and recreate textures
1590 infostream<<"- Rebuilding images and textures"<<std::endl;
1591 draw_load_screen(text,device, guienv, 0, 70);
1592 m_tsrc->rebuildImagesAndTextures();
1596 infostream<<"- Rebuilding shaders"<<std::endl;
1597 text = wgettext("Rebuilding shaders...");
1598 draw_load_screen(text, device, guienv, 0, 75);
1599 m_shsrc->rebuildShaders();
1602 // Update node aliases
1603 infostream<<"- Updating node aliases"<<std::endl;
1604 text = wgettext("Initializing nodes...");
1605 draw_load_screen(text, device, guienv, 0, 80);
1606 m_nodedef->updateAliases(m_itemdef);
1607 m_nodedef->setNodeRegistrationStatus(true);
1608 m_nodedef->runNodeResolverCallbacks();
1611 // Update node textures and assign shaders to each tile
1612 infostream<<"- Updating node textures"<<std::endl;
1613 m_nodedef->updateTextures(this);
1615 // Preload item textures and meshes if configured to
1616 if(g_settings->getBool("preload_item_visuals"))
1618 verbosestream<<"Updating item textures and meshes"<<std::endl;
1619 text = wgettext("Item textures...");
1620 draw_load_screen(text, device, guienv, 0, 0);
1621 std::set<std::string> names = m_itemdef->getAll();
1622 size_t size = names.size();
1625 for(std::set<std::string>::const_iterator
1626 i = names.begin(); i != names.end(); ++i)
1628 // Asking for these caches the result
1629 m_itemdef->getInventoryTexture(*i, this);
1630 m_itemdef->getWieldMesh(*i, this);
1632 percent = (count * 100 / size * 0.2) + 80;
1633 draw_load_screen(text, device, guienv, 0, percent);
1638 // Start mesh update thread after setting up content definitions
1639 infostream<<"- Starting mesh update thread"<<std::endl;
1640 m_mesh_update_thread.Start();
1644 text = wgettext("Done!");
1645 draw_load_screen(text, device, guienv, 0, 100);
1646 infostream<<"Client::afterContentReceived() done"<<std::endl;
1650 float Client::getRTT(void)
1652 return m_con.getPeerStat(PEER_ID_SERVER,con::AVG_RTT);
1655 float Client::getCurRate(void)
1657 return ( m_con.getLocalStat(con::CUR_INC_RATE) +
1658 m_con.getLocalStat(con::CUR_DL_RATE));
1661 float Client::getAvgRate(void)
1663 return ( m_con.getLocalStat(con::AVG_INC_RATE) +
1664 m_con.getLocalStat(con::AVG_DL_RATE));
1667 void Client::makeScreenshot(IrrlichtDevice *device)
1669 irr::video::IVideoDriver *driver = device->getVideoDriver();
1670 irr::video::IImage* const raw_image = driver->createScreenShot();
1672 irr::video::IImage* const image = driver->createImage(video::ECF_R8G8B8,
1673 raw_image->getDimension());
1676 raw_image->copyTo(image);
1677 irr::c8 filename[256];
1678 snprintf(filename, sizeof(filename), "%s" DIR_DELIM "screenshot_%u.png",
1679 g_settings->get("screenshot_path").c_str(),
1680 device->getTimer()->getRealTime());
1681 std::ostringstream sstr;
1682 if (driver->writeImageToFile(image, filename)) {
1683 sstr << "Saved screenshot to '" << filename << "'";
1685 sstr << "Failed to save screenshot '" << filename << "'";
1687 m_chat_queue.push_back(narrow_to_wide(sstr.str()));
1688 infostream << sstr.str() << std::endl;
1695 // IGameDef interface
1697 IItemDefManager* Client::getItemDefManager()
1701 INodeDefManager* Client::getNodeDefManager()
1705 ICraftDefManager* Client::getCraftDefManager()
1708 //return m_craftdef;
1710 ITextureSource* Client::getTextureSource()
1714 IShaderSource* Client::getShaderSource()
1718 scene::ISceneManager* Client::getSceneManager()
1720 return m_device->getSceneManager();
1722 u16 Client::allocateUnknownNodeId(const std::string &name)
1724 errorstream<<"Client::allocateUnknownNodeId(): "
1725 <<"Client cannot allocate node IDs"<<std::endl;
1727 return CONTENT_IGNORE;
1729 ISoundManager* Client::getSoundManager()
1733 MtEventManager* Client::getEventManager()
1738 ParticleManager* Client::getParticleManager()
1740 return &m_particle_manager;
1743 scene::IAnimatedMesh* Client::getMesh(const std::string &filename)
1745 std::map<std::string, std::string>::const_iterator i =
1746 m_mesh_data.find(filename);
1747 if(i == m_mesh_data.end()){
1748 errorstream<<"Client::getMesh(): Mesh not found: \""<<filename<<"\""
1752 const std::string &data = i->second;
1753 scene::ISceneManager *smgr = m_device->getSceneManager();
1755 // Create the mesh, remove it from cache and return it
1756 // This allows unique vertex colors and other properties for each instance
1757 Buffer<char> data_rw(data.c_str(), data.size()); // Const-incorrect Irrlicht
1758 io::IFileSystem *irrfs = m_device->getFileSystem();
1759 io::IReadFile *rfile = irrfs->createMemoryReadFile(
1760 *data_rw, data_rw.getSize(), filename.c_str());
1763 scene::IAnimatedMesh *mesh = smgr->getMesh(rfile);
1765 // NOTE: By playing with Irrlicht refcounts, maybe we could cache a bunch
1766 // of uniquely named instances and re-use them
1768 smgr->getMeshCache()->removeMesh(mesh);