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];
405 snprintf(pName, PLAYERNAME_SIZE, "%s", myplayer->getName());
406 snprintf(pPassword, PASSWORD_SIZE, "%s", m_password.c_str());
408 NetworkPacket* pkt = new NetworkPacket(TOSERVER_INIT,
409 1 + PLAYERNAME_SIZE + PASSWORD_SIZE + 2 + 2);
411 *pkt << (u8) SER_FMT_VER_HIGHEST_READ;
412 pkt->putRawString(pName,PLAYERNAME_SIZE);
413 pkt->putRawString(pPassword, PASSWORD_SIZE);
414 *pkt << (u16) CLIENT_PROTOCOL_VERSION_MIN << (u16) CLIENT_PROTOCOL_VERSION_MAX;
419 // Not connected, return
424 Do stuff if connected
428 Run Map's timers and unload unused data
430 const float map_timer_and_unload_dtime = 5.25;
431 if(m_map_timer_and_unload_interval.step(dtime, map_timer_and_unload_dtime)) {
432 ScopeProfiler sp(g_profiler, "Client: map timer and unload");
433 std::vector<v3s16> deleted_blocks;
434 m_env.getMap().timerUpdate(map_timer_and_unload_dtime,
435 g_settings->getFloat("client_unload_unused_data_timeout"),
440 NOTE: This loop is intentionally iterated the way it is.
443 std::vector<v3s16>::iterator i = deleted_blocks.begin();
444 std::vector<v3s16> sendlist;
446 if(sendlist.size() == 255 || i == deleted_blocks.end()) {
456 NetworkPacket* pkt = new NetworkPacket(TOSERVER_DELETEDBLOCKS, 1 + sizeof(v3s16) * sendlist.size());
458 *pkt << (u8) sendlist.size();
461 for(std::vector<v3s16>::iterator
462 j = sendlist.begin();
463 j != sendlist.end(); ++j) {
470 if(i == deleted_blocks.end())
476 sendlist.push_back(*i);
484 // Control local player (0ms)
485 LocalPlayer *player = m_env.getLocalPlayer();
486 assert(player != NULL);
487 player->applyControl(dtime);
496 ClientEnvEvent event = m_env.getClientEvent();
497 if(event.type == CEE_NONE) {
500 else if(event.type == CEE_PLAYER_DAMAGE) {
501 if(m_ignore_damage_timer <= 0) {
502 u8 damage = event.player_damage.amount;
504 if(event.player_damage.send_to_server)
507 // Add to ClientEvent queue
509 event.type = CE_PLAYER_DAMAGE;
510 event.player_damage.amount = damage;
511 m_client_event_queue.push(event);
514 else if(event.type == CEE_PLAYER_BREATH) {
515 u16 breath = event.player_breath.amount;
523 float &counter = m_avg_rtt_timer;
527 // connectedAndInitialized() is true, peer exists.
528 float avg_rtt = getRTT();
529 infostream << "Client: avg_rtt=" << avg_rtt << std::endl;
533 Send player position to server
536 float &counter = m_playerpos_send_timer;
538 if((m_state == LC_Ready) && (counter >= m_recommended_send_interval))
546 Replace updated meshes
549 int num_processed_meshes = 0;
550 while(!m_mesh_update_thread.m_queue_out.empty())
552 num_processed_meshes++;
553 MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_frontNoEx();
554 MapBlock *block = m_env.getMap().getBlockNoCreateNoEx(r.p);
556 // Delete the old mesh
557 if(block->mesh != NULL)
559 // TODO: Remove hardware buffers of meshbuffers of block->mesh
564 // Replace with the new mesh
565 block->mesh = r.mesh;
570 if(r.ack_block_to_server) {
576 NetworkPacket* pkt = new NetworkPacket(TOSERVER_GOTBLOCKS, 1 + 6);
577 *pkt << (u8) 1 << r.p;
582 if(num_processed_meshes > 0)
583 g_profiler->graphAdd("num_processed_meshes", num_processed_meshes);
589 if (m_media_downloader && m_media_downloader->isStarted()) {
590 m_media_downloader->step(this);
591 if (m_media_downloader->isDone()) {
593 delete m_media_downloader;
594 m_media_downloader = NULL;
599 If the server didn't update the inventory in a while, revert
600 the local inventory (so the player notices the lag problem
601 and knows something is wrong).
603 if(m_inventory_from_server)
605 float interval = 10.0;
606 float count_before = floor(m_inventory_from_server_age / interval);
608 m_inventory_from_server_age += dtime;
610 float count_after = floor(m_inventory_from_server_age / interval);
612 if(count_after != count_before)
614 // Do this every <interval> seconds after TOCLIENT_INVENTORY
615 // Reset the locally changed inventory to the authoritative inventory
616 Player *player = m_env.getLocalPlayer();
617 player->inventory = *m_inventory_from_server;
618 m_inventory_updated = true;
623 Update positions of sounds attached to objects
626 for(std::map<int, u16>::iterator
627 i = m_sounds_to_objects.begin();
628 i != m_sounds_to_objects.end(); i++)
630 int client_id = i->first;
631 u16 object_id = i->second;
632 ClientActiveObject *cao = m_env.getActiveObject(object_id);
635 v3f pos = cao->getPosition();
636 m_sound->updateSoundPosition(client_id, pos);
641 Handle removed remotely initiated sounds
643 m_removed_sounds_check_timer += dtime;
644 if(m_removed_sounds_check_timer >= 2.32) {
645 m_removed_sounds_check_timer = 0;
646 // Find removed sounds and clear references to them
647 std::set<s32> removed_server_ids;
648 for(std::map<s32, int>::iterator
649 i = m_sounds_server_to_client.begin();
650 i != m_sounds_server_to_client.end();) {
651 s32 server_id = i->first;
652 int client_id = i->second;
654 if(!m_sound->soundExists(client_id)) {
655 m_sounds_server_to_client.erase(server_id);
656 m_sounds_client_to_server.erase(client_id);
657 m_sounds_to_objects.erase(client_id);
658 removed_server_ids.insert(server_id);
663 if(!removed_server_ids.empty()) {
664 size_t server_ids = removed_server_ids.size();
665 assert(server_ids <= 0xFFFF);
667 NetworkPacket* pkt = new NetworkPacket(TOSERVER_REMOVED_SOUNDS, 2 + server_ids * 4);
669 *pkt << (u16) (server_ids & 0xFFFF);
671 for(std::set<s32>::iterator i = removed_server_ids.begin();
672 i != removed_server_ids.end(); i++)
680 if (m_localdb && m_localdb_save_interval.step(dtime,
681 m_cache_save_interval)) {
682 m_localdb->endSave();
683 m_localdb->beginSave();
687 bool Client::loadMedia(const std::string &data, const std::string &filename)
689 // Silly irrlicht's const-incorrectness
690 Buffer<char> data_rw(data.c_str(), data.size());
694 const char *image_ext[] = {
695 ".png", ".jpg", ".bmp", ".tga",
696 ".pcx", ".ppm", ".psd", ".wal", ".rgb",
699 name = removeStringEnd(filename, image_ext);
702 verbosestream<<"Client: Attempting to load image "
703 <<"file \""<<filename<<"\""<<std::endl;
705 io::IFileSystem *irrfs = m_device->getFileSystem();
706 video::IVideoDriver *vdrv = m_device->getVideoDriver();
708 // Create an irrlicht memory file
709 io::IReadFile *rfile = irrfs->createMemoryReadFile(
710 *data_rw, data_rw.getSize(), "_tempreadfile");
712 FATAL_ERROR_IF(!rfile, "Could not create irrlicht memory file.");
715 video::IImage *img = vdrv->createImageFromFile(rfile);
717 errorstream<<"Client: Cannot create image from data of "
718 <<"file \""<<filename<<"\""<<std::endl;
723 m_tsrc->insertSourceImage(filename, img);
730 const char *sound_ext[] = {
731 ".0.ogg", ".1.ogg", ".2.ogg", ".3.ogg", ".4.ogg",
732 ".5.ogg", ".6.ogg", ".7.ogg", ".8.ogg", ".9.ogg",
735 name = removeStringEnd(filename, sound_ext);
738 verbosestream<<"Client: Attempting to load sound "
739 <<"file \""<<filename<<"\""<<std::endl;
740 m_sound->loadSoundData(name, data);
744 const char *model_ext[] = {
745 ".x", ".b3d", ".md2", ".obj",
748 name = removeStringEnd(filename, model_ext);
751 verbosestream<<"Client: Storing model into memory: "
752 <<"\""<<filename<<"\""<<std::endl;
753 if(m_mesh_data.count(filename))
754 errorstream<<"Multiple models with name \""<<filename.c_str()
755 <<"\" found; replacing previous model"<<std::endl;
756 m_mesh_data[filename] = data;
760 errorstream<<"Client: Don't know how to load file \""
761 <<filename<<"\""<<std::endl;
765 // Virtual methods from con::PeerHandler
766 void Client::peerAdded(con::Peer *peer)
768 infostream<<"Client::peerAdded(): peer->id="
769 <<peer->id<<std::endl;
771 void Client::deletingPeer(con::Peer *peer, bool timeout)
773 infostream<<"Client::deletingPeer(): "
774 "Server Peer is getting deleted "
775 <<"(timeout="<<timeout<<")"<<std::endl;
780 u16 number of files requested
786 void Client::request_media(const std::vector<std::string> &file_requests)
788 std::ostringstream os(std::ios_base::binary);
789 writeU16(os, TOSERVER_REQUEST_MEDIA);
790 size_t file_requests_size = file_requests.size();
792 FATAL_ERROR_IF(file_requests_size > 0xFFFF, "Unsupported number of file requests");
794 // Packet dynamicly resized
795 NetworkPacket* pkt = new NetworkPacket(TOSERVER_REQUEST_MEDIA, 2 + 0);
797 *pkt << (u16) (file_requests_size & 0xFFFF);
799 for(std::vector<std::string>::const_iterator i = file_requests.begin();
800 i != file_requests.end(); ++i) {
806 infostream<<"Client: Sending media request list to server ("
807 <<file_requests.size()<<" files. packet size)"<<std::endl;
810 void Client::received_media()
812 NetworkPacket* pkt = new NetworkPacket(TOSERVER_RECEIVED_MEDIA, 0);
814 infostream<<"Client: Notifying server that we received all media"
818 void Client::initLocalMapSaving(const Address &address,
819 const std::string &hostname,
820 bool is_local_server)
822 if (!g_settings->getBool("enable_local_map_saving") || is_local_server) {
826 const std::string world_path = porting::path_user
827 + DIR_DELIM + "worlds"
828 + DIR_DELIM + "server_"
829 + hostname + "_" + to_string(address.getPort());
831 fs::CreateAllDirs(world_path);
833 m_localdb = new Database_SQLite3(world_path);
834 m_localdb->beginSave();
835 actionstream << "Local map saving started, map will be saved at '" << world_path << "'" << std::endl;
838 void Client::ReceiveAll()
840 DSTACK(__FUNCTION_NAME);
841 u32 start_ms = porting::getTimeMs();
844 // Limit time even if there would be huge amounts of data to
846 if(porting::getTimeMs() > start_ms + 100)
851 g_profiler->graphAdd("client_received_packets", 1);
853 catch(con::NoIncomingDataException &e) {
856 catch(con::InvalidIncomingDataException &e) {
857 infostream<<"Client::ReceiveAll(): "
858 "InvalidIncomingDataException: what()="
859 <<e.what()<<std::endl;
864 void Client::Receive()
866 DSTACK(__FUNCTION_NAME);
867 SharedBuffer<u8> data;
869 u32 datasize = m_con.Receive(sender_peer_id, data);
870 ProcessData(*data, datasize, sender_peer_id);
873 inline void Client::handleCommand(NetworkPacket* pkt)
875 const ToClientCommandHandler& opHandle = toClientCommandTable[pkt->getCommand()];
876 (this->*opHandle.handler)(pkt);
880 sender_peer_id given to this shall be quaranteed to be a valid peer
882 void Client::ProcessData(u8 *data, u32 datasize, u16 sender_peer_id)
884 DSTACK(__FUNCTION_NAME);
886 // Ignore packets that don't even fit a command
888 m_packetcounter.add(60000);
892 NetworkPacket* pkt = new NetworkPacket(data, datasize, sender_peer_id);
894 ToClientCommand command = (ToClientCommand) pkt->getCommand();
896 //infostream<<"Client: received command="<<command<<std::endl;
897 m_packetcounter.add((u16)command);
900 If this check is removed, be sure to change the queue
901 system to know the ids
903 if(sender_peer_id != PEER_ID_SERVER) {
904 infostream << "Client::ProcessData(): Discarding data not "
905 "coming from server: peer_id=" << sender_peer_id
911 // Command must be handled into ToClientCommandHandler
912 if (command >= TOCLIENT_NUM_MSG_TYPES) {
913 infostream << "Client: Ignoring unknown command "
914 << command << std::endl;
918 * Those packets are handled before m_server_ser_ver is set, it's normal
919 * But we must use the new ToClientConnectionState in the future,
922 if(toClientCommandTable[command].state == TOCLIENT_STATE_NOT_CONNECTED) {
928 if(m_server_ser_ver == SER_FMT_VER_INVALID) {
929 infostream << "Client: Server serialization"
930 " format invalid or not initialized."
931 " Skipping incoming command=" << command << std::endl;
937 Handle runtime commands
944 void Client::Send(NetworkPacket* pkt)
946 m_con.Send(PEER_ID_SERVER,
947 serverCommandFactoryTable[pkt->getCommand()].channel,
949 serverCommandFactoryTable[pkt->getCommand()].reliable);
953 void Client::interact(u8 action, const PointedThing& pointed)
955 if(m_state != LC_Ready) {
956 errorstream << "Client::interact() "
957 "cancelled (not connected)"
966 [5] u32 length of the next item
967 [9] serialized PointedThing
969 0: start digging (from undersurface) or use
970 1: stop digging (all parameters ignored)
972 3: place block or item (to abovesurface)
976 NetworkPacket* pkt = new NetworkPacket(TOSERVER_INTERACT, 1 + 2 + 0);
979 *pkt << (u16)getPlayerItem();
981 std::ostringstream tmp_os(std::ios::binary);
982 pointed.serialize(tmp_os);
984 pkt->putLongString(tmp_os.str());
989 void Client::sendNodemetaFields(v3s16 p, const std::string &formname,
990 const std::map<std::string, std::string> &fields)
992 size_t fields_size = fields.size();
994 FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of nodemeta fields");
996 NetworkPacket* pkt = new NetworkPacket(TOSERVER_NODEMETA_FIELDS, 0);
998 *pkt << p << formname << (u16) (fields_size & 0xFFFF);
1000 for(std::map<std::string, std::string>::const_iterator
1001 i = fields.begin(); i != fields.end(); i++) {
1002 const std::string &name = i->first;
1003 const std::string &value = i->second;
1005 pkt->putLongString(value);
1011 void Client::sendInventoryFields(const std::string &formname,
1012 const std::map<std::string, std::string> &fields)
1014 size_t fields_size = fields.size();
1015 FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of inventory fields");
1017 NetworkPacket* pkt = new NetworkPacket(TOSERVER_INVENTORY_FIELDS, 0);
1018 *pkt << formname << (u16) (fields_size & 0xFFFF);
1020 for(std::map<std::string, std::string>::const_iterator
1021 i = fields.begin(); i != fields.end(); i++) {
1022 const std::string &name = i->first;
1023 const std::string &value = i->second;
1025 pkt->putLongString(value);
1031 void Client::sendInventoryAction(InventoryAction *a)
1033 std::ostringstream os(std::ios_base::binary);
1038 std::string s = os.str();
1040 NetworkPacket* pkt = new NetworkPacket(TOSERVER_INVENTORY_ACTION, s.size());
1041 pkt->putRawString(s.c_str(),s.size());
1046 void Client::sendChatMessage(const std::wstring &message)
1048 NetworkPacket* pkt = new NetworkPacket(TOSERVER_CHAT_MESSAGE, 2 + message.size() * sizeof(u16));
1055 void Client::sendChangePassword(const std::wstring &oldpassword,
1056 const std::wstring &newpassword)
1058 Player *player = m_env.getLocalPlayer();
1062 std::string playername = player->getName();
1063 std::string oldpwd = translatePassword(playername, oldpassword);
1064 std::string newpwd = translatePassword(playername, newpassword);
1066 NetworkPacket* pkt = new NetworkPacket(TOSERVER_PASSWORD, 2 * PASSWORD_SIZE);
1068 for(u8 i = 0; i < PASSWORD_SIZE; i++) {
1069 *pkt << (u8) (i < oldpwd.length() ? oldpwd[i] : 0);
1072 for(u8 i = 0; i < PASSWORD_SIZE; i++) {
1073 *pkt << (u8) (i < newpwd.length() ? newpwd[i] : 0);
1080 void Client::sendDamage(u8 damage)
1082 DSTACK(__FUNCTION_NAME);
1084 NetworkPacket* pkt = new NetworkPacket(TOSERVER_DAMAGE, sizeof(u8));
1089 void Client::sendBreath(u16 breath)
1091 DSTACK(__FUNCTION_NAME);
1093 NetworkPacket* pkt = new NetworkPacket(TOSERVER_BREATH, sizeof(u16));
1098 void Client::sendRespawn()
1100 DSTACK(__FUNCTION_NAME);
1102 NetworkPacket* pkt = new NetworkPacket(TOSERVER_RESPAWN, 0);
1106 void Client::sendReady()
1108 DSTACK(__FUNCTION_NAME);
1110 NetworkPacket* pkt = new NetworkPacket(TOSERVER_CLIENT_READY,
1111 1 + 1 + 1 + 1 + 2 + sizeof(char) * strlen(minetest_version_hash));
1113 *pkt << (u8) VERSION_MAJOR << (u8) VERSION_MINOR << (u8) VERSION_PATCH_ORIG
1114 << (u8) 0 << (u16) strlen(minetest_version_hash);
1116 pkt->putRawString(minetest_version_hash, (u16) strlen(minetest_version_hash));
1120 void Client::sendPlayerPos()
1122 LocalPlayer *myplayer = m_env.getLocalPlayer();
1123 if(myplayer == NULL)
1126 // Save bandwidth by only updating position when something changed
1127 if(myplayer->last_position == myplayer->getPosition() &&
1128 myplayer->last_speed == myplayer->getSpeed() &&
1129 myplayer->last_pitch == myplayer->getPitch() &&
1130 myplayer->last_yaw == myplayer->getYaw() &&
1131 myplayer->last_keyPressed == myplayer->keyPressed)
1134 myplayer->last_position = myplayer->getPosition();
1135 myplayer->last_speed = myplayer->getSpeed();
1136 myplayer->last_pitch = myplayer->getPitch();
1137 myplayer->last_yaw = myplayer->getYaw();
1138 myplayer->last_keyPressed = myplayer->keyPressed;
1142 //JMutexAutoLock lock(m_con_mutex); //bulk comment-out
1143 our_peer_id = m_con.GetPeerID();
1146 // Set peer id if not set already
1147 if(myplayer->peer_id == PEER_ID_INEXISTENT)
1148 myplayer->peer_id = our_peer_id;
1150 assert(myplayer->peer_id == our_peer_id);
1152 v3f pf = myplayer->getPosition();
1153 v3f sf = myplayer->getSpeed();
1154 s32 pitch = myplayer->getPitch() * 100;
1155 s32 yaw = myplayer->getYaw() * 100;
1156 u32 keyPressed = myplayer->keyPressed;
1158 v3s32 position(pf.X*100, pf.Y*100, pf.Z*100);
1159 v3s32 speed(sf.X*100, sf.Y*100, sf.Z*100);
1162 [0] v3s32 position*100
1163 [12] v3s32 speed*100
1164 [12+12] s32 pitch*100
1165 [12+12+4] s32 yaw*100
1166 [12+12+4+4] u32 keyPressed
1169 NetworkPacket* pkt = new NetworkPacket(TOSERVER_PLAYERPOS, 12 + 12 + 4 + 4 + 4);
1171 *pkt << position << speed << pitch << yaw << keyPressed;
1176 void Client::sendPlayerItem(u16 item)
1178 Player *myplayer = m_env.getLocalPlayer();
1179 if(myplayer == NULL)
1182 u16 our_peer_id = m_con.GetPeerID();
1184 // Set peer id if not set already
1185 if(myplayer->peer_id == PEER_ID_INEXISTENT)
1186 myplayer->peer_id = our_peer_id;
1187 assert(myplayer->peer_id == our_peer_id);
1189 NetworkPacket* pkt = new NetworkPacket(TOSERVER_PLAYERITEM, 2);
1196 void Client::removeNode(v3s16 p)
1198 std::map<v3s16, MapBlock*> modified_blocks;
1201 m_env.getMap().removeNodeAndUpdate(p, modified_blocks);
1203 catch(InvalidPositionException &e) {
1206 for(std::map<v3s16, MapBlock *>::iterator
1207 i = modified_blocks.begin();
1208 i != modified_blocks.end(); ++i) {
1209 addUpdateMeshTaskWithEdge(i->first, false, true);
1213 void Client::addNode(v3s16 p, MapNode n, bool remove_metadata)
1215 //TimeTaker timer1("Client::addNode()");
1217 std::map<v3s16, MapBlock*> modified_blocks;
1220 //TimeTaker timer3("Client::addNode(): addNodeAndUpdate");
1221 m_env.getMap().addNodeAndUpdate(p, n, modified_blocks, remove_metadata);
1223 catch(InvalidPositionException &e) {
1226 for(std::map<v3s16, MapBlock *>::iterator
1227 i = modified_blocks.begin();
1228 i != modified_blocks.end(); ++i) {
1229 addUpdateMeshTaskWithEdge(i->first, false, true);
1233 void Client::setPlayerControl(PlayerControl &control)
1235 LocalPlayer *player = m_env.getLocalPlayer();
1236 assert(player != NULL);
1237 player->control = control;
1240 void Client::selectPlayerItem(u16 item)
1242 m_playeritem = item;
1243 m_inventory_updated = true;
1244 sendPlayerItem(item);
1247 // Returns true if the inventory of the local player has been
1248 // updated from the server. If it is true, it is set to false.
1249 bool Client::getLocalInventoryUpdated()
1251 bool updated = m_inventory_updated;
1252 m_inventory_updated = false;
1256 // Copies the inventory of the local player to parameter
1257 void Client::getLocalInventory(Inventory &dst)
1259 Player *player = m_env.getLocalPlayer();
1260 assert(player != NULL);
1261 dst = player->inventory;
1264 Inventory* Client::getInventory(const InventoryLocation &loc)
1267 case InventoryLocation::UNDEFINED:
1270 case InventoryLocation::CURRENT_PLAYER:
1272 Player *player = m_env.getLocalPlayer();
1273 assert(player != NULL);
1274 return &player->inventory;
1277 case InventoryLocation::PLAYER:
1279 Player *player = m_env.getPlayer(loc.name.c_str());
1282 return &player->inventory;
1285 case InventoryLocation::NODEMETA:
1287 NodeMetadata *meta = m_env.getMap().getNodeMetadata(loc.p);
1290 return meta->getInventory();
1293 case InventoryLocation::DETACHED:
1295 if(m_detached_inventories.count(loc.name) == 0)
1297 return m_detached_inventories[loc.name];
1301 FATAL_ERROR("Invalid inventory location type.");
1306 void Client::inventoryAction(InventoryAction *a)
1309 Send it to the server
1311 sendInventoryAction(a);
1314 Predict some local inventory changes
1316 a->clientApply(this, this);
1322 ClientActiveObject * Client::getSelectedActiveObject(
1324 v3f from_pos_f_on_map,
1325 core::line3d<f32> shootline_on_map
1328 std::vector<DistanceSortedActiveObject> objects;
1330 m_env.getActiveObjects(from_pos_f_on_map, max_d, objects);
1333 // After this, the closest object is the first in the array.
1334 std::sort(objects.begin(), objects.end());
1336 for(unsigned int i=0; i<objects.size(); i++)
1338 ClientActiveObject *obj = objects[i].obj;
1340 core::aabbox3d<f32> *selection_box = obj->getSelectionBox();
1341 if(selection_box == NULL)
1344 v3f pos = obj->getPosition();
1346 core::aabbox3d<f32> offsetted_box(
1347 selection_box->MinEdge + pos,
1348 selection_box->MaxEdge + pos
1351 if(offsetted_box.intersectsWithLine(shootline_on_map))
1360 std::list<std::string> Client::getConnectedPlayerNames()
1362 return m_env.getPlayerNames();
1365 float Client::getAnimationTime()
1367 return m_animation_time;
1370 int Client::getCrackLevel()
1372 return m_crack_level;
1375 void Client::setHighlighted(v3s16 pos, bool show_highlighted)
1377 m_show_highlighted = show_highlighted;
1378 v3s16 old_highlighted_pos = m_highlighted_pos;
1379 m_highlighted_pos = pos;
1380 addUpdateMeshTaskForNode(old_highlighted_pos, false, true);
1381 addUpdateMeshTaskForNode(m_highlighted_pos, false, true);
1384 void Client::setCrack(int level, v3s16 pos)
1386 int old_crack_level = m_crack_level;
1387 v3s16 old_crack_pos = m_crack_pos;
1389 m_crack_level = level;
1392 if(old_crack_level >= 0 && (level < 0 || pos != old_crack_pos))
1395 addUpdateMeshTaskForNode(old_crack_pos, false, true);
1397 if(level >= 0 && (old_crack_level < 0 || pos != old_crack_pos))
1400 addUpdateMeshTaskForNode(pos, false, true);
1406 Player *player = m_env.getLocalPlayer();
1407 assert(player != NULL);
1411 u16 Client::getBreath()
1413 Player *player = m_env.getLocalPlayer();
1414 assert(player != NULL);
1415 return player->getBreath();
1418 bool Client::getChatMessage(std::wstring &message)
1420 if(m_chat_queue.size() == 0)
1422 message = m_chat_queue.front();
1427 void Client::typeChatMessage(const std::wstring &message)
1429 // Discard empty line
1434 sendChatMessage(message);
1437 if (message[0] == L'/')
1439 m_chat_queue.push((std::wstring)L"issued command: " + message);
1443 LocalPlayer *player = m_env.getLocalPlayer();
1444 assert(player != NULL);
1445 std::wstring name = narrow_to_wide(player->getName());
1446 m_chat_queue.push((std::wstring)L"<" + name + L"> " + message);
1450 void Client::addUpdateMeshTask(v3s16 p, bool ack_to_server, bool urgent)
1452 MapBlock *b = m_env.getMap().getBlockNoCreateNoEx(p);
1457 Create a task to update the mesh of the block
1460 MeshMakeData *data = new MeshMakeData(this, m_cache_enable_shaders);
1463 //TimeTaker timer("data fill");
1465 // Debug: 1-6ms, avg=2ms
1467 data->setCrack(m_crack_level, m_crack_pos);
1468 data->setHighlighted(m_highlighted_pos, m_show_highlighted);
1469 data->setSmoothLighting(m_cache_smooth_lighting);
1472 // Add task to queue
1473 m_mesh_update_thread.m_queue_in.addBlock(p, data, ack_to_server, urgent);
1476 void Client::addUpdateMeshTaskWithEdge(v3s16 blockpos, bool ack_to_server, bool urgent)
1479 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1481 catch(InvalidPositionException &e){}
1484 for (int i=0;i<6;i++)
1487 v3s16 p = blockpos + g_6dirs[i];
1488 addUpdateMeshTask(p, false, urgent);
1490 catch(InvalidPositionException &e){}
1494 void Client::addUpdateMeshTaskForNode(v3s16 nodepos, bool ack_to_server, bool urgent)
1498 infostream<<"Client::addUpdateMeshTaskForNode(): "
1499 <<"("<<p.X<<","<<p.Y<<","<<p.Z<<")"
1503 v3s16 blockpos = getNodeBlockPos(nodepos);
1504 v3s16 blockpos_relative = blockpos * MAP_BLOCKSIZE;
1507 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1509 catch(InvalidPositionException &e) {}
1512 if(nodepos.X == blockpos_relative.X){
1514 v3s16 p = blockpos + v3s16(-1,0,0);
1515 addUpdateMeshTask(p, false, urgent);
1517 catch(InvalidPositionException &e){}
1520 if(nodepos.Y == blockpos_relative.Y){
1522 v3s16 p = blockpos + v3s16(0,-1,0);
1523 addUpdateMeshTask(p, false, urgent);
1525 catch(InvalidPositionException &e){}
1528 if(nodepos.Z == blockpos_relative.Z){
1530 v3s16 p = blockpos + v3s16(0,0,-1);
1531 addUpdateMeshTask(p, false, urgent);
1533 catch(InvalidPositionException &e){}
1537 ClientEvent Client::getClientEvent()
1540 if(m_client_event_queue.size() == 0) {
1541 event.type = CE_NONE;
1544 event = m_client_event_queue.front();
1545 m_client_event_queue.pop();
1550 float Client::mediaReceiveProgress()
1552 if (m_media_downloader)
1553 return m_media_downloader->getProgress();
1555 return 1.0; // downloader only exists when not yet done
1558 void Client::afterContentReceived(IrrlichtDevice *device, gui::IGUIFont* font)
1560 infostream<<"Client::afterContentReceived() started"<<std::endl;
1561 assert(m_itemdef_received); // pre-condition
1562 assert(m_nodedef_received); // pre-condition
1563 assert(mediaReceived()); // pre-condition
1565 const wchar_t* text = wgettext("Loading textures...");
1567 // Rebuild inherited images and recreate textures
1568 infostream<<"- Rebuilding images and textures"<<std::endl;
1569 draw_load_screen(text,device, guienv, 0, 70);
1570 m_tsrc->rebuildImagesAndTextures();
1574 infostream<<"- Rebuilding shaders"<<std::endl;
1575 text = wgettext("Rebuilding shaders...");
1576 draw_load_screen(text, device, guienv, 0, 75);
1577 m_shsrc->rebuildShaders();
1580 // Update node aliases
1581 infostream<<"- Updating node aliases"<<std::endl;
1582 text = wgettext("Initializing nodes...");
1583 draw_load_screen(text, device, guienv, 0, 80);
1584 m_nodedef->updateAliases(m_itemdef);
1585 m_nodedef->setNodeRegistrationStatus(true);
1586 m_nodedef->runNodeResolverCallbacks();
1589 // Update node textures and assign shaders to each tile
1590 infostream<<"- Updating node textures"<<std::endl;
1591 m_nodedef->updateTextures(this);
1593 // Preload item textures and meshes if configured to
1594 if(g_settings->getBool("preload_item_visuals"))
1596 verbosestream<<"Updating item textures and meshes"<<std::endl;
1597 text = wgettext("Item textures...");
1598 draw_load_screen(text, device, guienv, 0, 0);
1599 std::set<std::string> names = m_itemdef->getAll();
1600 size_t size = names.size();
1603 for(std::set<std::string>::const_iterator
1604 i = names.begin(); i != names.end(); ++i)
1606 // Asking for these caches the result
1607 m_itemdef->getInventoryTexture(*i, this);
1608 m_itemdef->getWieldMesh(*i, this);
1610 percent = (count * 100 / size * 0.2) + 80;
1611 draw_load_screen(text, device, guienv, 0, percent);
1616 // Start mesh update thread after setting up content definitions
1617 infostream<<"- Starting mesh update thread"<<std::endl;
1618 m_mesh_update_thread.Start();
1622 text = wgettext("Done!");
1623 draw_load_screen(text, device, guienv, 0, 100);
1624 infostream<<"Client::afterContentReceived() done"<<std::endl;
1628 float Client::getRTT(void)
1630 return m_con.getPeerStat(PEER_ID_SERVER,con::AVG_RTT);
1633 float Client::getCurRate(void)
1635 return ( m_con.getLocalStat(con::CUR_INC_RATE) +
1636 m_con.getLocalStat(con::CUR_DL_RATE));
1639 float Client::getAvgRate(void)
1641 return ( m_con.getLocalStat(con::AVG_INC_RATE) +
1642 m_con.getLocalStat(con::AVG_DL_RATE));
1645 void Client::makeScreenshot(IrrlichtDevice *device)
1647 irr::video::IVideoDriver *driver = device->getVideoDriver();
1648 irr::video::IImage* const raw_image = driver->createScreenShot();
1650 irr::video::IImage* const image = driver->createImage(video::ECF_R8G8B8,
1651 raw_image->getDimension());
1654 raw_image->copyTo(image);
1655 irr::c8 filename[256];
1656 snprintf(filename, sizeof(filename),
1657 (std::string("%s") + DIR_DELIM + "screenshot_%u.png").c_str(),
1658 g_settings->get("screenshot_path").c_str(),
1659 device->getTimer()->getRealTime());
1660 std::ostringstream sstr;
1661 if (driver->writeImageToFile(image, filename)) {
1662 sstr << "Saved screenshot to '" << filename << "'";
1664 sstr << "Failed to save screenshot '" << filename << "'";
1666 m_chat_queue.push(narrow_to_wide(sstr.str()));
1667 infostream << sstr.str() << std::endl;
1674 // IGameDef interface
1676 IItemDefManager* Client::getItemDefManager()
1680 INodeDefManager* Client::getNodeDefManager()
1684 ICraftDefManager* Client::getCraftDefManager()
1687 //return m_craftdef;
1689 ITextureSource* Client::getTextureSource()
1693 IShaderSource* Client::getShaderSource()
1697 scene::ISceneManager* Client::getSceneManager()
1699 return m_device->getSceneManager();
1701 u16 Client::allocateUnknownNodeId(const std::string &name)
1703 errorstream << "Client::allocateUnknownNodeId(): "
1704 << "Client cannot allocate node IDs" << std::endl;
1705 FATAL_ERROR("Client allocated unknown node");
1707 return CONTENT_IGNORE;
1709 ISoundManager* Client::getSoundManager()
1713 MtEventManager* Client::getEventManager()
1718 ParticleManager* Client::getParticleManager()
1720 return &m_particle_manager;
1723 scene::IAnimatedMesh* Client::getMesh(const std::string &filename)
1725 std::map<std::string, std::string>::const_iterator i =
1726 m_mesh_data.find(filename);
1727 if(i == m_mesh_data.end()){
1728 errorstream<<"Client::getMesh(): Mesh not found: \""<<filename<<"\""
1732 const std::string &data = i->second;
1733 scene::ISceneManager *smgr = m_device->getSceneManager();
1735 // Create the mesh, remove it from cache and return it
1736 // This allows unique vertex colors and other properties for each instance
1737 Buffer<char> data_rw(data.c_str(), data.size()); // Const-incorrect Irrlicht
1738 io::IFileSystem *irrfs = m_device->getFileSystem();
1739 io::IReadFile *rfile = irrfs->createMemoryReadFile(
1740 *data_rw, data_rw.getSize(), filename.c_str());
1741 FATAL_ERROR_IF(!rfile, "Could not create/open RAM file");
1743 scene::IAnimatedMesh *mesh = smgr->getMesh(rfile);
1745 // NOTE: By playing with Irrlicht refcounts, maybe we could cache a bunch
1746 // of uniquely named instances and re-use them
1748 smgr->getMeshCache()->removeMesh(mesh);