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.
24 #include <IFileSystem.h>
25 #include "threading/mutex_auto_lock.h"
26 #include "util/auth.h"
27 #include "util/directiontables.h"
28 #include "util/pointedthing.h"
29 #include "util/serialize.h"
30 #include "util/string.h"
33 #include "network/clientopcodes.h"
36 #include "mapblock_mesh.h"
43 #include "nodemetadata.h"
46 #include "clientmap.h"
47 #include "clientmedia.h"
49 #include "IMeshCache.h"
52 #include "drawscene.h"
53 #include "database-sqlite3.h"
54 #include "serialization.h"
55 #include "guiscalingfilter.h"
58 extern gui::IGUIEnvironment* guienv;
64 QueuedMeshUpdate::QueuedMeshUpdate():
67 ack_block_to_server(false)
71 QueuedMeshUpdate::~QueuedMeshUpdate()
81 MeshUpdateQueue::MeshUpdateQueue()
85 MeshUpdateQueue::~MeshUpdateQueue()
87 MutexAutoLock lock(m_mutex);
89 for(std::vector<QueuedMeshUpdate*>::iterator
91 i != m_queue.end(); ++i)
93 QueuedMeshUpdate *q = *i;
99 peer_id=0 adds with nobody to send to
101 void MeshUpdateQueue::addBlock(v3s16 p, MeshMakeData *data, bool ack_block_to_server, bool urgent)
103 DSTACK(FUNCTION_NAME);
105 assert(data); // pre-condition
107 MutexAutoLock lock(m_mutex);
113 Find if block is already in queue.
114 If it is, update the data and quit.
116 for(std::vector<QueuedMeshUpdate*>::iterator
118 i != m_queue.end(); ++i)
120 QueuedMeshUpdate *q = *i;
126 if(ack_block_to_server)
127 q->ack_block_to_server = true;
135 QueuedMeshUpdate *q = new QueuedMeshUpdate;
138 q->ack_block_to_server = ack_block_to_server;
139 m_queue.push_back(q);
142 // Returned pointer must be deleted
143 // Returns NULL if queue is empty
144 QueuedMeshUpdate *MeshUpdateQueue::pop()
146 MutexAutoLock lock(m_mutex);
148 bool must_be_urgent = !m_urgents.empty();
149 for(std::vector<QueuedMeshUpdate*>::iterator
151 i != m_queue.end(); ++i)
153 QueuedMeshUpdate *q = *i;
154 if(must_be_urgent && m_urgents.count(q->p) == 0)
157 m_urgents.erase(q->p);
167 void MeshUpdateThread::enqueueUpdate(v3s16 p, MeshMakeData *data,
168 bool ack_block_to_server, bool urgent)
170 m_queue_in.addBlock(p, data, ack_block_to_server, urgent);
174 void MeshUpdateThread::doUpdate()
177 while ((q = m_queue_in.pop())) {
179 ScopeProfiler sp(g_profiler, "Client: Mesh making");
181 MapBlockMesh *mesh_new = new MapBlockMesh(q->data, m_camera_offset);
186 r.ack_block_to_server = q->ack_block_to_server;
188 m_queue_out.push_back(r);
199 IrrlichtDevice *device,
200 const char *playername,
201 std::string password,
202 MapDrawControl &control,
203 IWritableTextureSource *tsrc,
204 IWritableShaderSource *shsrc,
205 IWritableItemDefManager *itemdef,
206 IWritableNodeDefManager *nodedef,
207 ISoundManager *sound,
208 MtEventManager *event,
211 m_packetcounter_timer(0.0),
212 m_connection_reinit_timer(0.1),
213 m_avg_rtt_timer(0.0),
214 m_playerpos_send_timer(0.0),
215 m_ignore_damage_timer(0.0),
222 m_mesh_update_thread(),
224 new ClientMap(this, control,
225 device->getSceneManager()->getRootSceneNode(),
226 device->getSceneManager(), 666),
227 device->getSceneManager(),
230 m_particle_manager(&m_env),
231 m_con(PROTOCOL_ID, 512, CONNECTION_TIMEOUT, ipv6, this),
234 m_minimap_disabled_by_server(false),
235 m_server_ser_ver(SER_FMT_VER_INVALID),
238 m_inventory_updated(false),
239 m_inventory_from_server(NULL),
240 m_inventory_from_server_age(0.0),
245 m_password(password),
246 m_chosen_auth_mech(AUTH_MECHANISM_NONE),
248 m_access_denied(false),
249 m_access_denied_reconnect(false),
250 m_itemdef_received(false),
251 m_nodedef_received(false),
252 m_media_downloader(new ClientMediaDownloader()),
253 m_time_of_day_set(false),
254 m_last_time_of_day_f(-1),
255 m_time_of_day_update_timer(0),
256 m_recommended_send_interval(0.1),
257 m_removed_sounds_check_timer(0),
262 m_env.setLocalPlayer(new LocalPlayer(this, playername));
264 m_mapper = new Mapper(device, this);
265 m_cache_save_interval = g_settings->getU16("server_map_save_interval");
267 m_cache_smooth_lighting = g_settings->getBool("smooth_lighting");
268 m_cache_enable_shaders = g_settings->getBool("enable_shaders");
269 m_cache_use_tangent_vertices = m_cache_enable_shaders && (
270 g_settings->getBool("enable_bumpmapping") ||
271 g_settings->getBool("enable_parallax_occlusion"));
276 //request all client managed threads to stop
277 m_mesh_update_thread.stop();
278 // Save local server map
280 infostream << "Local map saving ended." << std::endl;
281 m_localdb->endSave();
285 bool Client::isShutdown()
288 if (!m_mesh_update_thread.isRunning()) return true;
297 m_mesh_update_thread.stop();
298 m_mesh_update_thread.wait();
299 while (!m_mesh_update_thread.m_queue_out.empty()) {
300 MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_frontNoEx();
305 delete m_inventory_from_server;
307 // Delete detached inventories
308 for (UNORDERED_MAP<std::string, Inventory*>::iterator
309 i = m_detached_inventories.begin();
310 i != m_detached_inventories.end(); ++i) {
314 // cleanup 3d model meshes on client shutdown
315 while (m_device->getSceneManager()->getMeshCache()->getMeshCount() != 0) {
316 scene::IAnimatedMesh *mesh =
317 m_device->getSceneManager()->getMeshCache()->getMeshByIndex(0);
320 m_device->getSceneManager()->getMeshCache()->removeMesh(mesh);
326 void Client::connect(Address address,
327 const std::string &address_name,
328 bool is_local_server)
330 DSTACK(FUNCTION_NAME);
332 initLocalMapSaving(address, address_name, is_local_server);
334 m_con.SetTimeoutMs(0);
335 m_con.Connect(address);
338 void Client::step(float dtime)
340 DSTACK(FUNCTION_NAME);
346 if(m_ignore_damage_timer > dtime)
347 m_ignore_damage_timer -= dtime;
349 m_ignore_damage_timer = 0.0;
351 m_animation_time += dtime;
352 if(m_animation_time > 60.0)
353 m_animation_time -= 60.0;
355 m_time_of_day_update_timer += dtime;
363 float &counter = m_packetcounter_timer;
369 infostream << "Client packetcounter (" << m_packetcounter_timer
371 m_packetcounter.print(infostream);
372 m_packetcounter.clear();
376 // UGLY hack to fix 2 second startup delay caused by non existent
377 // server client startup synchronization in local server or singleplayer mode
378 static bool initial_step = true;
380 initial_step = false;
382 else if(m_state == LC_Created) {
383 float &counter = m_connection_reinit_timer;
388 LocalPlayer *myplayer = m_env.getLocalPlayer();
389 FATAL_ERROR_IF(myplayer == NULL, "Local player not found in environment.");
391 u16 proto_version_min = g_settings->getFlag("send_pre_v25_init") ?
392 CLIENT_PROTOCOL_VERSION_MIN_LEGACY : CLIENT_PROTOCOL_VERSION_MIN;
394 if (proto_version_min < 25) {
395 // Send TOSERVER_INIT_LEGACY
396 // [0] u16 TOSERVER_INIT_LEGACY
397 // [2] u8 SER_FMT_VER_HIGHEST_READ
398 // [3] u8[20] player_name
399 // [23] u8[28] password (new in some version)
400 // [51] u16 minimum supported network protocol version (added sometime)
401 // [53] u16 maximum supported network protocol version (added later than the previous one)
403 char pName[PLAYERNAME_SIZE];
404 char pPassword[PASSWORD_SIZE];
405 memset(pName, 0, PLAYERNAME_SIZE * sizeof(char));
406 memset(pPassword, 0, PASSWORD_SIZE * sizeof(char));
408 std::string hashed_password = translate_password(myplayer->getName(), m_password);
409 snprintf(pName, PLAYERNAME_SIZE, "%s", myplayer->getName());
410 snprintf(pPassword, PASSWORD_SIZE, "%s", hashed_password.c_str());
412 sendLegacyInit(pName, pPassword);
414 if (CLIENT_PROTOCOL_VERSION_MAX >= 25)
415 sendInit(myplayer->getName());
418 // Not connected, return
423 Do stuff if connected
427 Run Map's timers and unload unused data
429 const float map_timer_and_unload_dtime = 5.25;
430 if(m_map_timer_and_unload_interval.step(dtime, map_timer_and_unload_dtime)) {
431 ScopeProfiler sp(g_profiler, "Client: map timer and unload");
432 std::vector<v3s16> deleted_blocks;
433 m_env.getMap().timerUpdate(map_timer_and_unload_dtime,
434 g_settings->getFloat("client_unload_unused_data_timeout"),
435 g_settings->getS32("client_mapblock_limit"),
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()) {
457 sendDeletedBlocks(sendlist);
459 if(i == deleted_blocks.end())
465 sendlist.push_back(*i);
473 // Control local player (0ms)
474 LocalPlayer *player = m_env.getLocalPlayer();
475 assert(player != NULL);
476 player->applyControl(dtime);
485 ClientEnvEvent event = m_env.getClientEvent();
486 if(event.type == CEE_NONE) {
489 else if(event.type == CEE_PLAYER_DAMAGE) {
490 if(m_ignore_damage_timer <= 0) {
491 u8 damage = event.player_damage.amount;
493 if(event.player_damage.send_to_server)
496 // Add to ClientEvent queue
498 event.type = CE_PLAYER_DAMAGE;
499 event.player_damage.amount = damage;
500 m_client_event_queue.push(event);
503 // Protocol v29 or greater obsoleted this event
504 else if (event.type == CEE_PLAYER_BREATH && m_proto_ver < 29) {
505 u16 breath = event.player_breath.amount;
513 float &counter = m_avg_rtt_timer;
517 // connectedAndInitialized() is true, peer exists.
518 float avg_rtt = getRTT();
519 infostream << "Client: avg_rtt=" << avg_rtt << std::endl;
523 Send player position to server
526 float &counter = m_playerpos_send_timer;
528 if((m_state == LC_Ready) && (counter >= m_recommended_send_interval))
536 Replace updated meshes
539 int num_processed_meshes = 0;
540 while (!m_mesh_update_thread.m_queue_out.empty())
542 num_processed_meshes++;
544 MinimapMapblock *minimap_mapblock = NULL;
545 bool do_mapper_update = true;
547 MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_frontNoEx();
548 MapBlock *block = m_env.getMap().getBlockNoCreateNoEx(r.p);
550 // Delete the old mesh
551 if (block->mesh != NULL) {
557 minimap_mapblock = r.mesh->moveMinimapMapblock();
558 if (minimap_mapblock == NULL)
559 do_mapper_update = false;
562 if (r.mesh && r.mesh->getMesh()->getMeshBufferCount() == 0) {
565 // Replace with the new mesh
566 block->mesh = r.mesh;
572 if (do_mapper_update)
573 m_mapper->addBlock(r.p, minimap_mapblock);
575 if (r.ack_block_to_server) {
585 if (num_processed_meshes > 0)
586 g_profiler->graphAdd("num_processed_meshes", num_processed_meshes);
592 if (m_media_downloader && m_media_downloader->isStarted()) {
593 m_media_downloader->step(this);
594 if (m_media_downloader->isDone()) {
596 delete m_media_downloader;
597 m_media_downloader = NULL;
602 If the server didn't update the inventory in a while, revert
603 the local inventory (so the player notices the lag problem
604 and knows something is wrong).
606 if(m_inventory_from_server)
608 float interval = 10.0;
609 float count_before = floor(m_inventory_from_server_age / interval);
611 m_inventory_from_server_age += dtime;
613 float count_after = floor(m_inventory_from_server_age / interval);
615 if(count_after != count_before)
617 // Do this every <interval> seconds after TOCLIENT_INVENTORY
618 // Reset the locally changed inventory to the authoritative inventory
619 LocalPlayer *player = m_env.getLocalPlayer();
620 player->inventory = *m_inventory_from_server;
621 m_inventory_updated = true;
626 Update positions of sounds attached to objects
629 for(UNORDERED_MAP<int, u16>::iterator i = m_sounds_to_objects.begin();
630 i != m_sounds_to_objects.end(); ++i) {
631 int client_id = i->first;
632 u16 object_id = i->second;
633 ClientActiveObject *cao = m_env.getActiveObject(object_id);
636 v3f pos = cao->getPosition();
637 m_sound->updateSoundPosition(client_id, pos);
642 Handle removed remotely initiated sounds
644 m_removed_sounds_check_timer += dtime;
645 if(m_removed_sounds_check_timer >= 2.32) {
646 m_removed_sounds_check_timer = 0;
647 // Find removed sounds and clear references to them
648 std::vector<s32> removed_server_ids;
649 for(UNORDERED_MAP<s32, int>::iterator 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.push_back(server_id);
663 if(!removed_server_ids.empty()) {
664 sendRemovedSounds(removed_server_ids);
669 if (m_localdb && m_localdb_save_interval.step(dtime,
670 m_cache_save_interval)) {
671 m_localdb->endSave();
672 m_localdb->beginSave();
676 bool Client::loadMedia(const std::string &data, const std::string &filename)
678 // Silly irrlicht's const-incorrectness
679 Buffer<char> data_rw(data.c_str(), data.size());
683 const char *image_ext[] = {
684 ".png", ".jpg", ".bmp", ".tga",
685 ".pcx", ".ppm", ".psd", ".wal", ".rgb",
688 name = removeStringEnd(filename, image_ext);
691 verbosestream<<"Client: Attempting to load image "
692 <<"file \""<<filename<<"\""<<std::endl;
694 io::IFileSystem *irrfs = m_device->getFileSystem();
695 video::IVideoDriver *vdrv = m_device->getVideoDriver();
697 // Create an irrlicht memory file
698 io::IReadFile *rfile = irrfs->createMemoryReadFile(
699 *data_rw, data_rw.getSize(), "_tempreadfile");
701 FATAL_ERROR_IF(!rfile, "Could not create irrlicht memory file.");
704 video::IImage *img = vdrv->createImageFromFile(rfile);
706 errorstream<<"Client: Cannot create image from data of "
707 <<"file \""<<filename<<"\""<<std::endl;
712 m_tsrc->insertSourceImage(filename, img);
719 const char *sound_ext[] = {
720 ".0.ogg", ".1.ogg", ".2.ogg", ".3.ogg", ".4.ogg",
721 ".5.ogg", ".6.ogg", ".7.ogg", ".8.ogg", ".9.ogg",
724 name = removeStringEnd(filename, sound_ext);
727 verbosestream<<"Client: Attempting to load sound "
728 <<"file \""<<filename<<"\""<<std::endl;
729 m_sound->loadSoundData(name, data);
733 const char *model_ext[] = {
734 ".x", ".b3d", ".md2", ".obj",
737 name = removeStringEnd(filename, model_ext);
740 verbosestream<<"Client: Storing model into memory: "
741 <<"\""<<filename<<"\""<<std::endl;
742 if(m_mesh_data.count(filename))
743 errorstream<<"Multiple models with name \""<<filename.c_str()
744 <<"\" found; replacing previous model"<<std::endl;
745 m_mesh_data[filename] = data;
749 errorstream<<"Client: Don't know how to load file \""
750 <<filename<<"\""<<std::endl;
754 // Virtual methods from con::PeerHandler
755 void Client::peerAdded(con::Peer *peer)
757 infostream << "Client::peerAdded(): peer->id="
758 << peer->id << std::endl;
760 void Client::deletingPeer(con::Peer *peer, bool timeout)
762 infostream << "Client::deletingPeer(): "
763 "Server Peer is getting deleted "
764 << "(timeout=" << timeout << ")" << std::endl;
767 m_access_denied = true;
768 m_access_denied_reason = gettext("Connection timed out.");
774 u16 number of files requested
780 void Client::request_media(const std::vector<std::string> &file_requests)
782 std::ostringstream os(std::ios_base::binary);
783 writeU16(os, TOSERVER_REQUEST_MEDIA);
784 size_t file_requests_size = file_requests.size();
786 FATAL_ERROR_IF(file_requests_size > 0xFFFF, "Unsupported number of file requests");
788 // Packet dynamicly resized
789 NetworkPacket pkt(TOSERVER_REQUEST_MEDIA, 2 + 0);
791 pkt << (u16) (file_requests_size & 0xFFFF);
793 for(std::vector<std::string>::const_iterator i = file_requests.begin();
794 i != file_requests.end(); ++i) {
800 infostream << "Client: Sending media request list to server ("
801 << file_requests.size() << " files. packet size)" << std::endl;
804 void Client::received_media()
806 NetworkPacket pkt(TOSERVER_RECEIVED_MEDIA, 0);
808 infostream << "Client: Notifying server that we received all media"
812 void Client::initLocalMapSaving(const Address &address,
813 const std::string &hostname,
814 bool is_local_server)
816 if (!g_settings->getBool("enable_local_map_saving") || is_local_server) {
820 const std::string world_path = porting::path_user
821 + DIR_DELIM + "worlds"
822 + DIR_DELIM + "server_"
823 + hostname + "_" + std::to_string(address.getPort());
825 fs::CreateAllDirs(world_path);
827 m_localdb = new Database_SQLite3(world_path);
828 m_localdb->beginSave();
829 actionstream << "Local map saving started, map will be saved at '" << world_path << "'" << std::endl;
832 void Client::ReceiveAll()
834 DSTACK(FUNCTION_NAME);
835 u32 start_ms = porting::getTimeMs();
838 // Limit time even if there would be huge amounts of data to
840 if(porting::getTimeMs() > start_ms + 100)
845 g_profiler->graphAdd("client_received_packets", 1);
847 catch(con::NoIncomingDataException &e) {
850 catch(con::InvalidIncomingDataException &e) {
851 infostream<<"Client::ReceiveAll(): "
852 "InvalidIncomingDataException: what()="
853 <<e.what()<<std::endl;
858 void Client::Receive()
860 DSTACK(FUNCTION_NAME);
866 inline void Client::handleCommand(NetworkPacket* pkt)
868 const ToClientCommandHandler& opHandle = toClientCommandTable[pkt->getCommand()];
869 (this->*opHandle.handler)(pkt);
873 sender_peer_id given to this shall be quaranteed to be a valid peer
875 void Client::ProcessData(NetworkPacket *pkt)
877 DSTACK(FUNCTION_NAME);
879 ToClientCommand command = (ToClientCommand) pkt->getCommand();
880 u32 sender_peer_id = pkt->getPeerId();
882 //infostream<<"Client: received command="<<command<<std::endl;
883 m_packetcounter.add((u16)command);
886 If this check is removed, be sure to change the queue
887 system to know the ids
889 if(sender_peer_id != PEER_ID_SERVER) {
890 infostream << "Client::ProcessData(): Discarding data not "
891 "coming from server: peer_id=" << sender_peer_id
896 // Command must be handled into ToClientCommandHandler
897 if (command >= TOCLIENT_NUM_MSG_TYPES) {
898 infostream << "Client: Ignoring unknown command "
899 << command << std::endl;
904 * Those packets are handled before m_server_ser_ver is set, it's normal
905 * But we must use the new ToClientConnectionState in the future,
908 if(toClientCommandTable[command].state == TOCLIENT_STATE_NOT_CONNECTED) {
913 if(m_server_ser_ver == SER_FMT_VER_INVALID) {
914 infostream << "Client: Server serialization"
915 " format invalid or not initialized."
916 " Skipping incoming command=" << command << std::endl;
921 Handle runtime commands
927 void Client::Send(NetworkPacket* pkt)
929 m_con.Send(PEER_ID_SERVER,
930 serverCommandFactoryTable[pkt->getCommand()].channel,
932 serverCommandFactoryTable[pkt->getCommand()].reliable);
935 // Will fill up 12 + 12 + 4 + 4 + 4 bytes
936 void writePlayerPos(LocalPlayer *myplayer, ClientMap *clientMap, NetworkPacket *pkt)
938 v3f pf = myplayer->getPosition() * 100;
939 v3f sf = myplayer->getSpeed() * 100;
940 s32 pitch = myplayer->getPitch() * 100;
941 s32 yaw = myplayer->getYaw() * 100;
942 u32 keyPressed = myplayer->keyPressed;
943 // scaled by 80, so that pi can fit into a u8
944 u8 fov = clientMap->getCameraFov() * 80;
945 u8 wanted_range = MYMIN(255,
946 std::ceil(clientMap->getControl().wanted_range / MAP_BLOCKSIZE));
948 v3s32 position(pf.X, pf.Y, pf.Z);
949 v3s32 speed(sf.X, sf.Y, sf.Z);
953 [0] v3s32 position*100
955 [12+12] s32 pitch*100
956 [12+12+4] s32 yaw*100
957 [12+12+4+4] u32 keyPressed
958 [12+12+4+4+4] u8 fov*80
959 [12+12+4+4+4+1] u8 ceil(wanted_range / MAP_BLOCKSIZE)
961 *pkt << position << speed << pitch << yaw << keyPressed;
962 *pkt << fov << wanted_range;
965 void Client::interact(u8 action, const PointedThing& pointed)
967 if(m_state != LC_Ready) {
968 errorstream << "Client::interact() "
969 "Canceled (not connected)"
974 LocalPlayer *myplayer = m_env.getLocalPlayer();
975 if (myplayer == NULL)
982 [5] u32 length of the next item (plen)
983 [9] serialized PointedThing
984 [9 + plen] player position information
986 0: start digging (from undersurface) or use
987 1: stop digging (all parameters ignored)
989 3: place block or item (to abovesurface)
991 5: perform secondary action of item
994 NetworkPacket pkt(TOSERVER_INTERACT, 1 + 2 + 0);
997 pkt << (u16)getPlayerItem();
999 std::ostringstream tmp_os(std::ios::binary);
1000 pointed.serialize(tmp_os);
1002 pkt.putLongString(tmp_os.str());
1004 writePlayerPos(myplayer, &m_env.getClientMap(), &pkt);
1009 void Client::deleteAuthData()
1014 switch (m_chosen_auth_mech) {
1015 case AUTH_MECHANISM_FIRST_SRP:
1017 case AUTH_MECHANISM_SRP:
1018 case AUTH_MECHANISM_LEGACY_PASSWORD:
1019 srp_user_delete((SRPUser *) m_auth_data);
1022 case AUTH_MECHANISM_NONE:
1025 m_chosen_auth_mech = AUTH_MECHANISM_NONE;
1029 AuthMechanism Client::choseAuthMech(const u32 mechs)
1031 if (mechs & AUTH_MECHANISM_SRP)
1032 return AUTH_MECHANISM_SRP;
1034 if (mechs & AUTH_MECHANISM_FIRST_SRP)
1035 return AUTH_MECHANISM_FIRST_SRP;
1037 if (mechs & AUTH_MECHANISM_LEGACY_PASSWORD)
1038 return AUTH_MECHANISM_LEGACY_PASSWORD;
1040 return AUTH_MECHANISM_NONE;
1043 void Client::sendLegacyInit(const char* playerName, const char* playerPassword)
1045 NetworkPacket pkt(TOSERVER_INIT_LEGACY,
1046 1 + PLAYERNAME_SIZE + PASSWORD_SIZE + 2 + 2);
1048 u16 proto_version_min = g_settings->getFlag("send_pre_v25_init") ?
1049 CLIENT_PROTOCOL_VERSION_MIN_LEGACY : CLIENT_PROTOCOL_VERSION_MIN;
1051 pkt << (u8) SER_FMT_VER_HIGHEST_READ;
1052 pkt.putRawString(playerName,PLAYERNAME_SIZE);
1053 pkt.putRawString(playerPassword, PASSWORD_SIZE);
1054 pkt << (u16) proto_version_min << (u16) CLIENT_PROTOCOL_VERSION_MAX;
1059 void Client::sendInit(const std::string &playerName)
1061 NetworkPacket pkt(TOSERVER_INIT, 1 + 2 + 2 + (1 + playerName.size()));
1063 // we don't support network compression yet
1064 u16 supp_comp_modes = NETPROTO_COMPRESSION_NONE;
1066 u16 proto_version_min = g_settings->getFlag("send_pre_v25_init") ?
1067 CLIENT_PROTOCOL_VERSION_MIN_LEGACY : CLIENT_PROTOCOL_VERSION_MIN;
1069 pkt << (u8) SER_FMT_VER_HIGHEST_READ << (u16) supp_comp_modes;
1070 pkt << (u16) proto_version_min << (u16) CLIENT_PROTOCOL_VERSION_MAX;
1076 void Client::startAuth(AuthMechanism chosen_auth_mechanism)
1078 m_chosen_auth_mech = chosen_auth_mechanism;
1080 switch (chosen_auth_mechanism) {
1081 case AUTH_MECHANISM_FIRST_SRP: {
1082 // send srp verifier to server
1083 std::string verifier;
1085 generate_srp_verifier_and_salt(getPlayerName(), m_password,
1088 NetworkPacket resp_pkt(TOSERVER_FIRST_SRP, 0);
1089 resp_pkt << salt << verifier << (u8)((m_password == "") ? 1 : 0);
1094 case AUTH_MECHANISM_SRP:
1095 case AUTH_MECHANISM_LEGACY_PASSWORD: {
1098 if (chosen_auth_mechanism == AUTH_MECHANISM_LEGACY_PASSWORD) {
1099 m_password = translate_password(getPlayerName(), m_password);
1103 std::string playername_u = lowercase(getPlayerName());
1104 m_auth_data = srp_user_new(SRP_SHA256, SRP_NG_2048,
1105 getPlayerName().c_str(), playername_u.c_str(),
1106 (const unsigned char *) m_password.c_str(),
1107 m_password.length(), NULL, NULL);
1110 SRP_Result res = srp_user_start_authentication(
1111 (struct SRPUser *) m_auth_data, NULL, NULL, 0,
1112 (unsigned char **) &bytes_A, &len_A);
1113 FATAL_ERROR_IF(res != SRP_OK, "Creating local SRP user failed.");
1115 NetworkPacket resp_pkt(TOSERVER_SRP_BYTES_A, 0);
1116 resp_pkt << std::string(bytes_A, len_A) << based_on;
1120 case AUTH_MECHANISM_NONE:
1121 break; // not handled in this method
1125 void Client::sendDeletedBlocks(std::vector<v3s16> &blocks)
1127 NetworkPacket pkt(TOSERVER_DELETEDBLOCKS, 1 + sizeof(v3s16) * blocks.size());
1129 pkt << (u8) blocks.size();
1132 for(std::vector<v3s16>::iterator
1134 j != blocks.end(); ++j) {
1142 void Client::sendGotBlocks(v3s16 block)
1144 NetworkPacket pkt(TOSERVER_GOTBLOCKS, 1 + 6);
1145 pkt << (u8) 1 << block;
1149 void Client::sendRemovedSounds(std::vector<s32> &soundList)
1151 size_t server_ids = soundList.size();
1152 assert(server_ids <= 0xFFFF);
1154 NetworkPacket pkt(TOSERVER_REMOVED_SOUNDS, 2 + server_ids * 4);
1156 pkt << (u16) (server_ids & 0xFFFF);
1158 for(std::vector<s32>::iterator i = soundList.begin();
1159 i != soundList.end(); ++i)
1165 void Client::sendNodemetaFields(v3s16 p, const std::string &formname,
1166 const StringMap &fields)
1168 size_t fields_size = fields.size();
1170 FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of nodemeta fields");
1172 NetworkPacket pkt(TOSERVER_NODEMETA_FIELDS, 0);
1174 pkt << p << formname << (u16) (fields_size & 0xFFFF);
1176 StringMap::const_iterator it;
1177 for (it = fields.begin(); it != fields.end(); ++it) {
1178 const std::string &name = it->first;
1179 const std::string &value = it->second;
1181 pkt.putLongString(value);
1187 void Client::sendInventoryFields(const std::string &formname,
1188 const StringMap &fields)
1190 size_t fields_size = fields.size();
1191 FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of inventory fields");
1193 NetworkPacket pkt(TOSERVER_INVENTORY_FIELDS, 0);
1194 pkt << formname << (u16) (fields_size & 0xFFFF);
1196 StringMap::const_iterator it;
1197 for (it = fields.begin(); it != fields.end(); ++it) {
1198 const std::string &name = it->first;
1199 const std::string &value = it->second;
1201 pkt.putLongString(value);
1207 void Client::sendInventoryAction(InventoryAction *a)
1209 std::ostringstream os(std::ios_base::binary);
1214 std::string s = os.str();
1216 NetworkPacket pkt(TOSERVER_INVENTORY_ACTION, s.size());
1217 pkt.putRawString(s.c_str(),s.size());
1222 void Client::sendChatMessage(const std::wstring &message)
1224 NetworkPacket pkt(TOSERVER_CHAT_MESSAGE, 2 + message.size() * sizeof(u16));
1231 void Client::sendChangePassword(const std::string &oldpassword,
1232 const std::string &newpassword)
1234 LocalPlayer *player = m_env.getLocalPlayer();
1238 std::string playername = player->getName();
1239 if (m_proto_ver >= 25) {
1240 // get into sudo mode and then send new password to server
1241 m_password = oldpassword;
1242 m_new_password = newpassword;
1243 startAuth(choseAuthMech(m_sudo_auth_methods));
1245 std::string oldpwd = translate_password(playername, oldpassword);
1246 std::string newpwd = translate_password(playername, newpassword);
1248 NetworkPacket pkt(TOSERVER_PASSWORD_LEGACY, 2 * PASSWORD_SIZE);
1250 for (u8 i = 0; i < PASSWORD_SIZE; i++) {
1251 pkt << (u8) (i < oldpwd.length() ? oldpwd[i] : 0);
1254 for (u8 i = 0; i < PASSWORD_SIZE; i++) {
1255 pkt << (u8) (i < newpwd.length() ? newpwd[i] : 0);
1262 void Client::sendDamage(u8 damage)
1264 DSTACK(FUNCTION_NAME);
1266 NetworkPacket pkt(TOSERVER_DAMAGE, sizeof(u8));
1271 void Client::sendBreath(u16 breath)
1273 DSTACK(FUNCTION_NAME);
1275 // Protocol v29 make this obsolete
1276 if (m_proto_ver >= 29)
1279 NetworkPacket pkt(TOSERVER_BREATH, sizeof(u16));
1284 void Client::sendRespawn()
1286 DSTACK(FUNCTION_NAME);
1288 NetworkPacket pkt(TOSERVER_RESPAWN, 0);
1292 void Client::sendReady()
1294 DSTACK(FUNCTION_NAME);
1296 NetworkPacket pkt(TOSERVER_CLIENT_READY,
1297 1 + 1 + 1 + 1 + 2 + sizeof(char) * strlen(g_version_hash));
1299 pkt << (u8) VERSION_MAJOR << (u8) VERSION_MINOR << (u8) VERSION_PATCH
1300 << (u8) 0 << (u16) strlen(g_version_hash);
1302 pkt.putRawString(g_version_hash, (u16) strlen(g_version_hash));
1306 void Client::sendPlayerPos()
1308 LocalPlayer *myplayer = m_env.getLocalPlayer();
1309 if(myplayer == NULL)
1312 ClientMap &map = m_env.getClientMap();
1314 u8 camera_fov = map.getCameraFov();
1315 u8 wanted_range = map.getControl().wanted_range;
1317 // Save bandwidth by only updating position when something changed
1318 if(myplayer->last_position == myplayer->getPosition() &&
1319 myplayer->last_speed == myplayer->getSpeed() &&
1320 myplayer->last_pitch == myplayer->getPitch() &&
1321 myplayer->last_yaw == myplayer->getYaw() &&
1322 myplayer->last_keyPressed == myplayer->keyPressed &&
1323 myplayer->last_camera_fov == camera_fov &&
1324 myplayer->last_wanted_range == wanted_range)
1327 myplayer->last_position = myplayer->getPosition();
1328 myplayer->last_speed = myplayer->getSpeed();
1329 myplayer->last_pitch = myplayer->getPitch();
1330 myplayer->last_yaw = myplayer->getYaw();
1331 myplayer->last_keyPressed = myplayer->keyPressed;
1332 myplayer->last_camera_fov = camera_fov;
1333 myplayer->last_wanted_range = wanted_range;
1335 //infostream << "Sending Player Position information" << std::endl;
1339 //MutexAutoLock lock(m_con_mutex); //bulk comment-out
1340 our_peer_id = m_con.GetPeerID();
1343 // Set peer id if not set already
1344 if(myplayer->peer_id == PEER_ID_INEXISTENT)
1345 myplayer->peer_id = our_peer_id;
1347 assert(myplayer->peer_id == our_peer_id);
1349 NetworkPacket pkt(TOSERVER_PLAYERPOS, 12 + 12 + 4 + 4 + 4 + 1 + 1);
1351 writePlayerPos(myplayer, &map, &pkt);
1356 void Client::sendPlayerItem(u16 item)
1358 LocalPlayer *myplayer = m_env.getLocalPlayer();
1359 if(myplayer == NULL)
1362 u16 our_peer_id = m_con.GetPeerID();
1364 // Set peer id if not set already
1365 if(myplayer->peer_id == PEER_ID_INEXISTENT)
1366 myplayer->peer_id = our_peer_id;
1367 assert(myplayer->peer_id == our_peer_id);
1369 NetworkPacket pkt(TOSERVER_PLAYERITEM, 2);
1376 void Client::removeNode(v3s16 p)
1378 std::map<v3s16, MapBlock*> modified_blocks;
1381 m_env.getMap().removeNodeAndUpdate(p, modified_blocks);
1383 catch(InvalidPositionException &e) {
1386 for(std::map<v3s16, MapBlock *>::iterator
1387 i = modified_blocks.begin();
1388 i != modified_blocks.end(); ++i) {
1389 addUpdateMeshTaskWithEdge(i->first, false, true);
1393 void Client::addNode(v3s16 p, MapNode n, bool remove_metadata)
1395 //TimeTaker timer1("Client::addNode()");
1397 std::map<v3s16, MapBlock*> modified_blocks;
1400 //TimeTaker timer3("Client::addNode(): addNodeAndUpdate");
1401 m_env.getMap().addNodeAndUpdate(p, n, modified_blocks, remove_metadata);
1403 catch(InvalidPositionException &e) {
1406 for(std::map<v3s16, MapBlock *>::iterator
1407 i = modified_blocks.begin();
1408 i != modified_blocks.end(); ++i) {
1409 addUpdateMeshTaskWithEdge(i->first, false, true);
1413 void Client::setPlayerControl(PlayerControl &control)
1415 LocalPlayer *player = m_env.getLocalPlayer();
1416 assert(player != NULL);
1417 player->control = control;
1420 void Client::selectPlayerItem(u16 item)
1422 m_playeritem = item;
1423 m_inventory_updated = true;
1424 sendPlayerItem(item);
1427 // Returns true if the inventory of the local player has been
1428 // updated from the server. If it is true, it is set to false.
1429 bool Client::getLocalInventoryUpdated()
1431 bool updated = m_inventory_updated;
1432 m_inventory_updated = false;
1436 // Copies the inventory of the local player to parameter
1437 void Client::getLocalInventory(Inventory &dst)
1439 LocalPlayer *player = m_env.getLocalPlayer();
1440 assert(player != NULL);
1441 dst = player->inventory;
1444 Inventory* Client::getInventory(const InventoryLocation &loc)
1447 case InventoryLocation::UNDEFINED:
1450 case InventoryLocation::CURRENT_PLAYER:
1452 LocalPlayer *player = m_env.getLocalPlayer();
1453 assert(player != NULL);
1454 return &player->inventory;
1457 case InventoryLocation::PLAYER:
1459 // Check if we are working with local player inventory
1460 LocalPlayer *player = m_env.getLocalPlayer();
1461 if (!player || strcmp(player->getName(), loc.name.c_str()) != 0)
1463 return &player->inventory;
1466 case InventoryLocation::NODEMETA:
1468 NodeMetadata *meta = m_env.getMap().getNodeMetadata(loc.p);
1471 return meta->getInventory();
1474 case InventoryLocation::DETACHED:
1476 if (m_detached_inventories.count(loc.name) == 0)
1478 return m_detached_inventories[loc.name];
1482 FATAL_ERROR("Invalid inventory location type.");
1488 void Client::inventoryAction(InventoryAction *a)
1491 Send it to the server
1493 sendInventoryAction(a);
1496 Predict some local inventory changes
1498 a->clientApply(this, this);
1504 float Client::getAnimationTime()
1506 return m_animation_time;
1509 int Client::getCrackLevel()
1511 return m_crack_level;
1514 void Client::setCrack(int level, v3s16 pos)
1516 int old_crack_level = m_crack_level;
1517 v3s16 old_crack_pos = m_crack_pos;
1519 m_crack_level = level;
1522 if(old_crack_level >= 0 && (level < 0 || pos != old_crack_pos))
1525 addUpdateMeshTaskForNode(old_crack_pos, false, true);
1527 if(level >= 0 && (old_crack_level < 0 || pos != old_crack_pos))
1530 addUpdateMeshTaskForNode(pos, false, true);
1536 LocalPlayer *player = m_env.getLocalPlayer();
1537 assert(player != NULL);
1541 bool Client::getChatMessage(std::wstring &message)
1543 if(m_chat_queue.size() == 0)
1545 message = m_chat_queue.front();
1550 void Client::typeChatMessage(const std::wstring &message)
1552 // Discard empty line
1557 sendChatMessage(message);
1560 if (message[0] == L'/')
1562 m_chat_queue.push((std::wstring)L"issued command: " + message);
1566 LocalPlayer *player = m_env.getLocalPlayer();
1567 assert(player != NULL);
1568 std::wstring name = narrow_to_wide(player->getName());
1569 m_chat_queue.push((std::wstring)L"<" + name + L"> " + message);
1573 void Client::addUpdateMeshTask(v3s16 p, bool ack_to_server, bool urgent)
1575 MapBlock *b = m_env.getMap().getBlockNoCreateNoEx(p);
1580 Create a task to update the mesh of the block
1583 MeshMakeData *data = new MeshMakeData(this, m_cache_enable_shaders,
1584 m_cache_use_tangent_vertices);
1587 //TimeTaker timer("data fill");
1589 // Debug: 1-6ms, avg=2ms
1591 data->setCrack(m_crack_level, m_crack_pos);
1592 data->setSmoothLighting(m_cache_smooth_lighting);
1595 // Add task to queue
1596 m_mesh_update_thread.enqueueUpdate(p, data, ack_to_server, urgent);
1599 void Client::addUpdateMeshTaskWithEdge(v3s16 blockpos, bool ack_to_server, bool urgent)
1602 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1604 catch(InvalidPositionException &e){}
1607 for (int i=0;i<6;i++)
1610 v3s16 p = blockpos + g_6dirs[i];
1611 addUpdateMeshTask(p, false, urgent);
1613 catch(InvalidPositionException &e){}
1617 void Client::addUpdateMeshTaskForNode(v3s16 nodepos, bool ack_to_server, bool urgent)
1621 infostream<<"Client::addUpdateMeshTaskForNode(): "
1622 <<"("<<p.X<<","<<p.Y<<","<<p.Z<<")"
1626 v3s16 blockpos = getNodeBlockPos(nodepos);
1627 v3s16 blockpos_relative = blockpos * MAP_BLOCKSIZE;
1630 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1632 catch(InvalidPositionException &e) {}
1635 if(nodepos.X == blockpos_relative.X){
1637 v3s16 p = blockpos + v3s16(-1,0,0);
1638 addUpdateMeshTask(p, false, urgent);
1640 catch(InvalidPositionException &e){}
1643 if(nodepos.Y == blockpos_relative.Y){
1645 v3s16 p = blockpos + v3s16(0,-1,0);
1646 addUpdateMeshTask(p, false, urgent);
1648 catch(InvalidPositionException &e){}
1651 if(nodepos.Z == blockpos_relative.Z){
1653 v3s16 p = blockpos + v3s16(0,0,-1);
1654 addUpdateMeshTask(p, false, urgent);
1656 catch(InvalidPositionException &e){}
1660 ClientEvent Client::getClientEvent()
1663 if (m_client_event_queue.empty()) {
1664 event.type = CE_NONE;
1667 event = m_client_event_queue.front();
1668 m_client_event_queue.pop();
1673 float Client::mediaReceiveProgress()
1675 if (m_media_downloader)
1676 return m_media_downloader->getProgress();
1678 return 1.0; // downloader only exists when not yet done
1681 typedef struct TextureUpdateArgs {
1682 IrrlichtDevice *device;
1683 gui::IGUIEnvironment *guienv;
1686 const wchar_t* text_base;
1687 } TextureUpdateArgs;
1689 void texture_update_progress(void *args, u32 progress, u32 max_progress)
1691 TextureUpdateArgs* targs = (TextureUpdateArgs*) args;
1692 u16 cur_percent = ceil(progress / (double) max_progress * 100.);
1694 // update the loading menu -- if neccessary
1695 bool do_draw = false;
1696 u32 time_ms = targs->last_time_ms;
1697 if (cur_percent != targs->last_percent) {
1698 targs->last_percent = cur_percent;
1699 time_ms = getTimeMs();
1700 // only draw when the user will notice something:
1701 do_draw = (time_ms - targs->last_time_ms > 100);
1705 targs->last_time_ms = time_ms;
1706 std::basic_stringstream<wchar_t> strm;
1707 strm << targs->text_base << " " << targs->last_percent << "%...";
1708 draw_load_screen(strm.str(), targs->device, targs->guienv, 0,
1709 72 + (u16) ((18. / 100.) * (double) targs->last_percent));
1713 void Client::afterContentReceived(IrrlichtDevice *device)
1715 infostream<<"Client::afterContentReceived() started"<<std::endl;
1716 assert(m_itemdef_received); // pre-condition
1717 assert(m_nodedef_received); // pre-condition
1718 assert(mediaReceived()); // pre-condition
1720 const wchar_t* text = wgettext("Loading textures...");
1722 // Clear cached pre-scaled 2D GUI images, as this cache
1723 // might have images with the same name but different
1724 // content from previous sessions.
1725 guiScalingCacheClear(device->getVideoDriver());
1727 // Rebuild inherited images and recreate textures
1728 infostream<<"- Rebuilding images and textures"<<std::endl;
1729 draw_load_screen(text,device, guienv, 0, 70);
1730 m_tsrc->rebuildImagesAndTextures();
1734 infostream<<"- Rebuilding shaders"<<std::endl;
1735 text = wgettext("Rebuilding shaders...");
1736 draw_load_screen(text, device, guienv, 0, 71);
1737 m_shsrc->rebuildShaders();
1740 // Update node aliases
1741 infostream<<"- Updating node aliases"<<std::endl;
1742 text = wgettext("Initializing nodes...");
1743 draw_load_screen(text, device, guienv, 0, 72);
1744 m_nodedef->updateAliases(m_itemdef);
1745 std::string texture_path = g_settings->get("texture_path");
1746 if (texture_path != "" && fs::IsDir(texture_path))
1747 m_nodedef->applyTextureOverrides(texture_path + DIR_DELIM + "override.txt");
1748 m_nodedef->setNodeRegistrationStatus(true);
1749 m_nodedef->runNodeResolveCallbacks();
1752 // Update node textures and assign shaders to each tile
1753 infostream<<"- Updating node textures"<<std::endl;
1754 TextureUpdateArgs tu_args;
1755 tu_args.device = device;
1756 tu_args.guienv = guienv;
1757 tu_args.last_time_ms = getTimeMs();
1758 tu_args.last_percent = 0;
1759 tu_args.text_base = wgettext("Initializing nodes");
1760 m_nodedef->updateTextures(this, texture_update_progress, &tu_args);
1761 delete[] tu_args.text_base;
1763 // Start mesh update thread after setting up content definitions
1764 infostream<<"- Starting mesh update thread"<<std::endl;
1765 m_mesh_update_thread.start();
1769 text = wgettext("Done!");
1770 draw_load_screen(text, device, guienv, 0, 100);
1771 infostream<<"Client::afterContentReceived() done"<<std::endl;
1775 float Client::getRTT(void)
1777 return m_con.getPeerStat(PEER_ID_SERVER,con::AVG_RTT);
1780 float Client::getCurRate(void)
1782 return ( m_con.getLocalStat(con::CUR_INC_RATE) +
1783 m_con.getLocalStat(con::CUR_DL_RATE));
1786 float Client::getAvgRate(void)
1788 return ( m_con.getLocalStat(con::AVG_INC_RATE) +
1789 m_con.getLocalStat(con::AVG_DL_RATE));
1792 void Client::makeScreenshot(IrrlichtDevice *device)
1794 irr::video::IVideoDriver *driver = device->getVideoDriver();
1795 irr::video::IImage* const raw_image = driver->createScreenShot();
1800 time_t t = time(NULL);
1801 struct tm *tm = localtime(&t);
1803 char timetstamp_c[64];
1804 strftime(timetstamp_c, sizeof(timetstamp_c), "%Y%m%d_%H%M%S", tm);
1806 std::string filename_base = g_settings->get("screenshot_path")
1808 + std::string("screenshot_")
1809 + std::string(timetstamp_c);
1810 std::string filename_ext = "." + g_settings->get("screenshot_format");
1811 std::string filename;
1813 u32 quality = (u32)g_settings->getS32("screenshot_quality");
1814 quality = MYMIN(MYMAX(quality, 0), 100) / 100.0 * 255;
1816 // Try to find a unique filename
1817 unsigned serial = 0;
1819 while (serial < SCREENSHOT_MAX_SERIAL_TRIES) {
1820 filename = filename_base + (serial > 0 ? ("_" + itos(serial)) : "") + filename_ext;
1821 std::ifstream tmp(filename.c_str());
1823 break; // File did not apparently exist, we'll go with it
1827 if (serial == SCREENSHOT_MAX_SERIAL_TRIES) {
1828 infostream << "Could not find suitable filename for screenshot" << std::endl;
1830 irr::video::IImage* const image =
1831 driver->createImage(video::ECF_R8G8B8, raw_image->getDimension());
1834 raw_image->copyTo(image);
1836 std::ostringstream sstr;
1837 if (driver->writeImageToFile(image, filename.c_str(), quality)) {
1838 sstr << "Saved screenshot to '" << filename << "'";
1840 sstr << "Failed to save screenshot '" << filename << "'";
1842 m_chat_queue.push(narrow_to_wide(sstr.str()));
1843 infostream << sstr.str() << std::endl;
1851 // IGameDef interface
1853 IItemDefManager* Client::getItemDefManager()
1857 INodeDefManager* Client::getNodeDefManager()
1861 ICraftDefManager* Client::getCraftDefManager()
1864 //return m_craftdef;
1866 ITextureSource* Client::getTextureSource()
1870 IShaderSource* Client::getShaderSource()
1874 scene::ISceneManager* Client::getSceneManager()
1876 return m_device->getSceneManager();
1878 u16 Client::allocateUnknownNodeId(const std::string &name)
1880 errorstream << "Client::allocateUnknownNodeId(): "
1881 << "Client cannot allocate node IDs" << std::endl;
1882 FATAL_ERROR("Client allocated unknown node");
1884 return CONTENT_IGNORE;
1886 ISoundManager* Client::getSoundManager()
1890 MtEventManager* Client::getEventManager()
1895 ParticleManager* Client::getParticleManager()
1897 return &m_particle_manager;
1900 scene::IAnimatedMesh* Client::getMesh(const std::string &filename)
1902 StringMap::const_iterator it = m_mesh_data.find(filename);
1903 if (it == m_mesh_data.end()) {
1904 errorstream << "Client::getMesh(): Mesh not found: \"" << filename
1905 << "\"" << std::endl;
1908 const std::string &data = it->second;
1909 scene::ISceneManager *smgr = m_device->getSceneManager();
1911 // Create the mesh, remove it from cache and return it
1912 // This allows unique vertex colors and other properties for each instance
1913 Buffer<char> data_rw(data.c_str(), data.size()); // Const-incorrect Irrlicht
1914 io::IFileSystem *irrfs = m_device->getFileSystem();
1915 io::IReadFile *rfile = irrfs->createMemoryReadFile(
1916 *data_rw, data_rw.getSize(), filename.c_str());
1917 FATAL_ERROR_IF(!rfile, "Could not create/open RAM file");
1919 scene::IAnimatedMesh *mesh = smgr->getMesh(rfile);
1921 // NOTE: By playing with Irrlicht refcounts, maybe we could cache a bunch
1922 // of uniquely named instances and re-use them
1924 smgr->getMeshCache()->removeMesh(mesh);