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"
35 #include "mapblock_mesh.h"
41 #include "clientmap.h"
42 #include "clientmedia.h"
44 #include "drawscene.h"
45 #include "database-sqlite3.h"
46 #include "serialization.h"
47 #include "guiscalingfilter.h"
48 #include "script/clientscripting.h"
50 extern gui::IGUIEnvironment* guienv;
56 QueuedMeshUpdate::QueuedMeshUpdate():
59 ack_block_to_server(false)
63 QueuedMeshUpdate::~QueuedMeshUpdate()
73 MeshUpdateQueue::MeshUpdateQueue()
77 MeshUpdateQueue::~MeshUpdateQueue()
79 MutexAutoLock lock(m_mutex);
81 for(std::vector<QueuedMeshUpdate*>::iterator
83 i != m_queue.end(); ++i)
85 QueuedMeshUpdate *q = *i;
91 peer_id=0 adds with nobody to send to
93 void MeshUpdateQueue::addBlock(v3s16 p, MeshMakeData *data, bool ack_block_to_server, bool urgent)
95 DSTACK(FUNCTION_NAME);
97 assert(data); // pre-condition
99 MutexAutoLock lock(m_mutex);
105 Find if block is already in queue.
106 If it is, update the data and quit.
108 for(std::vector<QueuedMeshUpdate*>::iterator
110 i != m_queue.end(); ++i)
112 QueuedMeshUpdate *q = *i;
118 if(ack_block_to_server)
119 q->ack_block_to_server = true;
127 QueuedMeshUpdate *q = new QueuedMeshUpdate;
130 q->ack_block_to_server = ack_block_to_server;
131 m_queue.push_back(q);
134 // Returned pointer must be deleted
135 // Returns NULL if queue is empty
136 QueuedMeshUpdate *MeshUpdateQueue::pop()
138 MutexAutoLock lock(m_mutex);
140 bool must_be_urgent = !m_urgents.empty();
141 for(std::vector<QueuedMeshUpdate*>::iterator
143 i != m_queue.end(); ++i)
145 QueuedMeshUpdate *q = *i;
146 if(must_be_urgent && m_urgents.count(q->p) == 0)
149 m_urgents.erase(q->p);
159 void MeshUpdateThread::enqueueUpdate(v3s16 p, MeshMakeData *data,
160 bool ack_block_to_server, bool urgent)
162 m_queue_in.addBlock(p, data, ack_block_to_server, urgent);
166 void MeshUpdateThread::doUpdate()
169 while ((q = m_queue_in.pop())) {
171 ScopeProfiler sp(g_profiler, "Client: Mesh making");
173 MapBlockMesh *mesh_new = new MapBlockMesh(q->data, m_camera_offset);
178 r.ack_block_to_server = q->ack_block_to_server;
180 m_queue_out.push_back(r);
191 IrrlichtDevice *device,
192 const char *playername,
193 std::string password,
194 MapDrawControl &control,
195 IWritableTextureSource *tsrc,
196 IWritableShaderSource *shsrc,
197 IWritableItemDefManager *itemdef,
198 IWritableNodeDefManager *nodedef,
199 ISoundManager *sound,
200 MtEventManager *event,
203 m_packetcounter_timer(0.0),
204 m_connection_reinit_timer(0.1),
205 m_avg_rtt_timer(0.0),
206 m_playerpos_send_timer(0.0),
207 m_ignore_damage_timer(0.0),
214 m_mesh_update_thread(),
216 new ClientMap(this, control,
217 device->getSceneManager()->getRootSceneNode(),
218 device->getSceneManager(), 666),
219 device->getSceneManager(),
222 m_particle_manager(&m_env),
223 m_con(PROTOCOL_ID, 512, CONNECTION_TIMEOUT, ipv6, this),
226 m_minimap_disabled_by_server(false),
227 m_server_ser_ver(SER_FMT_VER_INVALID),
230 m_inventory_updated(false),
231 m_inventory_from_server(NULL),
232 m_inventory_from_server_age(0.0),
237 m_password(password),
238 m_chosen_auth_mech(AUTH_MECHANISM_NONE),
240 m_access_denied(false),
241 m_access_denied_reconnect(false),
242 m_itemdef_received(false),
243 m_nodedef_received(false),
244 m_media_downloader(new ClientMediaDownloader()),
245 m_time_of_day_set(false),
246 m_last_time_of_day_f(-1),
247 m_time_of_day_update_timer(0),
248 m_recommended_send_interval(0.1),
249 m_removed_sounds_check_timer(0),
254 m_env.setLocalPlayer(new LocalPlayer(this, playername));
256 m_mapper = new Mapper(device, this);
257 m_cache_save_interval = g_settings->getU16("server_map_save_interval");
259 m_cache_smooth_lighting = g_settings->getBool("smooth_lighting");
260 m_cache_enable_shaders = g_settings->getBool("enable_shaders");
261 m_cache_use_tangent_vertices = m_cache_enable_shaders && (
262 g_settings->getBool("enable_bumpmapping") ||
263 g_settings->getBool("enable_parallax_occlusion"));
265 m_script = new ClientScripting(this);
266 m_env.setScript(m_script);
269 void Client::initMods()
271 m_script->loadMod(getBuiltinLuaPath() + DIR_DELIM "init.lua", BUILTIN_MOD_NAME);
273 ClientModConfiguration modconf(getClientModsLuaPath());
274 std::vector<ModSpec> mods = modconf.getMods();
275 std::vector<ModSpec> unsatisfied_mods = modconf.getUnsatisfiedMods();
276 // complain about mods with unsatisfied dependencies
277 if (!modconf.isConsistent()) {
278 modconf.printUnsatisfiedModsError();
282 infostream << "Client Loading mods: ";
283 for (std::vector<ModSpec>::const_iterator i = mods.begin();
284 i != mods.end(); ++i) {
285 infostream << (*i).name << " ";
288 infostream << std::endl;
289 // Load and run "mod" scripts
290 for (std::vector<ModSpec>::const_iterator it = mods.begin();
291 it != mods.end(); ++it) {
292 const ModSpec &mod = *it;
293 if (!string_allowed(mod.name, MODNAME_ALLOWED_CHARS)) {
294 throw ModError("Error loading mod \"" + mod.name +
295 "\": Mod name does not follow naming conventions: "
296 "Only chararacters [a-z0-9_] are allowed.");
298 std::string script_path = mod.path + DIR_DELIM + "init.lua";
299 infostream << " [" << padStringRight(mod.name, 12) << "] [\""
300 << script_path << "\"]" << std::endl;
301 m_script->loadMod(script_path, mod.name);
305 const std::string &Client::getBuiltinLuaPath()
307 static const std::string builtin_dir = porting::path_share + DIR_DELIM + "builtin";
311 const std::string &Client::getClientModsLuaPath()
313 static const std::string clientmods_dir = porting::path_share + DIR_DELIM + "clientmods";
314 return clientmods_dir;
317 const std::vector<ModSpec>& Client::getMods() const
319 static std::vector<ModSpec> client_modspec_temp;
320 return client_modspec_temp;
323 const ModSpec* Client::getModSpec(const std::string &modname) const
330 m_script->on_shutdown();
331 //request all client managed threads to stop
332 m_mesh_update_thread.stop();
333 // Save local server map
335 infostream << "Local map saving ended." << std::endl;
336 m_localdb->endSave();
342 bool Client::isShutdown()
345 if (!m_mesh_update_thread.isRunning()) return true;
354 m_mesh_update_thread.stop();
355 m_mesh_update_thread.wait();
356 while (!m_mesh_update_thread.m_queue_out.empty()) {
357 MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_frontNoEx();
362 delete m_inventory_from_server;
364 // Delete detached inventories
365 for (UNORDERED_MAP<std::string, Inventory*>::iterator
366 i = m_detached_inventories.begin();
367 i != m_detached_inventories.end(); ++i) {
371 // cleanup 3d model meshes on client shutdown
372 while (m_device->getSceneManager()->getMeshCache()->getMeshCount() != 0) {
373 scene::IAnimatedMesh *mesh =
374 m_device->getSceneManager()->getMeshCache()->getMeshByIndex(0);
377 m_device->getSceneManager()->getMeshCache()->removeMesh(mesh);
383 void Client::connect(Address address,
384 const std::string &address_name,
385 bool is_local_server)
387 DSTACK(FUNCTION_NAME);
389 initLocalMapSaving(address, address_name, is_local_server);
391 m_con.SetTimeoutMs(0);
392 m_con.Connect(address);
395 void Client::step(float dtime)
397 DSTACK(FUNCTION_NAME);
403 if(m_ignore_damage_timer > dtime)
404 m_ignore_damage_timer -= dtime;
406 m_ignore_damage_timer = 0.0;
408 m_animation_time += dtime;
409 if(m_animation_time > 60.0)
410 m_animation_time -= 60.0;
412 m_time_of_day_update_timer += dtime;
420 float &counter = m_packetcounter_timer;
426 infostream << "Client packetcounter (" << m_packetcounter_timer
428 m_packetcounter.print(infostream);
429 m_packetcounter.clear();
433 // UGLY hack to fix 2 second startup delay caused by non existent
434 // server client startup synchronization in local server or singleplayer mode
435 static bool initial_step = true;
437 initial_step = false;
439 else if(m_state == LC_Created) {
440 float &counter = m_connection_reinit_timer;
445 LocalPlayer *myplayer = m_env.getLocalPlayer();
446 FATAL_ERROR_IF(myplayer == NULL, "Local player not found in environment.");
448 u16 proto_version_min = g_settings->getFlag("send_pre_v25_init") ?
449 CLIENT_PROTOCOL_VERSION_MIN_LEGACY : CLIENT_PROTOCOL_VERSION_MIN;
451 if (proto_version_min < 25) {
452 // Send TOSERVER_INIT_LEGACY
453 // [0] u16 TOSERVER_INIT_LEGACY
454 // [2] u8 SER_FMT_VER_HIGHEST_READ
455 // [3] u8[20] player_name
456 // [23] u8[28] password (new in some version)
457 // [51] u16 minimum supported network protocol version (added sometime)
458 // [53] u16 maximum supported network protocol version (added later than the previous one)
460 char pName[PLAYERNAME_SIZE];
461 char pPassword[PASSWORD_SIZE];
462 memset(pName, 0, PLAYERNAME_SIZE * sizeof(char));
463 memset(pPassword, 0, PASSWORD_SIZE * sizeof(char));
465 std::string hashed_password = translate_password(myplayer->getName(), m_password);
466 snprintf(pName, PLAYERNAME_SIZE, "%s", myplayer->getName());
467 snprintf(pPassword, PASSWORD_SIZE, "%s", hashed_password.c_str());
469 sendLegacyInit(pName, pPassword);
471 if (CLIENT_PROTOCOL_VERSION_MAX >= 25)
472 sendInit(myplayer->getName());
475 // Not connected, return
480 Do stuff if connected
484 Run Map's timers and unload unused data
486 const float map_timer_and_unload_dtime = 5.25;
487 if(m_map_timer_and_unload_interval.step(dtime, map_timer_and_unload_dtime)) {
488 ScopeProfiler sp(g_profiler, "Client: map timer and unload");
489 std::vector<v3s16> deleted_blocks;
490 m_env.getMap().timerUpdate(map_timer_and_unload_dtime,
491 g_settings->getFloat("client_unload_unused_data_timeout"),
492 g_settings->getS32("client_mapblock_limit"),
497 NOTE: This loop is intentionally iterated the way it is.
500 std::vector<v3s16>::iterator i = deleted_blocks.begin();
501 std::vector<v3s16> sendlist;
503 if(sendlist.size() == 255 || i == deleted_blocks.end()) {
514 sendDeletedBlocks(sendlist);
516 if(i == deleted_blocks.end())
522 sendlist.push_back(*i);
530 // Control local player (0ms)
531 LocalPlayer *player = m_env.getLocalPlayer();
532 assert(player != NULL);
533 player->applyControl(dtime);
542 ClientEnvEvent event = m_env.getClientEvent();
543 if(event.type == CEE_NONE) {
546 else if(event.type == CEE_PLAYER_DAMAGE) {
547 if(m_ignore_damage_timer <= 0) {
548 u8 damage = event.player_damage.amount;
550 if(event.player_damage.send_to_server)
553 // Add to ClientEvent queue
555 event.type = CE_PLAYER_DAMAGE;
556 event.player_damage.amount = damage;
557 m_client_event_queue.push(event);
560 // Protocol v29 or greater obsoleted this event
561 else if (event.type == CEE_PLAYER_BREATH && m_proto_ver < 29) {
562 u16 breath = event.player_breath.amount;
570 float &counter = m_avg_rtt_timer;
574 // connectedAndInitialized() is true, peer exists.
575 float avg_rtt = getRTT();
576 infostream << "Client: avg_rtt=" << avg_rtt << std::endl;
580 Send player position to server
583 float &counter = m_playerpos_send_timer;
585 if((m_state == LC_Ready) && (counter >= m_recommended_send_interval))
593 Replace updated meshes
596 int num_processed_meshes = 0;
597 while (!m_mesh_update_thread.m_queue_out.empty())
599 num_processed_meshes++;
601 MinimapMapblock *minimap_mapblock = NULL;
602 bool do_mapper_update = true;
604 MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_frontNoEx();
605 MapBlock *block = m_env.getMap().getBlockNoCreateNoEx(r.p);
607 // Delete the old mesh
608 if (block->mesh != NULL) {
614 minimap_mapblock = r.mesh->moveMinimapMapblock();
615 if (minimap_mapblock == NULL)
616 do_mapper_update = false;
619 if (r.mesh && r.mesh->getMesh()->getMeshBufferCount() == 0) {
622 // Replace with the new mesh
623 block->mesh = r.mesh;
629 if (do_mapper_update)
630 m_mapper->addBlock(r.p, minimap_mapblock);
632 if (r.ack_block_to_server) {
642 if (num_processed_meshes > 0)
643 g_profiler->graphAdd("num_processed_meshes", num_processed_meshes);
649 if (m_media_downloader && m_media_downloader->isStarted()) {
650 m_media_downloader->step(this);
651 if (m_media_downloader->isDone()) {
653 delete m_media_downloader;
654 m_media_downloader = NULL;
659 If the server didn't update the inventory in a while, revert
660 the local inventory (so the player notices the lag problem
661 and knows something is wrong).
663 if(m_inventory_from_server)
665 float interval = 10.0;
666 float count_before = floor(m_inventory_from_server_age / interval);
668 m_inventory_from_server_age += dtime;
670 float count_after = floor(m_inventory_from_server_age / interval);
672 if(count_after != count_before)
674 // Do this every <interval> seconds after TOCLIENT_INVENTORY
675 // Reset the locally changed inventory to the authoritative inventory
676 LocalPlayer *player = m_env.getLocalPlayer();
677 player->inventory = *m_inventory_from_server;
678 m_inventory_updated = true;
683 Update positions of sounds attached to objects
686 for(UNORDERED_MAP<int, u16>::iterator i = m_sounds_to_objects.begin();
687 i != m_sounds_to_objects.end(); ++i) {
688 int client_id = i->first;
689 u16 object_id = i->second;
690 ClientActiveObject *cao = m_env.getActiveObject(object_id);
693 v3f pos = cao->getPosition();
694 m_sound->updateSoundPosition(client_id, pos);
699 Handle removed remotely initiated sounds
701 m_removed_sounds_check_timer += dtime;
702 if(m_removed_sounds_check_timer >= 2.32) {
703 m_removed_sounds_check_timer = 0;
704 // Find removed sounds and clear references to them
705 std::vector<s32> removed_server_ids;
706 for(UNORDERED_MAP<s32, int>::iterator i = m_sounds_server_to_client.begin();
707 i != m_sounds_server_to_client.end();) {
708 s32 server_id = i->first;
709 int client_id = i->second;
711 if(!m_sound->soundExists(client_id)) {
712 m_sounds_server_to_client.erase(server_id);
713 m_sounds_client_to_server.erase(client_id);
714 m_sounds_to_objects.erase(client_id);
715 removed_server_ids.push_back(server_id);
720 if(!removed_server_ids.empty()) {
721 sendRemovedSounds(removed_server_ids);
726 if (m_localdb && m_localdb_save_interval.step(dtime,
727 m_cache_save_interval)) {
728 m_localdb->endSave();
729 m_localdb->beginSave();
733 bool Client::loadMedia(const std::string &data, const std::string &filename)
735 // Silly irrlicht's const-incorrectness
736 Buffer<char> data_rw(data.c_str(), data.size());
740 const char *image_ext[] = {
741 ".png", ".jpg", ".bmp", ".tga",
742 ".pcx", ".ppm", ".psd", ".wal", ".rgb",
745 name = removeStringEnd(filename, image_ext);
748 verbosestream<<"Client: Attempting to load image "
749 <<"file \""<<filename<<"\""<<std::endl;
751 io::IFileSystem *irrfs = m_device->getFileSystem();
752 video::IVideoDriver *vdrv = m_device->getVideoDriver();
754 // Create an irrlicht memory file
755 io::IReadFile *rfile = irrfs->createMemoryReadFile(
756 *data_rw, data_rw.getSize(), "_tempreadfile");
758 FATAL_ERROR_IF(!rfile, "Could not create irrlicht memory file.");
761 video::IImage *img = vdrv->createImageFromFile(rfile);
763 errorstream<<"Client: Cannot create image from data of "
764 <<"file \""<<filename<<"\""<<std::endl;
769 m_tsrc->insertSourceImage(filename, img);
776 const char *sound_ext[] = {
777 ".0.ogg", ".1.ogg", ".2.ogg", ".3.ogg", ".4.ogg",
778 ".5.ogg", ".6.ogg", ".7.ogg", ".8.ogg", ".9.ogg",
781 name = removeStringEnd(filename, sound_ext);
784 verbosestream<<"Client: Attempting to load sound "
785 <<"file \""<<filename<<"\""<<std::endl;
786 m_sound->loadSoundData(name, data);
790 const char *model_ext[] = {
791 ".x", ".b3d", ".md2", ".obj",
794 name = removeStringEnd(filename, model_ext);
797 verbosestream<<"Client: Storing model into memory: "
798 <<"\""<<filename<<"\""<<std::endl;
799 if(m_mesh_data.count(filename))
800 errorstream<<"Multiple models with name \""<<filename.c_str()
801 <<"\" found; replacing previous model"<<std::endl;
802 m_mesh_data[filename] = data;
806 errorstream<<"Client: Don't know how to load file \""
807 <<filename<<"\""<<std::endl;
811 // Virtual methods from con::PeerHandler
812 void Client::peerAdded(con::Peer *peer)
814 infostream << "Client::peerAdded(): peer->id="
815 << peer->id << std::endl;
817 void Client::deletingPeer(con::Peer *peer, bool timeout)
819 infostream << "Client::deletingPeer(): "
820 "Server Peer is getting deleted "
821 << "(timeout=" << timeout << ")" << std::endl;
824 m_access_denied = true;
825 m_access_denied_reason = gettext("Connection timed out.");
831 u16 number of files requested
837 void Client::request_media(const std::vector<std::string> &file_requests)
839 std::ostringstream os(std::ios_base::binary);
840 writeU16(os, TOSERVER_REQUEST_MEDIA);
841 size_t file_requests_size = file_requests.size();
843 FATAL_ERROR_IF(file_requests_size > 0xFFFF, "Unsupported number of file requests");
845 // Packet dynamicly resized
846 NetworkPacket pkt(TOSERVER_REQUEST_MEDIA, 2 + 0);
848 pkt << (u16) (file_requests_size & 0xFFFF);
850 for(std::vector<std::string>::const_iterator i = file_requests.begin();
851 i != file_requests.end(); ++i) {
857 infostream << "Client: Sending media request list to server ("
858 << file_requests.size() << " files. packet size)" << std::endl;
861 void Client::received_media()
863 NetworkPacket pkt(TOSERVER_RECEIVED_MEDIA, 0);
865 infostream << "Client: Notifying server that we received all media"
869 void Client::initLocalMapSaving(const Address &address,
870 const std::string &hostname,
871 bool is_local_server)
873 if (!g_settings->getBool("enable_local_map_saving") || is_local_server) {
877 const std::string world_path = porting::path_user
878 + DIR_DELIM + "worlds"
879 + DIR_DELIM + "server_"
880 + hostname + "_" + std::to_string(address.getPort());
882 fs::CreateAllDirs(world_path);
884 m_localdb = new Database_SQLite3(world_path);
885 m_localdb->beginSave();
886 actionstream << "Local map saving started, map will be saved at '" << world_path << "'" << std::endl;
889 void Client::ReceiveAll()
891 DSTACK(FUNCTION_NAME);
892 u32 start_ms = porting::getTimeMs();
895 // Limit time even if there would be huge amounts of data to
897 if(porting::getTimeMs() > start_ms + 100)
902 g_profiler->graphAdd("client_received_packets", 1);
904 catch(con::NoIncomingDataException &e) {
907 catch(con::InvalidIncomingDataException &e) {
908 infostream<<"Client::ReceiveAll(): "
909 "InvalidIncomingDataException: what()="
910 <<e.what()<<std::endl;
915 void Client::Receive()
917 DSTACK(FUNCTION_NAME);
923 inline void Client::handleCommand(NetworkPacket* pkt)
925 const ToClientCommandHandler& opHandle = toClientCommandTable[pkt->getCommand()];
926 (this->*opHandle.handler)(pkt);
930 sender_peer_id given to this shall be quaranteed to be a valid peer
932 void Client::ProcessData(NetworkPacket *pkt)
934 DSTACK(FUNCTION_NAME);
936 ToClientCommand command = (ToClientCommand) pkt->getCommand();
937 u32 sender_peer_id = pkt->getPeerId();
939 //infostream<<"Client: received command="<<command<<std::endl;
940 m_packetcounter.add((u16)command);
943 If this check is removed, be sure to change the queue
944 system to know the ids
946 if(sender_peer_id != PEER_ID_SERVER) {
947 infostream << "Client::ProcessData(): Discarding data not "
948 "coming from server: peer_id=" << sender_peer_id
953 // Command must be handled into ToClientCommandHandler
954 if (command >= TOCLIENT_NUM_MSG_TYPES) {
955 infostream << "Client: Ignoring unknown command "
956 << command << std::endl;
961 * Those packets are handled before m_server_ser_ver is set, it's normal
962 * But we must use the new ToClientConnectionState in the future,
965 if(toClientCommandTable[command].state == TOCLIENT_STATE_NOT_CONNECTED) {
970 if(m_server_ser_ver == SER_FMT_VER_INVALID) {
971 infostream << "Client: Server serialization"
972 " format invalid or not initialized."
973 " Skipping incoming command=" << command << std::endl;
978 Handle runtime commands
984 void Client::Send(NetworkPacket* pkt)
986 m_con.Send(PEER_ID_SERVER,
987 serverCommandFactoryTable[pkt->getCommand()].channel,
989 serverCommandFactoryTable[pkt->getCommand()].reliable);
992 // Will fill up 12 + 12 + 4 + 4 + 4 bytes
993 void writePlayerPos(LocalPlayer *myplayer, ClientMap *clientMap, NetworkPacket *pkt)
995 v3f pf = myplayer->getPosition() * 100;
996 v3f sf = myplayer->getSpeed() * 100;
997 s32 pitch = myplayer->getPitch() * 100;
998 s32 yaw = myplayer->getYaw() * 100;
999 u32 keyPressed = myplayer->keyPressed;
1000 // scaled by 80, so that pi can fit into a u8
1001 u8 fov = clientMap->getCameraFov() * 80;
1002 u8 wanted_range = MYMIN(255,
1003 std::ceil(clientMap->getControl().wanted_range / MAP_BLOCKSIZE));
1005 v3s32 position(pf.X, pf.Y, pf.Z);
1006 v3s32 speed(sf.X, sf.Y, sf.Z);
1010 [0] v3s32 position*100
1011 [12] v3s32 speed*100
1012 [12+12] s32 pitch*100
1013 [12+12+4] s32 yaw*100
1014 [12+12+4+4] u32 keyPressed
1015 [12+12+4+4+4] u8 fov*80
1016 [12+12+4+4+4+1] u8 ceil(wanted_range / MAP_BLOCKSIZE)
1018 *pkt << position << speed << pitch << yaw << keyPressed;
1019 *pkt << fov << wanted_range;
1022 void Client::interact(u8 action, const PointedThing& pointed)
1024 if(m_state != LC_Ready) {
1025 errorstream << "Client::interact() "
1026 "Canceled (not connected)"
1031 LocalPlayer *myplayer = m_env.getLocalPlayer();
1032 if (myplayer == NULL)
1039 [5] u32 length of the next item (plen)
1040 [9] serialized PointedThing
1041 [9 + plen] player position information
1043 0: start digging (from undersurface) or use
1044 1: stop digging (all parameters ignored)
1045 2: digging completed
1046 3: place block or item (to abovesurface)
1048 5: perform secondary action of item
1051 NetworkPacket pkt(TOSERVER_INTERACT, 1 + 2 + 0);
1054 pkt << (u16)getPlayerItem();
1056 std::ostringstream tmp_os(std::ios::binary);
1057 pointed.serialize(tmp_os);
1059 pkt.putLongString(tmp_os.str());
1061 writePlayerPos(myplayer, &m_env.getClientMap(), &pkt);
1066 void Client::deleteAuthData()
1071 switch (m_chosen_auth_mech) {
1072 case AUTH_MECHANISM_FIRST_SRP:
1074 case AUTH_MECHANISM_SRP:
1075 case AUTH_MECHANISM_LEGACY_PASSWORD:
1076 srp_user_delete((SRPUser *) m_auth_data);
1079 case AUTH_MECHANISM_NONE:
1082 m_chosen_auth_mech = AUTH_MECHANISM_NONE;
1086 AuthMechanism Client::choseAuthMech(const u32 mechs)
1088 if (mechs & AUTH_MECHANISM_SRP)
1089 return AUTH_MECHANISM_SRP;
1091 if (mechs & AUTH_MECHANISM_FIRST_SRP)
1092 return AUTH_MECHANISM_FIRST_SRP;
1094 if (mechs & AUTH_MECHANISM_LEGACY_PASSWORD)
1095 return AUTH_MECHANISM_LEGACY_PASSWORD;
1097 return AUTH_MECHANISM_NONE;
1100 void Client::sendLegacyInit(const char* playerName, const char* playerPassword)
1102 NetworkPacket pkt(TOSERVER_INIT_LEGACY,
1103 1 + PLAYERNAME_SIZE + PASSWORD_SIZE + 2 + 2);
1105 u16 proto_version_min = g_settings->getFlag("send_pre_v25_init") ?
1106 CLIENT_PROTOCOL_VERSION_MIN_LEGACY : CLIENT_PROTOCOL_VERSION_MIN;
1108 pkt << (u8) SER_FMT_VER_HIGHEST_READ;
1109 pkt.putRawString(playerName,PLAYERNAME_SIZE);
1110 pkt.putRawString(playerPassword, PASSWORD_SIZE);
1111 pkt << (u16) proto_version_min << (u16) CLIENT_PROTOCOL_VERSION_MAX;
1116 void Client::sendInit(const std::string &playerName)
1118 NetworkPacket pkt(TOSERVER_INIT, 1 + 2 + 2 + (1 + playerName.size()));
1120 // we don't support network compression yet
1121 u16 supp_comp_modes = NETPROTO_COMPRESSION_NONE;
1123 u16 proto_version_min = g_settings->getFlag("send_pre_v25_init") ?
1124 CLIENT_PROTOCOL_VERSION_MIN_LEGACY : CLIENT_PROTOCOL_VERSION_MIN;
1126 pkt << (u8) SER_FMT_VER_HIGHEST_READ << (u16) supp_comp_modes;
1127 pkt << (u16) proto_version_min << (u16) CLIENT_PROTOCOL_VERSION_MAX;
1133 void Client::startAuth(AuthMechanism chosen_auth_mechanism)
1135 m_chosen_auth_mech = chosen_auth_mechanism;
1137 switch (chosen_auth_mechanism) {
1138 case AUTH_MECHANISM_FIRST_SRP: {
1139 // send srp verifier to server
1140 std::string verifier;
1142 generate_srp_verifier_and_salt(getPlayerName(), m_password,
1145 NetworkPacket resp_pkt(TOSERVER_FIRST_SRP, 0);
1146 resp_pkt << salt << verifier << (u8)((m_password == "") ? 1 : 0);
1151 case AUTH_MECHANISM_SRP:
1152 case AUTH_MECHANISM_LEGACY_PASSWORD: {
1155 if (chosen_auth_mechanism == AUTH_MECHANISM_LEGACY_PASSWORD) {
1156 m_password = translate_password(getPlayerName(), m_password);
1160 std::string playername_u = lowercase(getPlayerName());
1161 m_auth_data = srp_user_new(SRP_SHA256, SRP_NG_2048,
1162 getPlayerName().c_str(), playername_u.c_str(),
1163 (const unsigned char *) m_password.c_str(),
1164 m_password.length(), NULL, NULL);
1167 SRP_Result res = srp_user_start_authentication(
1168 (struct SRPUser *) m_auth_data, NULL, NULL, 0,
1169 (unsigned char **) &bytes_A, &len_A);
1170 FATAL_ERROR_IF(res != SRP_OK, "Creating local SRP user failed.");
1172 NetworkPacket resp_pkt(TOSERVER_SRP_BYTES_A, 0);
1173 resp_pkt << std::string(bytes_A, len_A) << based_on;
1177 case AUTH_MECHANISM_NONE:
1178 break; // not handled in this method
1182 void Client::sendDeletedBlocks(std::vector<v3s16> &blocks)
1184 NetworkPacket pkt(TOSERVER_DELETEDBLOCKS, 1 + sizeof(v3s16) * blocks.size());
1186 pkt << (u8) blocks.size();
1189 for(std::vector<v3s16>::iterator
1191 j != blocks.end(); ++j) {
1199 void Client::sendGotBlocks(v3s16 block)
1201 NetworkPacket pkt(TOSERVER_GOTBLOCKS, 1 + 6);
1202 pkt << (u8) 1 << block;
1206 void Client::sendRemovedSounds(std::vector<s32> &soundList)
1208 size_t server_ids = soundList.size();
1209 assert(server_ids <= 0xFFFF);
1211 NetworkPacket pkt(TOSERVER_REMOVED_SOUNDS, 2 + server_ids * 4);
1213 pkt << (u16) (server_ids & 0xFFFF);
1215 for(std::vector<s32>::iterator i = soundList.begin();
1216 i != soundList.end(); ++i)
1222 void Client::sendNodemetaFields(v3s16 p, const std::string &formname,
1223 const StringMap &fields)
1225 size_t fields_size = fields.size();
1227 FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of nodemeta fields");
1229 NetworkPacket pkt(TOSERVER_NODEMETA_FIELDS, 0);
1231 pkt << p << formname << (u16) (fields_size & 0xFFFF);
1233 StringMap::const_iterator it;
1234 for (it = fields.begin(); it != fields.end(); ++it) {
1235 const std::string &name = it->first;
1236 const std::string &value = it->second;
1238 pkt.putLongString(value);
1244 void Client::sendInventoryFields(const std::string &formname,
1245 const StringMap &fields)
1247 size_t fields_size = fields.size();
1248 FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of inventory fields");
1250 NetworkPacket pkt(TOSERVER_INVENTORY_FIELDS, 0);
1251 pkt << formname << (u16) (fields_size & 0xFFFF);
1253 StringMap::const_iterator it;
1254 for (it = fields.begin(); it != fields.end(); ++it) {
1255 const std::string &name = it->first;
1256 const std::string &value = it->second;
1258 pkt.putLongString(value);
1264 void Client::sendInventoryAction(InventoryAction *a)
1266 std::ostringstream os(std::ios_base::binary);
1271 std::string s = os.str();
1273 NetworkPacket pkt(TOSERVER_INVENTORY_ACTION, s.size());
1274 pkt.putRawString(s.c_str(),s.size());
1279 void Client::sendChatMessage(const std::wstring &message)
1281 NetworkPacket pkt(TOSERVER_CHAT_MESSAGE, 2 + message.size() * sizeof(u16));
1288 void Client::sendChangePassword(const std::string &oldpassword,
1289 const std::string &newpassword)
1291 LocalPlayer *player = m_env.getLocalPlayer();
1295 std::string playername = player->getName();
1296 if (m_proto_ver >= 25) {
1297 // get into sudo mode and then send new password to server
1298 m_password = oldpassword;
1299 m_new_password = newpassword;
1300 startAuth(choseAuthMech(m_sudo_auth_methods));
1302 std::string oldpwd = translate_password(playername, oldpassword);
1303 std::string newpwd = translate_password(playername, newpassword);
1305 NetworkPacket pkt(TOSERVER_PASSWORD_LEGACY, 2 * PASSWORD_SIZE);
1307 for (u8 i = 0; i < PASSWORD_SIZE; i++) {
1308 pkt << (u8) (i < oldpwd.length() ? oldpwd[i] : 0);
1311 for (u8 i = 0; i < PASSWORD_SIZE; i++) {
1312 pkt << (u8) (i < newpwd.length() ? newpwd[i] : 0);
1319 void Client::sendDamage(u8 damage)
1321 DSTACK(FUNCTION_NAME);
1323 NetworkPacket pkt(TOSERVER_DAMAGE, sizeof(u8));
1328 void Client::sendBreath(u16 breath)
1330 DSTACK(FUNCTION_NAME);
1332 // Protocol v29 make this obsolete
1333 if (m_proto_ver >= 29)
1336 NetworkPacket pkt(TOSERVER_BREATH, sizeof(u16));
1341 void Client::sendRespawn()
1343 DSTACK(FUNCTION_NAME);
1345 NetworkPacket pkt(TOSERVER_RESPAWN, 0);
1349 void Client::sendReady()
1351 DSTACK(FUNCTION_NAME);
1353 NetworkPacket pkt(TOSERVER_CLIENT_READY,
1354 1 + 1 + 1 + 1 + 2 + sizeof(char) * strlen(g_version_hash));
1356 pkt << (u8) VERSION_MAJOR << (u8) VERSION_MINOR << (u8) VERSION_PATCH
1357 << (u8) 0 << (u16) strlen(g_version_hash);
1359 pkt.putRawString(g_version_hash, (u16) strlen(g_version_hash));
1363 void Client::sendPlayerPos()
1365 LocalPlayer *myplayer = m_env.getLocalPlayer();
1366 if(myplayer == NULL)
1369 ClientMap &map = m_env.getClientMap();
1371 u8 camera_fov = map.getCameraFov();
1372 u8 wanted_range = map.getControl().wanted_range;
1374 // Save bandwidth by only updating position when something changed
1375 if(myplayer->last_position == myplayer->getPosition() &&
1376 myplayer->last_speed == myplayer->getSpeed() &&
1377 myplayer->last_pitch == myplayer->getPitch() &&
1378 myplayer->last_yaw == myplayer->getYaw() &&
1379 myplayer->last_keyPressed == myplayer->keyPressed &&
1380 myplayer->last_camera_fov == camera_fov &&
1381 myplayer->last_wanted_range == wanted_range)
1384 myplayer->last_position = myplayer->getPosition();
1385 myplayer->last_speed = myplayer->getSpeed();
1386 myplayer->last_pitch = myplayer->getPitch();
1387 myplayer->last_yaw = myplayer->getYaw();
1388 myplayer->last_keyPressed = myplayer->keyPressed;
1389 myplayer->last_camera_fov = camera_fov;
1390 myplayer->last_wanted_range = wanted_range;
1392 //infostream << "Sending Player Position information" << std::endl;
1396 //MutexAutoLock lock(m_con_mutex); //bulk comment-out
1397 our_peer_id = m_con.GetPeerID();
1400 // Set peer id if not set already
1401 if(myplayer->peer_id == PEER_ID_INEXISTENT)
1402 myplayer->peer_id = our_peer_id;
1404 assert(myplayer->peer_id == our_peer_id);
1406 NetworkPacket pkt(TOSERVER_PLAYERPOS, 12 + 12 + 4 + 4 + 4 + 1 + 1);
1408 writePlayerPos(myplayer, &map, &pkt);
1413 void Client::sendPlayerItem(u16 item)
1415 LocalPlayer *myplayer = m_env.getLocalPlayer();
1416 if(myplayer == NULL)
1419 u16 our_peer_id = m_con.GetPeerID();
1421 // Set peer id if not set already
1422 if(myplayer->peer_id == PEER_ID_INEXISTENT)
1423 myplayer->peer_id = our_peer_id;
1424 assert(myplayer->peer_id == our_peer_id);
1426 NetworkPacket pkt(TOSERVER_PLAYERITEM, 2);
1433 void Client::removeNode(v3s16 p)
1435 std::map<v3s16, MapBlock*> modified_blocks;
1438 m_env.getMap().removeNodeAndUpdate(p, modified_blocks);
1440 catch(InvalidPositionException &e) {
1443 for(std::map<v3s16, MapBlock *>::iterator
1444 i = modified_blocks.begin();
1445 i != modified_blocks.end(); ++i) {
1446 addUpdateMeshTaskWithEdge(i->first, false, true);
1450 MapNode Client::getNode(v3s16 p, bool *is_valid_position)
1452 return m_env.getMap().getNodeNoEx(p, is_valid_position);
1455 void Client::addNode(v3s16 p, MapNode n, bool remove_metadata)
1457 //TimeTaker timer1("Client::addNode()");
1459 std::map<v3s16, MapBlock*> modified_blocks;
1462 //TimeTaker timer3("Client::addNode(): addNodeAndUpdate");
1463 m_env.getMap().addNodeAndUpdate(p, n, modified_blocks, remove_metadata);
1465 catch(InvalidPositionException &e) {
1468 for(std::map<v3s16, MapBlock *>::iterator
1469 i = modified_blocks.begin();
1470 i != modified_blocks.end(); ++i) {
1471 addUpdateMeshTaskWithEdge(i->first, false, true);
1475 void Client::setPlayerControl(PlayerControl &control)
1477 LocalPlayer *player = m_env.getLocalPlayer();
1478 assert(player != NULL);
1479 player->control = control;
1482 void Client::selectPlayerItem(u16 item)
1484 m_playeritem = item;
1485 m_inventory_updated = true;
1486 sendPlayerItem(item);
1489 // Returns true if the inventory of the local player has been
1490 // updated from the server. If it is true, it is set to false.
1491 bool Client::getLocalInventoryUpdated()
1493 bool updated = m_inventory_updated;
1494 m_inventory_updated = false;
1498 // Copies the inventory of the local player to parameter
1499 void Client::getLocalInventory(Inventory &dst)
1501 LocalPlayer *player = m_env.getLocalPlayer();
1502 assert(player != NULL);
1503 dst = player->inventory;
1506 Inventory* Client::getInventory(const InventoryLocation &loc)
1509 case InventoryLocation::UNDEFINED:
1512 case InventoryLocation::CURRENT_PLAYER:
1514 LocalPlayer *player = m_env.getLocalPlayer();
1515 assert(player != NULL);
1516 return &player->inventory;
1519 case InventoryLocation::PLAYER:
1521 // Check if we are working with local player inventory
1522 LocalPlayer *player = m_env.getLocalPlayer();
1523 if (!player || strcmp(player->getName(), loc.name.c_str()) != 0)
1525 return &player->inventory;
1528 case InventoryLocation::NODEMETA:
1530 NodeMetadata *meta = m_env.getMap().getNodeMetadata(loc.p);
1533 return meta->getInventory();
1536 case InventoryLocation::DETACHED:
1538 if (m_detached_inventories.count(loc.name) == 0)
1540 return m_detached_inventories[loc.name];
1544 FATAL_ERROR("Invalid inventory location type.");
1550 void Client::inventoryAction(InventoryAction *a)
1553 Send it to the server
1555 sendInventoryAction(a);
1558 Predict some local inventory changes
1560 a->clientApply(this, this);
1566 float Client::getAnimationTime()
1568 return m_animation_time;
1571 int Client::getCrackLevel()
1573 return m_crack_level;
1576 void Client::setCrack(int level, v3s16 pos)
1578 int old_crack_level = m_crack_level;
1579 v3s16 old_crack_pos = m_crack_pos;
1581 m_crack_level = level;
1584 if(old_crack_level >= 0 && (level < 0 || pos != old_crack_pos))
1587 addUpdateMeshTaskForNode(old_crack_pos, false, true);
1589 if(level >= 0 && (old_crack_level < 0 || pos != old_crack_pos))
1592 addUpdateMeshTaskForNode(pos, false, true);
1598 LocalPlayer *player = m_env.getLocalPlayer();
1599 assert(player != NULL);
1603 bool Client::getChatMessage(std::wstring &message)
1605 if(m_chat_queue.size() == 0)
1607 message = m_chat_queue.front();
1612 void Client::typeChatMessage(const std::wstring &message)
1614 // Discard empty line
1618 // If message was ate by script API, don't send it to server
1619 if (m_script->on_sending_message(wide_to_utf8(message))) {
1624 sendChatMessage(message);
1627 if (message[0] != L'/')
1629 // compatibility code
1630 if (m_proto_ver < 29) {
1631 LocalPlayer *player = m_env.getLocalPlayer();
1632 assert(player != NULL);
1633 std::wstring name = narrow_to_wide(player->getName());
1634 pushToChatQueue((std::wstring)L"<" + name + L"> " + message);
1639 void Client::addUpdateMeshTask(v3s16 p, bool ack_to_server, bool urgent)
1641 MapBlock *b = m_env.getMap().getBlockNoCreateNoEx(p);
1646 Create a task to update the mesh of the block
1649 MeshMakeData *data = new MeshMakeData(this, m_cache_enable_shaders,
1650 m_cache_use_tangent_vertices);
1653 //TimeTaker timer("data fill");
1655 // Debug: 1-6ms, avg=2ms
1657 data->setCrack(m_crack_level, m_crack_pos);
1658 data->setSmoothLighting(m_cache_smooth_lighting);
1661 // Add task to queue
1662 m_mesh_update_thread.enqueueUpdate(p, data, ack_to_server, urgent);
1665 void Client::addUpdateMeshTaskWithEdge(v3s16 blockpos, bool ack_to_server, bool urgent)
1668 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1670 catch(InvalidPositionException &e){}
1673 for (int i=0;i<6;i++)
1676 v3s16 p = blockpos + g_6dirs[i];
1677 addUpdateMeshTask(p, false, urgent);
1679 catch(InvalidPositionException &e){}
1683 void Client::addUpdateMeshTaskForNode(v3s16 nodepos, bool ack_to_server, bool urgent)
1687 infostream<<"Client::addUpdateMeshTaskForNode(): "
1688 <<"("<<p.X<<","<<p.Y<<","<<p.Z<<")"
1692 v3s16 blockpos = getNodeBlockPos(nodepos);
1693 v3s16 blockpos_relative = blockpos * MAP_BLOCKSIZE;
1696 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1698 catch(InvalidPositionException &e) {}
1701 if(nodepos.X == blockpos_relative.X){
1703 v3s16 p = blockpos + v3s16(-1,0,0);
1704 addUpdateMeshTask(p, false, urgent);
1706 catch(InvalidPositionException &e){}
1709 if(nodepos.Y == blockpos_relative.Y){
1711 v3s16 p = blockpos + v3s16(0,-1,0);
1712 addUpdateMeshTask(p, false, urgent);
1714 catch(InvalidPositionException &e){}
1717 if(nodepos.Z == blockpos_relative.Z){
1719 v3s16 p = blockpos + v3s16(0,0,-1);
1720 addUpdateMeshTask(p, false, urgent);
1722 catch(InvalidPositionException &e){}
1726 ClientEvent Client::getClientEvent()
1729 if (m_client_event_queue.empty()) {
1730 event.type = CE_NONE;
1733 event = m_client_event_queue.front();
1734 m_client_event_queue.pop();
1739 float Client::mediaReceiveProgress()
1741 if (m_media_downloader)
1742 return m_media_downloader->getProgress();
1744 return 1.0; // downloader only exists when not yet done
1747 typedef struct TextureUpdateArgs {
1748 IrrlichtDevice *device;
1749 gui::IGUIEnvironment *guienv;
1752 const wchar_t* text_base;
1753 } TextureUpdateArgs;
1755 void texture_update_progress(void *args, u32 progress, u32 max_progress)
1757 TextureUpdateArgs* targs = (TextureUpdateArgs*) args;
1758 u16 cur_percent = ceil(progress / (double) max_progress * 100.);
1760 // update the loading menu -- if neccessary
1761 bool do_draw = false;
1762 u32 time_ms = targs->last_time_ms;
1763 if (cur_percent != targs->last_percent) {
1764 targs->last_percent = cur_percent;
1765 time_ms = getTimeMs();
1766 // only draw when the user will notice something:
1767 do_draw = (time_ms - targs->last_time_ms > 100);
1771 targs->last_time_ms = time_ms;
1772 std::basic_stringstream<wchar_t> strm;
1773 strm << targs->text_base << " " << targs->last_percent << "%...";
1774 draw_load_screen(strm.str(), targs->device, targs->guienv, 0,
1775 72 + (u16) ((18. / 100.) * (double) targs->last_percent));
1779 void Client::afterContentReceived(IrrlichtDevice *device)
1781 infostream<<"Client::afterContentReceived() started"<<std::endl;
1782 assert(m_itemdef_received); // pre-condition
1783 assert(m_nodedef_received); // pre-condition
1784 assert(mediaReceived()); // pre-condition
1786 const wchar_t* text = wgettext("Loading textures...");
1788 // Clear cached pre-scaled 2D GUI images, as this cache
1789 // might have images with the same name but different
1790 // content from previous sessions.
1791 guiScalingCacheClear(device->getVideoDriver());
1793 // Rebuild inherited images and recreate textures
1794 infostream<<"- Rebuilding images and textures"<<std::endl;
1795 draw_load_screen(text,device, guienv, 0, 70);
1796 m_tsrc->rebuildImagesAndTextures();
1800 infostream<<"- Rebuilding shaders"<<std::endl;
1801 text = wgettext("Rebuilding shaders...");
1802 draw_load_screen(text, device, guienv, 0, 71);
1803 m_shsrc->rebuildShaders();
1806 // Update node aliases
1807 infostream<<"- Updating node aliases"<<std::endl;
1808 text = wgettext("Initializing nodes...");
1809 draw_load_screen(text, device, guienv, 0, 72);
1810 m_nodedef->updateAliases(m_itemdef);
1811 std::string texture_path = g_settings->get("texture_path");
1812 if (texture_path != "" && fs::IsDir(texture_path))
1813 m_nodedef->applyTextureOverrides(texture_path + DIR_DELIM + "override.txt");
1814 m_nodedef->setNodeRegistrationStatus(true);
1815 m_nodedef->runNodeResolveCallbacks();
1818 // Update node textures and assign shaders to each tile
1819 infostream<<"- Updating node textures"<<std::endl;
1820 TextureUpdateArgs tu_args;
1821 tu_args.device = device;
1822 tu_args.guienv = guienv;
1823 tu_args.last_time_ms = getTimeMs();
1824 tu_args.last_percent = 0;
1825 tu_args.text_base = wgettext("Initializing nodes");
1826 m_nodedef->updateTextures(this, texture_update_progress, &tu_args);
1827 delete[] tu_args.text_base;
1829 // Start mesh update thread after setting up content definitions
1830 infostream<<"- Starting mesh update thread"<<std::endl;
1831 m_mesh_update_thread.start();
1835 text = wgettext("Done!");
1836 draw_load_screen(text, device, guienv, 0, 100);
1837 infostream<<"Client::afterContentReceived() done"<<std::endl;
1841 float Client::getRTT(void)
1843 return m_con.getPeerStat(PEER_ID_SERVER,con::AVG_RTT);
1846 float Client::getCurRate(void)
1848 return ( m_con.getLocalStat(con::CUR_INC_RATE) +
1849 m_con.getLocalStat(con::CUR_DL_RATE));
1852 float Client::getAvgRate(void)
1854 return ( m_con.getLocalStat(con::AVG_INC_RATE) +
1855 m_con.getLocalStat(con::AVG_DL_RATE));
1858 void Client::makeScreenshot(IrrlichtDevice *device)
1860 irr::video::IVideoDriver *driver = device->getVideoDriver();
1861 irr::video::IImage* const raw_image = driver->createScreenShot();
1866 time_t t = time(NULL);
1867 struct tm *tm = localtime(&t);
1869 char timetstamp_c[64];
1870 strftime(timetstamp_c, sizeof(timetstamp_c), "%Y%m%d_%H%M%S", tm);
1872 std::string filename_base = g_settings->get("screenshot_path")
1874 + std::string("screenshot_")
1875 + std::string(timetstamp_c);
1876 std::string filename_ext = "." + g_settings->get("screenshot_format");
1877 std::string filename;
1879 u32 quality = (u32)g_settings->getS32("screenshot_quality");
1880 quality = MYMIN(MYMAX(quality, 0), 100) / 100.0 * 255;
1882 // Try to find a unique filename
1883 unsigned serial = 0;
1885 while (serial < SCREENSHOT_MAX_SERIAL_TRIES) {
1886 filename = filename_base + (serial > 0 ? ("_" + itos(serial)) : "") + filename_ext;
1887 std::ifstream tmp(filename.c_str());
1889 break; // File did not apparently exist, we'll go with it
1893 if (serial == SCREENSHOT_MAX_SERIAL_TRIES) {
1894 infostream << "Could not find suitable filename for screenshot" << std::endl;
1896 irr::video::IImage* const image =
1897 driver->createImage(video::ECF_R8G8B8, raw_image->getDimension());
1900 raw_image->copyTo(image);
1902 std::ostringstream sstr;
1903 if (driver->writeImageToFile(image, filename.c_str(), quality)) {
1904 sstr << "Saved screenshot to '" << filename << "'";
1906 sstr << "Failed to save screenshot '" << filename << "'";
1908 pushToChatQueue(narrow_to_wide(sstr.str()));
1909 infostream << sstr.str() << std::endl;
1917 // IGameDef interface
1919 IItemDefManager* Client::getItemDefManager()
1923 INodeDefManager* Client::getNodeDefManager()
1927 ICraftDefManager* Client::getCraftDefManager()
1930 //return m_craftdef;
1932 ITextureSource* Client::getTextureSource()
1936 IShaderSource* Client::getShaderSource()
1940 scene::ISceneManager* Client::getSceneManager()
1942 return m_device->getSceneManager();
1944 u16 Client::allocateUnknownNodeId(const std::string &name)
1946 errorstream << "Client::allocateUnknownNodeId(): "
1947 << "Client cannot allocate node IDs" << std::endl;
1948 FATAL_ERROR("Client allocated unknown node");
1950 return CONTENT_IGNORE;
1952 ISoundManager* Client::getSoundManager()
1956 MtEventManager* Client::getEventManager()
1961 ParticleManager* Client::getParticleManager()
1963 return &m_particle_manager;
1966 scene::IAnimatedMesh* Client::getMesh(const std::string &filename)
1968 StringMap::const_iterator it = m_mesh_data.find(filename);
1969 if (it == m_mesh_data.end()) {
1970 errorstream << "Client::getMesh(): Mesh not found: \"" << filename
1971 << "\"" << std::endl;
1974 const std::string &data = it->second;
1975 scene::ISceneManager *smgr = m_device->getSceneManager();
1977 // Create the mesh, remove it from cache and return it
1978 // This allows unique vertex colors and other properties for each instance
1979 Buffer<char> data_rw(data.c_str(), data.size()); // Const-incorrect Irrlicht
1980 io::IFileSystem *irrfs = m_device->getFileSystem();
1981 io::IReadFile *rfile = irrfs->createMemoryReadFile(
1982 *data_rw, data_rw.getSize(), filename.c_str());
1983 FATAL_ERROR_IF(!rfile, "Could not create/open RAM file");
1985 scene::IAnimatedMesh *mesh = smgr->getMesh(rfile);
1987 // NOTE: By playing with Irrlicht refcounts, maybe we could cache a bunch
1988 // of uniquely named instances and re-use them
1990 smgr->getMeshCache()->removeMesh(mesh);