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/auth.h"
26 #include "util/directiontables.h"
27 #include "util/pointedthing.h"
28 #include "util/serialize.h"
29 #include "util/string.h"
32 #include "network/clientopcodes.h"
35 #include "mapblock_mesh.h"
42 #include "nodemetadata.h"
45 #include "clientmap.h"
46 #include "clientmedia.h"
48 #include "IMeshCache.h"
51 #include "drawscene.h"
52 #include "database-sqlite3.h"
53 #include "serialization.h"
54 #include "guiscalingfilter.h"
56 extern gui::IGUIEnvironment* guienv;
62 QueuedMeshUpdate::QueuedMeshUpdate():
65 ack_block_to_server(false)
69 QueuedMeshUpdate::~QueuedMeshUpdate()
79 MeshUpdateQueue::MeshUpdateQueue()
83 MeshUpdateQueue::~MeshUpdateQueue()
85 JMutexAutoLock lock(m_mutex);
87 for(std::vector<QueuedMeshUpdate*>::iterator
89 i != m_queue.end(); i++)
91 QueuedMeshUpdate *q = *i;
97 peer_id=0 adds with nobody to send to
99 void MeshUpdateQueue::addBlock(v3s16 p, MeshMakeData *data, bool ack_block_to_server, bool urgent)
101 DSTACK(__FUNCTION_NAME);
103 assert(data); // pre-condition
105 JMutexAutoLock lock(m_mutex);
111 Find if block is already in queue.
112 If it is, update the data and quit.
114 for(std::vector<QueuedMeshUpdate*>::iterator
116 i != m_queue.end(); i++)
118 QueuedMeshUpdate *q = *i;
124 if(ack_block_to_server)
125 q->ack_block_to_server = true;
133 QueuedMeshUpdate *q = new QueuedMeshUpdate;
136 q->ack_block_to_server = ack_block_to_server;
137 m_queue.push_back(q);
140 // Returned pointer must be deleted
141 // Returns NULL if queue is empty
142 QueuedMeshUpdate *MeshUpdateQueue::pop()
144 JMutexAutoLock lock(m_mutex);
146 bool must_be_urgent = !m_urgents.empty();
147 for(std::vector<QueuedMeshUpdate*>::iterator
149 i != m_queue.end(); i++)
151 QueuedMeshUpdate *q = *i;
152 if(must_be_urgent && m_urgents.count(q->p) == 0)
155 m_urgents.erase(q->p);
165 void MeshUpdateThread::enqueueUpdate(v3s16 p, MeshMakeData *data,
166 bool ack_block_to_server, bool urgent)
168 m_queue_in.addBlock(p, data, ack_block_to_server, urgent);
172 void MeshUpdateThread::doUpdate()
175 while ((q = m_queue_in.pop())) {
177 ScopeProfiler sp(g_profiler, "Client: Mesh making");
179 MapBlockMesh *mesh_new = new MapBlockMesh(q->data, m_camera_offset);
184 r.ack_block_to_server = q->ack_block_to_server;
186 m_queue_out.push_back(r);
197 IrrlichtDevice *device,
198 const char *playername,
199 std::string password,
200 MapDrawControl &control,
201 IWritableTextureSource *tsrc,
202 IWritableShaderSource *shsrc,
203 IWritableItemDefManager *itemdef,
204 IWritableNodeDefManager *nodedef,
205 ISoundManager *sound,
206 MtEventManager *event,
209 m_packetcounter_timer(0.0),
210 m_connection_reinit_timer(0.1),
211 m_avg_rtt_timer(0.0),
212 m_playerpos_send_timer(0.0),
213 m_ignore_damage_timer(0.0),
220 m_mesh_update_thread(),
222 new ClientMap(this, this, control,
223 device->getSceneManager()->getRootSceneNode(),
224 device->getSceneManager(), 666),
225 device->getSceneManager(),
228 m_particle_manager(&m_env),
229 m_con(PROTOCOL_ID, 512, CONNECTION_TIMEOUT, ipv6, this),
231 m_server_ser_ver(SER_FMT_VER_INVALID),
234 m_inventory_updated(false),
235 m_inventory_from_server(NULL),
236 m_inventory_from_server_age(0.0),
237 m_show_highlighted(false),
241 m_highlighted_pos(0,0,0),
243 m_password(password),
244 m_chosen_auth_mech(AUTH_MECHANISM_NONE),
246 m_access_denied(false),
247 m_access_denied_reconnect(false),
248 m_itemdef_received(false),
249 m_nodedef_received(false),
250 m_media_downloader(new ClientMediaDownloader()),
251 m_time_of_day_set(false),
252 m_last_time_of_day_f(-1),
253 m_time_of_day_update_timer(0),
254 m_recommended_send_interval(0.1),
255 m_removed_sounds_check_timer(0),
260 m_env.addPlayer(new LocalPlayer(this, playername));
262 m_mapper = new Mapper(device, this);
263 m_cache_save_interval = g_settings->getU16("server_map_save_interval");
265 m_cache_smooth_lighting = g_settings->getBool("smooth_lighting");
266 m_cache_enable_shaders = g_settings->getBool("enable_shaders");
271 //request all client managed threads to stop
272 m_mesh_update_thread.Stop();
273 // Save local server map
275 infostream << "Local map saving ended." << std::endl;
276 m_localdb->endSave();
280 bool Client::isShutdown()
283 if (!m_mesh_update_thread.IsRunning()) return true;
292 m_mesh_update_thread.Stop();
293 m_mesh_update_thread.Wait();
294 while (!m_mesh_update_thread.m_queue_out.empty()) {
295 MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_frontNoEx();
300 delete m_inventory_from_server;
302 // Delete detached inventories
303 for (std::map<std::string, Inventory*>::iterator
304 i = m_detached_inventories.begin();
305 i != m_detached_inventories.end(); ++i) {
309 // cleanup 3d model meshes on client shutdown
310 while (m_device->getSceneManager()->getMeshCache()->getMeshCount() != 0) {
311 scene::IAnimatedMesh *mesh =
312 m_device->getSceneManager()->getMeshCache()->getMeshByIndex(0);
315 m_device->getSceneManager()->getMeshCache()->removeMesh(mesh);
321 void Client::connect(Address address,
322 const std::string &address_name,
323 bool is_local_server)
325 DSTACK(__FUNCTION_NAME);
327 initLocalMapSaving(address, address_name, is_local_server);
329 m_con.SetTimeoutMs(0);
330 m_con.Connect(address);
333 void Client::step(float dtime)
335 DSTACK(__FUNCTION_NAME);
341 if(m_ignore_damage_timer > dtime)
342 m_ignore_damage_timer -= dtime;
344 m_ignore_damage_timer = 0.0;
346 m_animation_time += dtime;
347 if(m_animation_time > 60.0)
348 m_animation_time -= 60.0;
350 m_time_of_day_update_timer += dtime;
358 float &counter = m_packetcounter_timer;
364 infostream << "Client packetcounter (" << m_packetcounter_timer
366 m_packetcounter.print(infostream);
367 m_packetcounter.clear();
371 // UGLY hack to fix 2 second startup delay caused by non existent
372 // server client startup synchronization in local server or singleplayer mode
373 static bool initial_step = true;
375 initial_step = false;
377 else if(m_state == LC_Created) {
378 float &counter = m_connection_reinit_timer;
383 Player *myplayer = m_env.getLocalPlayer();
384 FATAL_ERROR_IF(myplayer == NULL, "Local player not found in environment.");
386 // Send TOSERVER_INIT_LEGACY
387 // [0] u16 TOSERVER_INIT_LEGACY
388 // [2] u8 SER_FMT_VER_HIGHEST_READ
389 // [3] u8[20] player_name
390 // [23] u8[28] password (new in some version)
391 // [51] u16 minimum supported network protocol version (added sometime)
392 // [53] u16 maximum supported network protocol version (added later than the previous one)
394 char pName[PLAYERNAME_SIZE];
395 char pPassword[PASSWORD_SIZE];
396 memset(pName, 0, PLAYERNAME_SIZE * sizeof(char));
397 memset(pPassword, 0, PASSWORD_SIZE * sizeof(char));
399 std::string hashed_password = translatePassword(myplayer->getName(), m_password);
400 snprintf(pName, PLAYERNAME_SIZE, "%s", myplayer->getName());
401 snprintf(pPassword, PASSWORD_SIZE, "%s", hashed_password.c_str());
403 sendLegacyInit(pName, pPassword);
404 if (LATEST_PROTOCOL_VERSION >= 25)
405 sendInit(myplayer->getName());
408 // Not connected, return
413 Do stuff if connected
417 Run Map's timers and unload unused data
419 const float map_timer_and_unload_dtime = 5.25;
420 if(m_map_timer_and_unload_interval.step(dtime, map_timer_and_unload_dtime)) {
421 ScopeProfiler sp(g_profiler, "Client: map timer and unload");
422 std::vector<v3s16> deleted_blocks;
423 m_env.getMap().timerUpdate(map_timer_and_unload_dtime,
424 g_settings->getFloat("client_unload_unused_data_timeout"),
425 g_settings->getS32("client_mapblock_limit"),
430 NOTE: This loop is intentionally iterated the way it is.
433 std::vector<v3s16>::iterator i = deleted_blocks.begin();
434 std::vector<v3s16> sendlist;
436 if(sendlist.size() == 255 || i == deleted_blocks.end()) {
447 sendDeletedBlocks(sendlist);
449 if(i == deleted_blocks.end())
455 sendlist.push_back(*i);
463 // Control local player (0ms)
464 LocalPlayer *player = m_env.getLocalPlayer();
465 assert(player != NULL);
466 player->applyControl(dtime);
475 ClientEnvEvent event = m_env.getClientEvent();
476 if(event.type == CEE_NONE) {
479 else if(event.type == CEE_PLAYER_DAMAGE) {
480 if(m_ignore_damage_timer <= 0) {
481 u8 damage = event.player_damage.amount;
483 if(event.player_damage.send_to_server)
486 // Add to ClientEvent queue
488 event.type = CE_PLAYER_DAMAGE;
489 event.player_damage.amount = damage;
490 m_client_event_queue.push(event);
493 else if(event.type == CEE_PLAYER_BREATH) {
494 u16 breath = event.player_breath.amount;
502 float &counter = m_avg_rtt_timer;
506 // connectedAndInitialized() is true, peer exists.
507 float avg_rtt = getRTT();
508 infostream << "Client: avg_rtt=" << avg_rtt << std::endl;
512 Send player position to server
515 float &counter = m_playerpos_send_timer;
517 if((m_state == LC_Ready) && (counter >= m_recommended_send_interval))
525 Replace updated meshes
528 int num_processed_meshes = 0;
529 while (!m_mesh_update_thread.m_queue_out.empty())
531 num_processed_meshes++;
533 MinimapMapblock *minimap_mapblock = NULL;
534 bool do_mapper_update = true;
536 MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_frontNoEx();
537 MapBlock *block = m_env.getMap().getBlockNoCreateNoEx(r.p);
539 // Delete the old mesh
540 if (block->mesh != NULL) {
546 minimap_mapblock = r.mesh->moveMinimapMapblock();
547 if (minimap_mapblock == NULL)
548 do_mapper_update = false;
551 if (r.mesh && r.mesh->getMesh()->getMeshBufferCount() == 0) {
554 // Replace with the new mesh
555 block->mesh = r.mesh;
561 if (do_mapper_update)
562 m_mapper->addBlock(r.p, minimap_mapblock);
564 if (r.ack_block_to_server) {
574 if (num_processed_meshes > 0)
575 g_profiler->graphAdd("num_processed_meshes", num_processed_meshes);
581 if (m_media_downloader && m_media_downloader->isStarted()) {
582 m_media_downloader->step(this);
583 if (m_media_downloader->isDone()) {
585 delete m_media_downloader;
586 m_media_downloader = NULL;
591 If the server didn't update the inventory in a while, revert
592 the local inventory (so the player notices the lag problem
593 and knows something is wrong).
595 if(m_inventory_from_server)
597 float interval = 10.0;
598 float count_before = floor(m_inventory_from_server_age / interval);
600 m_inventory_from_server_age += dtime;
602 float count_after = floor(m_inventory_from_server_age / interval);
604 if(count_after != count_before)
606 // Do this every <interval> seconds after TOCLIENT_INVENTORY
607 // Reset the locally changed inventory to the authoritative inventory
608 Player *player = m_env.getLocalPlayer();
609 player->inventory = *m_inventory_from_server;
610 m_inventory_updated = true;
615 Update positions of sounds attached to objects
618 for(std::map<int, u16>::iterator
619 i = m_sounds_to_objects.begin();
620 i != m_sounds_to_objects.end(); i++)
622 int client_id = i->first;
623 u16 object_id = i->second;
624 ClientActiveObject *cao = m_env.getActiveObject(object_id);
627 v3f pos = cao->getPosition();
628 m_sound->updateSoundPosition(client_id, pos);
633 Handle removed remotely initiated sounds
635 m_removed_sounds_check_timer += dtime;
636 if(m_removed_sounds_check_timer >= 2.32) {
637 m_removed_sounds_check_timer = 0;
638 // Find removed sounds and clear references to them
639 std::vector<s32> removed_server_ids;
640 for(std::map<s32, int>::iterator
641 i = m_sounds_server_to_client.begin();
642 i != m_sounds_server_to_client.end();) {
643 s32 server_id = i->first;
644 int client_id = i->second;
646 if(!m_sound->soundExists(client_id)) {
647 m_sounds_server_to_client.erase(server_id);
648 m_sounds_client_to_server.erase(client_id);
649 m_sounds_to_objects.erase(client_id);
650 removed_server_ids.push_back(server_id);
655 if(!removed_server_ids.empty()) {
656 sendRemovedSounds(removed_server_ids);
661 if (m_localdb && m_localdb_save_interval.step(dtime,
662 m_cache_save_interval)) {
663 m_localdb->endSave();
664 m_localdb->beginSave();
668 bool Client::loadMedia(const std::string &data, const std::string &filename)
670 // Silly irrlicht's const-incorrectness
671 Buffer<char> data_rw(data.c_str(), data.size());
675 const char *image_ext[] = {
676 ".png", ".jpg", ".bmp", ".tga",
677 ".pcx", ".ppm", ".psd", ".wal", ".rgb",
680 name = removeStringEnd(filename, image_ext);
683 verbosestream<<"Client: Attempting to load image "
684 <<"file \""<<filename<<"\""<<std::endl;
686 io::IFileSystem *irrfs = m_device->getFileSystem();
687 video::IVideoDriver *vdrv = m_device->getVideoDriver();
689 // Create an irrlicht memory file
690 io::IReadFile *rfile = irrfs->createMemoryReadFile(
691 *data_rw, data_rw.getSize(), "_tempreadfile");
693 FATAL_ERROR_IF(!rfile, "Could not create irrlicht memory file.");
696 video::IImage *img = vdrv->createImageFromFile(rfile);
698 errorstream<<"Client: Cannot create image from data of "
699 <<"file \""<<filename<<"\""<<std::endl;
704 m_tsrc->insertSourceImage(filename, img);
711 const char *sound_ext[] = {
712 ".0.ogg", ".1.ogg", ".2.ogg", ".3.ogg", ".4.ogg",
713 ".5.ogg", ".6.ogg", ".7.ogg", ".8.ogg", ".9.ogg",
716 name = removeStringEnd(filename, sound_ext);
719 verbosestream<<"Client: Attempting to load sound "
720 <<"file \""<<filename<<"\""<<std::endl;
721 m_sound->loadSoundData(name, data);
725 const char *model_ext[] = {
726 ".x", ".b3d", ".md2", ".obj",
729 name = removeStringEnd(filename, model_ext);
732 verbosestream<<"Client: Storing model into memory: "
733 <<"\""<<filename<<"\""<<std::endl;
734 if(m_mesh_data.count(filename))
735 errorstream<<"Multiple models with name \""<<filename.c_str()
736 <<"\" found; replacing previous model"<<std::endl;
737 m_mesh_data[filename] = data;
741 errorstream<<"Client: Don't know how to load file \""
742 <<filename<<"\""<<std::endl;
746 // Virtual methods from con::PeerHandler
747 void Client::peerAdded(con::Peer *peer)
749 infostream << "Client::peerAdded(): peer->id="
750 << peer->id << std::endl;
752 void Client::deletingPeer(con::Peer *peer, bool timeout)
754 infostream << "Client::deletingPeer(): "
755 "Server Peer is getting deleted "
756 << "(timeout=" << timeout << ")" << std::endl;
759 m_access_denied = true;
760 m_access_denied_reason = gettext("Connection timed out.");
766 u16 number of files requested
772 void Client::request_media(const std::vector<std::string> &file_requests)
774 std::ostringstream os(std::ios_base::binary);
775 writeU16(os, TOSERVER_REQUEST_MEDIA);
776 size_t file_requests_size = file_requests.size();
778 FATAL_ERROR_IF(file_requests_size > 0xFFFF, "Unsupported number of file requests");
780 // Packet dynamicly resized
781 NetworkPacket pkt(TOSERVER_REQUEST_MEDIA, 2 + 0);
783 pkt << (u16) (file_requests_size & 0xFFFF);
785 for(std::vector<std::string>::const_iterator i = file_requests.begin();
786 i != file_requests.end(); ++i) {
792 infostream << "Client: Sending media request list to server ("
793 << file_requests.size() << " files. packet size)" << std::endl;
796 void Client::received_media()
798 NetworkPacket pkt(TOSERVER_RECEIVED_MEDIA, 0);
800 infostream << "Client: Notifying server that we received all media"
804 void Client::initLocalMapSaving(const Address &address,
805 const std::string &hostname,
806 bool is_local_server)
808 if (!g_settings->getBool("enable_local_map_saving") || is_local_server) {
812 const std::string world_path = porting::path_user
813 + DIR_DELIM + "worlds"
814 + DIR_DELIM + "server_"
815 + hostname + "_" + to_string(address.getPort());
817 fs::CreateAllDirs(world_path);
819 m_localdb = new Database_SQLite3(world_path);
820 m_localdb->beginSave();
821 actionstream << "Local map saving started, map will be saved at '" << world_path << "'" << std::endl;
824 void Client::ReceiveAll()
826 DSTACK(__FUNCTION_NAME);
827 u32 start_ms = porting::getTimeMs();
830 // Limit time even if there would be huge amounts of data to
832 if(porting::getTimeMs() > start_ms + 100)
837 g_profiler->graphAdd("client_received_packets", 1);
839 catch(con::NoIncomingDataException &e) {
842 catch(con::InvalidIncomingDataException &e) {
843 infostream<<"Client::ReceiveAll(): "
844 "InvalidIncomingDataException: what()="
845 <<e.what()<<std::endl;
850 void Client::Receive()
852 DSTACK(__FUNCTION_NAME);
858 inline void Client::handleCommand(NetworkPacket* pkt)
860 const ToClientCommandHandler& opHandle = toClientCommandTable[pkt->getCommand()];
861 (this->*opHandle.handler)(pkt);
865 sender_peer_id given to this shall be quaranteed to be a valid peer
867 void Client::ProcessData(NetworkPacket *pkt)
869 DSTACK(__FUNCTION_NAME);
871 ToClientCommand command = (ToClientCommand) pkt->getCommand();
872 u32 sender_peer_id = pkt->getPeerId();
874 //infostream<<"Client: received command="<<command<<std::endl;
875 m_packetcounter.add((u16)command);
878 If this check is removed, be sure to change the queue
879 system to know the ids
881 if(sender_peer_id != PEER_ID_SERVER) {
882 infostream << "Client::ProcessData(): Discarding data not "
883 "coming from server: peer_id=" << sender_peer_id
888 // Command must be handled into ToClientCommandHandler
889 if (command >= TOCLIENT_NUM_MSG_TYPES) {
890 infostream << "Client: Ignoring unknown command "
891 << command << std::endl;
896 * Those packets are handled before m_server_ser_ver is set, it's normal
897 * But we must use the new ToClientConnectionState in the future,
900 if(toClientCommandTable[command].state == TOCLIENT_STATE_NOT_CONNECTED) {
905 if(m_server_ser_ver == SER_FMT_VER_INVALID) {
906 infostream << "Client: Server serialization"
907 " format invalid or not initialized."
908 " Skipping incoming command=" << command << std::endl;
913 Handle runtime commands
919 void Client::Send(NetworkPacket* pkt)
921 m_con.Send(PEER_ID_SERVER,
922 serverCommandFactoryTable[pkt->getCommand()].channel,
924 serverCommandFactoryTable[pkt->getCommand()].reliable);
927 void Client::interact(u8 action, const PointedThing& pointed)
929 if(m_state != LC_Ready) {
930 errorstream << "Client::interact() "
931 "Canceled (not connected)"
940 [5] u32 length of the next item
941 [9] serialized PointedThing
943 0: start digging (from undersurface) or use
944 1: stop digging (all parameters ignored)
946 3: place block or item (to abovesurface)
950 NetworkPacket pkt(TOSERVER_INTERACT, 1 + 2 + 0);
953 pkt << (u16)getPlayerItem();
955 std::ostringstream tmp_os(std::ios::binary);
956 pointed.serialize(tmp_os);
958 pkt.putLongString(tmp_os.str());
963 void Client::deleteAuthData()
968 switch (m_chosen_auth_mech) {
969 case AUTH_MECHANISM_FIRST_SRP:
971 case AUTH_MECHANISM_SRP:
972 case AUTH_MECHANISM_LEGACY_PASSWORD:
973 srp_user_delete((SRPUser *) m_auth_data);
976 case AUTH_MECHANISM_NONE:
979 m_chosen_auth_mech = AUTH_MECHANISM_NONE;
983 AuthMechanism Client::choseAuthMech(const u32 mechs)
985 if (mechs & AUTH_MECHANISM_SRP)
986 return AUTH_MECHANISM_SRP;
988 if (mechs & AUTH_MECHANISM_FIRST_SRP)
989 return AUTH_MECHANISM_FIRST_SRP;
991 if (mechs & AUTH_MECHANISM_LEGACY_PASSWORD)
992 return AUTH_MECHANISM_LEGACY_PASSWORD;
994 return AUTH_MECHANISM_NONE;
997 void Client::sendLegacyInit(const char* playerName, const char* playerPassword)
999 NetworkPacket pkt(TOSERVER_INIT_LEGACY,
1000 1 + PLAYERNAME_SIZE + PASSWORD_SIZE + 2 + 2);
1002 pkt << (u8) SER_FMT_VER_HIGHEST_READ;
1003 pkt.putRawString(playerName,PLAYERNAME_SIZE);
1004 pkt.putRawString(playerPassword, PASSWORD_SIZE);
1005 pkt << (u16) CLIENT_PROTOCOL_VERSION_MIN << (u16) CLIENT_PROTOCOL_VERSION_MAX;
1010 void Client::sendInit(const std::string &playerName)
1012 NetworkPacket pkt(TOSERVER_INIT, 1 + 2 + 2 + (1 + playerName.size()));
1014 // we don't support network compression yet
1015 u16 supp_comp_modes = NETPROTO_COMPRESSION_NONE;
1016 pkt << (u8) SER_FMT_VER_HIGHEST_READ << (u16) supp_comp_modes;
1017 pkt << (u16) CLIENT_PROTOCOL_VERSION_MIN << (u16) CLIENT_PROTOCOL_VERSION_MAX;
1023 void Client::startAuth(AuthMechanism chosen_auth_mechanism)
1025 m_chosen_auth_mech = chosen_auth_mechanism;
1027 switch (chosen_auth_mechanism) {
1028 case AUTH_MECHANISM_FIRST_SRP: {
1029 // send srp verifier to server
1030 NetworkPacket resp_pkt(TOSERVER_FIRST_SRP, 0);
1031 char *salt, *bytes_v;
1032 std::size_t len_salt, len_v;
1034 getSRPVerifier(getPlayerName(), m_password,
1035 &salt, &len_salt, &bytes_v, &len_v);
1037 << std::string((char*)salt, len_salt)
1038 << std::string((char*)bytes_v, len_v)
1039 << (u8)((m_password == "") ? 1 : 0);
1045 case AUTH_MECHANISM_SRP:
1046 case AUTH_MECHANISM_LEGACY_PASSWORD: {
1049 if (chosen_auth_mechanism == AUTH_MECHANISM_LEGACY_PASSWORD) {
1050 m_password = translatePassword(getPlayerName(), m_password);
1054 std::string playername_u = lowercase(getPlayerName());
1055 m_auth_data = srp_user_new(SRP_SHA256, SRP_NG_2048,
1056 getPlayerName().c_str(), playername_u.c_str(),
1057 (const unsigned char *) m_password.c_str(),
1058 m_password.length(), NULL, NULL);
1061 srp_user_start_authentication((struct SRPUser *) m_auth_data,
1062 NULL, NULL, 0, (unsigned char **) &bytes_A, &len_A);
1064 NetworkPacket resp_pkt(TOSERVER_SRP_BYTES_A, 0);
1065 resp_pkt << std::string(bytes_A, len_A) << based_on;
1069 case AUTH_MECHANISM_NONE:
1070 break; // not handled in this method
1074 void Client::sendDeletedBlocks(std::vector<v3s16> &blocks)
1076 NetworkPacket pkt(TOSERVER_DELETEDBLOCKS, 1 + sizeof(v3s16) * blocks.size());
1078 pkt << (u8) blocks.size();
1081 for(std::vector<v3s16>::iterator
1083 j != blocks.end(); ++j) {
1091 void Client::sendGotBlocks(v3s16 block)
1093 NetworkPacket pkt(TOSERVER_GOTBLOCKS, 1 + 6);
1094 pkt << (u8) 1 << block;
1098 void Client::sendRemovedSounds(std::vector<s32> &soundList)
1100 size_t server_ids = soundList.size();
1101 assert(server_ids <= 0xFFFF);
1103 NetworkPacket pkt(TOSERVER_REMOVED_SOUNDS, 2 + server_ids * 4);
1105 pkt << (u16) (server_ids & 0xFFFF);
1107 for(std::vector<s32>::iterator i = soundList.begin();
1108 i != soundList.end(); i++)
1114 void Client::sendNodemetaFields(v3s16 p, const std::string &formname,
1115 const StringMap &fields)
1117 size_t fields_size = fields.size();
1119 FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of nodemeta fields");
1121 NetworkPacket pkt(TOSERVER_NODEMETA_FIELDS, 0);
1123 pkt << p << formname << (u16) (fields_size & 0xFFFF);
1125 StringMap::const_iterator it;
1126 for (it = fields.begin(); it != fields.end(); ++it) {
1127 const std::string &name = it->first;
1128 const std::string &value = it->second;
1130 pkt.putLongString(value);
1136 void Client::sendInventoryFields(const std::string &formname,
1137 const StringMap &fields)
1139 size_t fields_size = fields.size();
1140 FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of inventory fields");
1142 NetworkPacket pkt(TOSERVER_INVENTORY_FIELDS, 0);
1143 pkt << formname << (u16) (fields_size & 0xFFFF);
1145 StringMap::const_iterator it;
1146 for (it = fields.begin(); it != fields.end(); ++it) {
1147 const std::string &name = it->first;
1148 const std::string &value = it->second;
1150 pkt.putLongString(value);
1156 void Client::sendInventoryAction(InventoryAction *a)
1158 std::ostringstream os(std::ios_base::binary);
1163 std::string s = os.str();
1165 NetworkPacket pkt(TOSERVER_INVENTORY_ACTION, s.size());
1166 pkt.putRawString(s.c_str(),s.size());
1171 void Client::sendChatMessage(const std::wstring &message)
1173 NetworkPacket pkt(TOSERVER_CHAT_MESSAGE, 2 + message.size() * sizeof(u16));
1180 void Client::sendChangePassword(const std::string &oldpassword,
1181 const std::string &newpassword)
1183 Player *player = m_env.getLocalPlayer();
1187 std::string playername = player->getName();
1188 if (m_proto_ver >= 25) {
1189 // get into sudo mode and then send new password to server
1190 m_password = oldpassword;
1191 m_new_password = newpassword;
1192 startAuth(choseAuthMech(m_sudo_auth_methods));
1194 std::string oldpwd = translatePassword(playername, oldpassword);
1195 std::string newpwd = translatePassword(playername, newpassword);
1197 NetworkPacket pkt(TOSERVER_PASSWORD_LEGACY, 2 * PASSWORD_SIZE);
1199 for (u8 i = 0; i < PASSWORD_SIZE; i++) {
1200 pkt << (u8) (i < oldpwd.length() ? oldpwd[i] : 0);
1203 for (u8 i = 0; i < PASSWORD_SIZE; i++) {
1204 pkt << (u8) (i < newpwd.length() ? newpwd[i] : 0);
1211 void Client::sendDamage(u8 damage)
1213 DSTACK(__FUNCTION_NAME);
1215 NetworkPacket pkt(TOSERVER_DAMAGE, sizeof(u8));
1220 void Client::sendBreath(u16 breath)
1222 DSTACK(__FUNCTION_NAME);
1224 NetworkPacket pkt(TOSERVER_BREATH, sizeof(u16));
1229 void Client::sendRespawn()
1231 DSTACK(__FUNCTION_NAME);
1233 NetworkPacket pkt(TOSERVER_RESPAWN, 0);
1237 void Client::sendReady()
1239 DSTACK(__FUNCTION_NAME);
1241 NetworkPacket pkt(TOSERVER_CLIENT_READY,
1242 1 + 1 + 1 + 1 + 2 + sizeof(char) * strlen(g_version_hash));
1244 pkt << (u8) VERSION_MAJOR << (u8) VERSION_MINOR << (u8) VERSION_PATCH
1245 << (u8) 0 << (u16) strlen(g_version_hash);
1247 pkt.putRawString(g_version_hash, (u16) strlen(g_version_hash));
1251 void Client::sendPlayerPos()
1253 LocalPlayer *myplayer = m_env.getLocalPlayer();
1254 if(myplayer == NULL)
1257 // Save bandwidth by only updating position when something changed
1258 if(myplayer->last_position == myplayer->getPosition() &&
1259 myplayer->last_speed == myplayer->getSpeed() &&
1260 myplayer->last_pitch == myplayer->getPitch() &&
1261 myplayer->last_yaw == myplayer->getYaw() &&
1262 myplayer->last_keyPressed == myplayer->keyPressed)
1265 myplayer->last_position = myplayer->getPosition();
1266 myplayer->last_speed = myplayer->getSpeed();
1267 myplayer->last_pitch = myplayer->getPitch();
1268 myplayer->last_yaw = myplayer->getYaw();
1269 myplayer->last_keyPressed = myplayer->keyPressed;
1273 //JMutexAutoLock lock(m_con_mutex); //bulk comment-out
1274 our_peer_id = m_con.GetPeerID();
1277 // Set peer id if not set already
1278 if(myplayer->peer_id == PEER_ID_INEXISTENT)
1279 myplayer->peer_id = our_peer_id;
1281 assert(myplayer->peer_id == our_peer_id);
1283 v3f pf = myplayer->getPosition();
1284 v3f sf = myplayer->getSpeed();
1285 s32 pitch = myplayer->getPitch() * 100;
1286 s32 yaw = myplayer->getYaw() * 100;
1287 u32 keyPressed = myplayer->keyPressed;
1289 v3s32 position(pf.X*100, pf.Y*100, pf.Z*100);
1290 v3s32 speed(sf.X*100, sf.Y*100, sf.Z*100);
1293 [0] v3s32 position*100
1294 [12] v3s32 speed*100
1295 [12+12] s32 pitch*100
1296 [12+12+4] s32 yaw*100
1297 [12+12+4+4] u32 keyPressed
1300 NetworkPacket pkt(TOSERVER_PLAYERPOS, 12 + 12 + 4 + 4 + 4);
1302 pkt << position << speed << pitch << yaw << keyPressed;
1307 void Client::sendPlayerItem(u16 item)
1309 Player *myplayer = m_env.getLocalPlayer();
1310 if(myplayer == NULL)
1313 u16 our_peer_id = m_con.GetPeerID();
1315 // Set peer id if not set already
1316 if(myplayer->peer_id == PEER_ID_INEXISTENT)
1317 myplayer->peer_id = our_peer_id;
1318 assert(myplayer->peer_id == our_peer_id);
1320 NetworkPacket pkt(TOSERVER_PLAYERITEM, 2);
1327 void Client::removeNode(v3s16 p)
1329 std::map<v3s16, MapBlock*> modified_blocks;
1332 m_env.getMap().removeNodeAndUpdate(p, modified_blocks);
1334 catch(InvalidPositionException &e) {
1337 for(std::map<v3s16, MapBlock *>::iterator
1338 i = modified_blocks.begin();
1339 i != modified_blocks.end(); ++i) {
1340 addUpdateMeshTaskWithEdge(i->first, false, true);
1344 void Client::addNode(v3s16 p, MapNode n, bool remove_metadata)
1346 //TimeTaker timer1("Client::addNode()");
1348 std::map<v3s16, MapBlock*> modified_blocks;
1351 //TimeTaker timer3("Client::addNode(): addNodeAndUpdate");
1352 m_env.getMap().addNodeAndUpdate(p, n, modified_blocks, remove_metadata);
1354 catch(InvalidPositionException &e) {
1357 for(std::map<v3s16, MapBlock *>::iterator
1358 i = modified_blocks.begin();
1359 i != modified_blocks.end(); ++i) {
1360 addUpdateMeshTaskWithEdge(i->first, false, true);
1364 void Client::setPlayerControl(PlayerControl &control)
1366 LocalPlayer *player = m_env.getLocalPlayer();
1367 assert(player != NULL);
1368 player->control = control;
1371 void Client::selectPlayerItem(u16 item)
1373 m_playeritem = item;
1374 m_inventory_updated = true;
1375 sendPlayerItem(item);
1378 // Returns true if the inventory of the local player has been
1379 // updated from the server. If it is true, it is set to false.
1380 bool Client::getLocalInventoryUpdated()
1382 bool updated = m_inventory_updated;
1383 m_inventory_updated = false;
1387 // Copies the inventory of the local player to parameter
1388 void Client::getLocalInventory(Inventory &dst)
1390 Player *player = m_env.getLocalPlayer();
1391 assert(player != NULL);
1392 dst = player->inventory;
1395 Inventory* Client::getInventory(const InventoryLocation &loc)
1398 case InventoryLocation::UNDEFINED:
1401 case InventoryLocation::CURRENT_PLAYER:
1403 Player *player = m_env.getLocalPlayer();
1404 assert(player != NULL);
1405 return &player->inventory;
1408 case InventoryLocation::PLAYER:
1410 Player *player = m_env.getPlayer(loc.name.c_str());
1413 return &player->inventory;
1416 case InventoryLocation::NODEMETA:
1418 NodeMetadata *meta = m_env.getMap().getNodeMetadata(loc.p);
1421 return meta->getInventory();
1424 case InventoryLocation::DETACHED:
1426 if(m_detached_inventories.count(loc.name) == 0)
1428 return m_detached_inventories[loc.name];
1432 FATAL_ERROR("Invalid inventory location type.");
1438 void Client::inventoryAction(InventoryAction *a)
1441 Send it to the server
1443 sendInventoryAction(a);
1446 Predict some local inventory changes
1448 a->clientApply(this, this);
1454 ClientActiveObject * Client::getSelectedActiveObject(
1456 v3f from_pos_f_on_map,
1457 core::line3d<f32> shootline_on_map
1460 std::vector<DistanceSortedActiveObject> objects;
1462 m_env.getActiveObjects(from_pos_f_on_map, max_d, objects);
1465 // After this, the closest object is the first in the array.
1466 std::sort(objects.begin(), objects.end());
1468 for(unsigned int i=0; i<objects.size(); i++)
1470 ClientActiveObject *obj = objects[i].obj;
1472 core::aabbox3d<f32> *selection_box = obj->getSelectionBox();
1473 if(selection_box == NULL)
1476 v3f pos = obj->getPosition();
1478 core::aabbox3d<f32> offsetted_box(
1479 selection_box->MinEdge + pos,
1480 selection_box->MaxEdge + pos
1483 if(offsetted_box.intersectsWithLine(shootline_on_map))
1492 std::list<std::string> Client::getConnectedPlayerNames()
1494 return m_env.getPlayerNames();
1497 float Client::getAnimationTime()
1499 return m_animation_time;
1502 int Client::getCrackLevel()
1504 return m_crack_level;
1507 void Client::setHighlighted(v3s16 pos, bool show_highlighted)
1509 m_show_highlighted = show_highlighted;
1510 v3s16 old_highlighted_pos = m_highlighted_pos;
1511 m_highlighted_pos = pos;
1512 addUpdateMeshTaskForNode(old_highlighted_pos, false, true);
1513 addUpdateMeshTaskForNode(m_highlighted_pos, false, true);
1516 void Client::setCrack(int level, v3s16 pos)
1518 int old_crack_level = m_crack_level;
1519 v3s16 old_crack_pos = m_crack_pos;
1521 m_crack_level = level;
1524 if(old_crack_level >= 0 && (level < 0 || pos != old_crack_pos))
1527 addUpdateMeshTaskForNode(old_crack_pos, false, true);
1529 if(level >= 0 && (old_crack_level < 0 || pos != old_crack_pos))
1532 addUpdateMeshTaskForNode(pos, false, true);
1538 Player *player = m_env.getLocalPlayer();
1539 assert(player != NULL);
1543 u16 Client::getBreath()
1545 Player *player = m_env.getLocalPlayer();
1546 assert(player != NULL);
1547 return player->getBreath();
1550 bool Client::getChatMessage(std::wstring &message)
1552 if(m_chat_queue.size() == 0)
1554 message = m_chat_queue.front();
1559 void Client::typeChatMessage(const std::wstring &message)
1561 // Discard empty line
1566 sendChatMessage(message);
1569 if (message[0] == L'/')
1571 m_chat_queue.push((std::wstring)L"issued command: " + message);
1575 LocalPlayer *player = m_env.getLocalPlayer();
1576 assert(player != NULL);
1577 std::wstring name = narrow_to_wide(player->getName());
1578 m_chat_queue.push((std::wstring)L"<" + name + L"> " + message);
1582 void Client::addUpdateMeshTask(v3s16 p, bool ack_to_server, bool urgent)
1584 MapBlock *b = m_env.getMap().getBlockNoCreateNoEx(p);
1589 Create a task to update the mesh of the block
1592 MeshMakeData *data = new MeshMakeData(this, m_cache_enable_shaders);
1595 //TimeTaker timer("data fill");
1597 // Debug: 1-6ms, avg=2ms
1599 data->setCrack(m_crack_level, m_crack_pos);
1600 data->setHighlighted(m_highlighted_pos, m_show_highlighted);
1601 data->setSmoothLighting(m_cache_smooth_lighting);
1604 // Add task to queue
1605 m_mesh_update_thread.enqueueUpdate(p, data, ack_to_server, urgent);
1608 void Client::addUpdateMeshTaskWithEdge(v3s16 blockpos, bool ack_to_server, bool urgent)
1611 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1613 catch(InvalidPositionException &e){}
1616 for (int i=0;i<6;i++)
1619 v3s16 p = blockpos + g_6dirs[i];
1620 addUpdateMeshTask(p, false, urgent);
1622 catch(InvalidPositionException &e){}
1626 void Client::addUpdateMeshTaskForNode(v3s16 nodepos, bool ack_to_server, bool urgent)
1630 infostream<<"Client::addUpdateMeshTaskForNode(): "
1631 <<"("<<p.X<<","<<p.Y<<","<<p.Z<<")"
1635 v3s16 blockpos = getNodeBlockPos(nodepos);
1636 v3s16 blockpos_relative = blockpos * MAP_BLOCKSIZE;
1639 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1641 catch(InvalidPositionException &e) {}
1644 if(nodepos.X == blockpos_relative.X){
1646 v3s16 p = blockpos + v3s16(-1,0,0);
1647 addUpdateMeshTask(p, false, urgent);
1649 catch(InvalidPositionException &e){}
1652 if(nodepos.Y == blockpos_relative.Y){
1654 v3s16 p = blockpos + v3s16(0,-1,0);
1655 addUpdateMeshTask(p, false, urgent);
1657 catch(InvalidPositionException &e){}
1660 if(nodepos.Z == blockpos_relative.Z){
1662 v3s16 p = blockpos + v3s16(0,0,-1);
1663 addUpdateMeshTask(p, false, urgent);
1665 catch(InvalidPositionException &e){}
1669 ClientEvent Client::getClientEvent()
1672 if(m_client_event_queue.size() == 0) {
1673 event.type = CE_NONE;
1676 event = m_client_event_queue.front();
1677 m_client_event_queue.pop();
1682 float Client::mediaReceiveProgress()
1684 if (m_media_downloader)
1685 return m_media_downloader->getProgress();
1687 return 1.0; // downloader only exists when not yet done
1690 typedef struct TextureUpdateArgs {
1691 IrrlichtDevice *device;
1692 gui::IGUIEnvironment *guienv;
1695 const wchar_t* text_base;
1696 } TextureUpdateArgs;
1698 void texture_update_progress(void *args, u32 progress, u32 max_progress)
1700 TextureUpdateArgs* targs = (TextureUpdateArgs*) args;
1701 u16 cur_percent = ceil(progress / (double) max_progress * 100.);
1703 // update the loading menu -- if neccessary
1704 bool do_draw = false;
1705 u32 time_ms = targs->last_time_ms;
1706 if (cur_percent != targs->last_percent) {
1707 targs->last_percent = cur_percent;
1708 time_ms = getTimeMs();
1709 // only draw when the user will notice something:
1710 do_draw = (time_ms - targs->last_time_ms > 100);
1714 targs->last_time_ms = time_ms;
1715 std::basic_stringstream<wchar_t> strm;
1716 strm << targs->text_base << " " << targs->last_percent << "%...";
1717 draw_load_screen(strm.str(), targs->device, targs->guienv, 0,
1718 72 + (u16) ((18. / 100.) * (double) targs->last_percent));
1722 void Client::afterContentReceived(IrrlichtDevice *device)
1724 infostream<<"Client::afterContentReceived() started"<<std::endl;
1725 assert(m_itemdef_received); // pre-condition
1726 assert(m_nodedef_received); // pre-condition
1727 assert(mediaReceived()); // pre-condition
1729 const wchar_t* text = wgettext("Loading textures...");
1731 // Clear cached pre-scaled 2D GUI images, as this cache
1732 // might have images with the same name but different
1733 // content from previous sessions.
1734 guiScalingCacheClear(device->getVideoDriver());
1736 // Rebuild inherited images and recreate textures
1737 infostream<<"- Rebuilding images and textures"<<std::endl;
1738 draw_load_screen(text,device, guienv, 0, 70);
1739 m_tsrc->rebuildImagesAndTextures();
1743 infostream<<"- Rebuilding shaders"<<std::endl;
1744 text = wgettext("Rebuilding shaders...");
1745 draw_load_screen(text, device, guienv, 0, 71);
1746 m_shsrc->rebuildShaders();
1749 // Update node aliases
1750 infostream<<"- Updating node aliases"<<std::endl;
1751 text = wgettext("Initializing nodes...");
1752 draw_load_screen(text, device, guienv, 0, 72);
1753 m_nodedef->updateAliases(m_itemdef);
1754 std::string texture_path = g_settings->get("texture_path");
1755 if (texture_path != "" && fs::IsDir(texture_path))
1756 m_nodedef->applyTextureOverrides(texture_path + DIR_DELIM + "override.txt");
1757 m_nodedef->setNodeRegistrationStatus(true);
1758 m_nodedef->runNodeResolveCallbacks();
1761 // Update node textures and assign shaders to each tile
1762 infostream<<"- Updating node textures"<<std::endl;
1763 TextureUpdateArgs tu_args;
1764 tu_args.device = device;
1765 tu_args.guienv = guienv;
1766 tu_args.last_time_ms = getTimeMs();
1767 tu_args.last_percent = 0;
1768 tu_args.text_base = wgettext("Initializing nodes");
1769 m_nodedef->updateTextures(this, texture_update_progress, &tu_args);
1770 delete[] tu_args.text_base;
1772 // Preload item textures and meshes if configured to
1773 if(g_settings->getBool("preload_item_visuals"))
1775 verbosestream<<"Updating item textures and meshes"<<std::endl;
1776 text = wgettext("Item textures...");
1777 draw_load_screen(text, device, guienv, 0, 0);
1778 std::set<std::string> names = m_itemdef->getAll();
1779 size_t size = names.size();
1782 for(std::set<std::string>::const_iterator
1783 i = names.begin(); i != names.end(); ++i)
1785 // Asking for these caches the result
1786 m_itemdef->getInventoryTexture(*i, this);
1787 m_itemdef->getWieldMesh(*i, this);
1789 percent = (count * 100 / size * 0.2) + 80;
1790 draw_load_screen(text, device, guienv, 0, percent);
1795 // Start mesh update thread after setting up content definitions
1796 infostream<<"- Starting mesh update thread"<<std::endl;
1797 m_mesh_update_thread.Start();
1801 text = wgettext("Done!");
1802 draw_load_screen(text, device, guienv, 0, 100);
1803 infostream<<"Client::afterContentReceived() done"<<std::endl;
1807 float Client::getRTT(void)
1809 return m_con.getPeerStat(PEER_ID_SERVER,con::AVG_RTT);
1812 float Client::getCurRate(void)
1814 return ( m_con.getLocalStat(con::CUR_INC_RATE) +
1815 m_con.getLocalStat(con::CUR_DL_RATE));
1818 float Client::getAvgRate(void)
1820 return ( m_con.getLocalStat(con::AVG_INC_RATE) +
1821 m_con.getLocalStat(con::AVG_DL_RATE));
1824 void Client::makeScreenshot(IrrlichtDevice *device)
1826 irr::video::IVideoDriver *driver = device->getVideoDriver();
1827 irr::video::IImage* const raw_image = driver->createScreenShot();
1832 time_t t = time(NULL);
1833 struct tm *tm = localtime(&t);
1835 char timetstamp_c[64];
1836 strftime(timetstamp_c, sizeof(timetstamp_c), "%Y%m%d_%H%M%S", tm);
1838 std::string filename_base = g_settings->get("screenshot_path")
1840 + std::string("screenshot_")
1841 + std::string(timetstamp_c);
1842 std::string filename_ext = ".png";
1843 std::string filename;
1845 // Try to find a unique filename
1846 unsigned serial = 0;
1848 while (serial < SCREENSHOT_MAX_SERIAL_TRIES) {
1849 filename = filename_base + (serial > 0 ? ("_" + itos(serial)) : "") + filename_ext;
1850 std::ifstream tmp(filename.c_str());
1852 break; // File did not apparently exist, we'll go with it
1856 if (serial == SCREENSHOT_MAX_SERIAL_TRIES) {
1857 infostream << "Could not find suitable filename for screenshot" << std::endl;
1859 irr::video::IImage* const image =
1860 driver->createImage(video::ECF_R8G8B8, raw_image->getDimension());
1863 raw_image->copyTo(image);
1865 std::ostringstream sstr;
1866 if (driver->writeImageToFile(image, filename.c_str())) {
1867 sstr << "Saved screenshot to '" << filename << "'";
1869 sstr << "Failed to save screenshot '" << filename << "'";
1871 m_chat_queue.push(narrow_to_wide(sstr.str()));
1872 infostream << sstr.str() << std::endl;
1880 // IGameDef interface
1882 IItemDefManager* Client::getItemDefManager()
1886 INodeDefManager* Client::getNodeDefManager()
1890 ICraftDefManager* Client::getCraftDefManager()
1893 //return m_craftdef;
1895 ITextureSource* Client::getTextureSource()
1899 IShaderSource* Client::getShaderSource()
1903 scene::ISceneManager* Client::getSceneManager()
1905 return m_device->getSceneManager();
1907 u16 Client::allocateUnknownNodeId(const std::string &name)
1909 errorstream << "Client::allocateUnknownNodeId(): "
1910 << "Client cannot allocate node IDs" << std::endl;
1911 FATAL_ERROR("Client allocated unknown node");
1913 return CONTENT_IGNORE;
1915 ISoundManager* Client::getSoundManager()
1919 MtEventManager* Client::getEventManager()
1924 ParticleManager* Client::getParticleManager()
1926 return &m_particle_manager;
1929 scene::IAnimatedMesh* Client::getMesh(const std::string &filename)
1931 StringMap::const_iterator it = m_mesh_data.find(filename);
1932 if (it == m_mesh_data.end()) {
1933 errorstream << "Client::getMesh(): Mesh not found: \"" << filename
1934 << "\"" << std::endl;
1937 const std::string &data = it->second;
1938 scene::ISceneManager *smgr = m_device->getSceneManager();
1940 // Create the mesh, remove it from cache and return it
1941 // This allows unique vertex colors and other properties for each instance
1942 Buffer<char> data_rw(data.c_str(), data.size()); // Const-incorrect Irrlicht
1943 io::IFileSystem *irrfs = m_device->getFileSystem();
1944 io::IReadFile *rfile = irrfs->createMemoryReadFile(
1945 *data_rw, data_rw.getSize(), filename.c_str());
1946 FATAL_ERROR_IF(!rfile, "Could not create/open RAM file");
1948 scene::IAnimatedMesh *mesh = smgr->getMesh(rfile);
1950 // NOTE: By playing with Irrlicht refcounts, maybe we could cache a bunch
1951 // of uniquely named instances and re-use them
1953 smgr->getMeshCache()->removeMesh(mesh);