]> git.lizzy.rs Git - minetest.git/blob - src/client.cpp
8a9d62d2922df193eea653f69360a0ef77fedbe3
[minetest.git] / src / client.cpp
1 /*
2 Minetest
3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4
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.
9
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.
14
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.
18 */
19
20 #include <iostream>
21 #include <algorithm>
22 #include <sstream>
23 #include <IFileSystem.h>
24 #include "jthread/jmutexautolock.h"
25 #include "util/directiontables.h"
26 #include "util/pointedthing.h"
27 #include "util/serialize.h"
28 #include "util/string.h"
29 #include "client.h"
30 #include "network/clientopcodes.h"
31 #include "main.h"
32 #include "filesys.h"
33 #include "porting.h"
34 #include "mapblock_mesh.h"
35 #include "mapblock.h"
36 #include "settings.h"
37 #include "profiler.h"
38 #include "gettext.h"
39 #include "log.h"
40 #include "nodemetadata.h"
41 #include "itemdef.h"
42 #include "shader.h"
43 #include "clientmap.h"
44 #include "clientmedia.h"
45 #include "sound.h"
46 #include "IMeshCache.h"
47 #include "config.h"
48 #include "version.h"
49 #include "drawscene.h"
50 #include "database-sqlite3.h"
51 #include "serialization.h"
52
53 extern gui::IGUIEnvironment* guienv;
54
55 /*
56         QueuedMeshUpdate
57 */
58
59 QueuedMeshUpdate::QueuedMeshUpdate():
60         p(-1337,-1337,-1337),
61         data(NULL),
62         ack_block_to_server(false)
63 {
64 }
65
66 QueuedMeshUpdate::~QueuedMeshUpdate()
67 {
68         if(data)
69                 delete data;
70 }
71
72 /*
73         MeshUpdateQueue
74 */
75
76 MeshUpdateQueue::MeshUpdateQueue()
77 {
78 }
79
80 MeshUpdateQueue::~MeshUpdateQueue()
81 {
82         JMutexAutoLock lock(m_mutex);
83
84         for(std::vector<QueuedMeshUpdate*>::iterator
85                         i = m_queue.begin();
86                         i != m_queue.end(); i++)
87         {
88                 QueuedMeshUpdate *q = *i;
89                 delete q;
90         }
91 }
92
93 /*
94         peer_id=0 adds with nobody to send to
95 */
96 void MeshUpdateQueue::addBlock(v3s16 p, MeshMakeData *data, bool ack_block_to_server, bool urgent)
97 {
98         DSTACK(__FUNCTION_NAME);
99
100         assert(data);   // pre-condition
101
102         JMutexAutoLock lock(m_mutex);
103
104         if(urgent)
105                 m_urgents.insert(p);
106
107         /*
108                 Find if block is already in queue.
109                 If it is, update the data and quit.
110         */
111         for(std::vector<QueuedMeshUpdate*>::iterator
112                         i = m_queue.begin();
113                         i != m_queue.end(); i++)
114         {
115                 QueuedMeshUpdate *q = *i;
116                 if(q->p == p)
117                 {
118                         if(q->data)
119                                 delete q->data;
120                         q->data = data;
121                         if(ack_block_to_server)
122                                 q->ack_block_to_server = true;
123                         return;
124                 }
125         }
126
127         /*
128                 Add the block
129         */
130         QueuedMeshUpdate *q = new QueuedMeshUpdate;
131         q->p = p;
132         q->data = data;
133         q->ack_block_to_server = ack_block_to_server;
134         m_queue.push_back(q);
135 }
136
137 // Returned pointer must be deleted
138 // Returns NULL if queue is empty
139 QueuedMeshUpdate * MeshUpdateQueue::pop()
140 {
141         JMutexAutoLock lock(m_mutex);
142
143         bool must_be_urgent = !m_urgents.empty();
144         for(std::vector<QueuedMeshUpdate*>::iterator
145                         i = m_queue.begin();
146                         i != m_queue.end(); i++)
147         {
148                 QueuedMeshUpdate *q = *i;
149                 if(must_be_urgent && m_urgents.count(q->p) == 0)
150                         continue;
151                 m_queue.erase(i);
152                 m_urgents.erase(q->p);
153                 return q;
154         }
155         return NULL;
156 }
157
158 /*
159         MeshUpdateThread
160 */
161
162 void * MeshUpdateThread::Thread()
163 {
164         ThreadStarted();
165
166         log_register_thread("MeshUpdateThread");
167
168         DSTACK(__FUNCTION_NAME);
169
170         BEGIN_DEBUG_EXCEPTION_HANDLER
171
172         porting::setThreadName("MeshUpdateThread");
173
174         while(!StopRequested())
175         {
176                 QueuedMeshUpdate *q = m_queue_in.pop();
177                 if(q == NULL)
178                 {
179                         sleep_ms(3);
180                         continue;
181                 }
182
183                 ScopeProfiler sp(g_profiler, "Client: Mesh making");
184
185                 MapBlockMesh *mesh_new = new MapBlockMesh(q->data, m_camera_offset);
186                 if(mesh_new->getMesh()->getMeshBufferCount() == 0)
187                 {
188                         delete mesh_new;
189                         mesh_new = NULL;
190                 }
191
192                 MeshUpdateResult r;
193                 r.p = q->p;
194                 r.mesh = mesh_new;
195                 r.ack_block_to_server = q->ack_block_to_server;
196
197                 m_queue_out.push_back(r);
198
199                 delete q;
200         }
201
202         END_DEBUG_EXCEPTION_HANDLER(errorstream)
203
204         return NULL;
205 }
206
207 /*
208         Client
209 */
210
211 Client::Client(
212                 IrrlichtDevice *device,
213                 const char *playername,
214                 std::string password,
215                 MapDrawControl &control,
216                 IWritableTextureSource *tsrc,
217                 IWritableShaderSource *shsrc,
218                 IWritableItemDefManager *itemdef,
219                 IWritableNodeDefManager *nodedef,
220                 ISoundManager *sound,
221                 MtEventManager *event,
222                 bool ipv6
223 ):
224         m_packetcounter_timer(0.0),
225         m_connection_reinit_timer(0.1),
226         m_avg_rtt_timer(0.0),
227         m_playerpos_send_timer(0.0),
228         m_ignore_damage_timer(0.0),
229         m_tsrc(tsrc),
230         m_shsrc(shsrc),
231         m_itemdef(itemdef),
232         m_nodedef(nodedef),
233         m_sound(sound),
234         m_event(event),
235         m_mesh_update_thread(this),
236         m_env(
237                 new ClientMap(this, this, control,
238                         device->getSceneManager()->getRootSceneNode(),
239                         device->getSceneManager(), 666),
240                 device->getSceneManager(),
241                 tsrc, this, device
242         ),
243         m_particle_manager(&m_env),
244         m_con(PROTOCOL_ID, 512, CONNECTION_TIMEOUT, ipv6, this),
245         m_device(device),
246         m_server_ser_ver(SER_FMT_VER_INVALID),
247         m_playeritem(0),
248         m_inventory_updated(false),
249         m_inventory_from_server(NULL),
250         m_inventory_from_server_age(0.0),
251         m_show_highlighted(false),
252         m_animation_time(0),
253         m_crack_level(-1),
254         m_crack_pos(0,0,0),
255         m_highlighted_pos(0,0,0),
256         m_map_seed(0),
257         m_password(password),
258         m_access_denied(false),
259         m_itemdef_received(false),
260         m_nodedef_received(false),
261         m_media_downloader(new ClientMediaDownloader()),
262         m_time_of_day_set(false),
263         m_last_time_of_day_f(-1),
264         m_time_of_day_update_timer(0),
265         m_recommended_send_interval(0.1),
266         m_removed_sounds_check_timer(0),
267         m_state(LC_Created),
268         m_localdb(NULL)
269 {
270         // Add local player
271         m_env.addPlayer(new LocalPlayer(this, playername));
272
273         m_cache_save_interval = g_settings->getU16("server_map_save_interval");
274
275         m_cache_smooth_lighting = g_settings->getBool("smooth_lighting");
276         m_cache_enable_shaders  = g_settings->getBool("enable_shaders");
277 }
278
279 void Client::Stop()
280 {
281         //request all client managed threads to stop
282         m_mesh_update_thread.Stop();
283         // Save local server map
284         if (m_localdb) {
285                 infostream << "Local map saving ended." << std::endl;
286                 m_localdb->endSave();
287         }
288 }
289
290 bool Client::isShutdown()
291 {
292
293         if (!m_mesh_update_thread.IsRunning()) return true;
294
295         return false;
296 }
297
298 Client::~Client()
299 {
300         m_con.Disconnect();
301
302         m_mesh_update_thread.Stop();
303         m_mesh_update_thread.Wait();
304         while(!m_mesh_update_thread.m_queue_out.empty()) {
305                 MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_frontNoEx();
306                 delete r.mesh;
307         }
308
309
310         delete m_inventory_from_server;
311
312         // Delete detached inventories
313         for(std::map<std::string, Inventory*>::iterator
314                         i = m_detached_inventories.begin();
315                         i != m_detached_inventories.end(); i++){
316                 delete i->second;
317         }
318
319         // cleanup 3d model meshes on client shutdown
320         while (m_device->getSceneManager()->getMeshCache()->getMeshCount() != 0) {
321                 scene::IAnimatedMesh * mesh =
322                         m_device->getSceneManager()->getMeshCache()->getMeshByIndex(0);
323
324                 if (mesh != NULL)
325                         m_device->getSceneManager()->getMeshCache()->removeMesh(mesh);
326         }
327 }
328
329 void Client::connect(Address address,
330                 const std::string &address_name,
331                 bool is_local_server)
332 {
333         DSTACK(__FUNCTION_NAME);
334
335         initLocalMapSaving(address, address_name, is_local_server);
336
337         m_con.SetTimeoutMs(0);
338         m_con.Connect(address);
339 }
340
341 void Client::step(float dtime)
342 {
343         DSTACK(__FUNCTION_NAME);
344
345         // Limit a bit
346         if(dtime > 2.0)
347                 dtime = 2.0;
348
349         if(m_ignore_damage_timer > dtime)
350                 m_ignore_damage_timer -= dtime;
351         else
352                 m_ignore_damage_timer = 0.0;
353
354         m_animation_time += dtime;
355         if(m_animation_time > 60.0)
356                 m_animation_time -= 60.0;
357
358         m_time_of_day_update_timer += dtime;
359
360         ReceiveAll();
361
362         /*
363                 Packet counter
364         */
365         {
366                 float &counter = m_packetcounter_timer;
367                 counter -= dtime;
368                 if(counter <= 0.0)
369                 {
370                         counter = 20.0;
371
372                         infostream << "Client packetcounter (" << m_packetcounter_timer
373                                         << "):"<<std::endl;
374                         m_packetcounter.print(infostream);
375                         m_packetcounter.clear();
376                 }
377         }
378
379         // UGLY hack to fix 2 second startup delay caused by non existent
380         // server client startup synchronization in local server or singleplayer mode
381         static bool initial_step = true;
382         if (initial_step) {
383                 initial_step = false;
384         }
385         else if(m_state == LC_Created) {
386                 float &counter = m_connection_reinit_timer;
387                 counter -= dtime;
388                 if(counter <= 0.0) {
389                         counter = 2.0;
390
391                         Player *myplayer = m_env.getLocalPlayer();              
392                         FATAL_ERROR_IF(myplayer == NULL, "Local player not found in environment.");
393
394                         // Send TOSERVER_INIT
395                         // [0] u16 TOSERVER_INIT
396                         // [2] u8 SER_FMT_VER_HIGHEST_READ
397                         // [3] u8[20] player_name
398                         // [23] u8[28] password (new in some version)
399                         // [51] u16 minimum supported network protocol version (added sometime)
400                         // [53] u16 maximum supported network protocol version (added later than the previous one)
401
402                         char pName[PLAYERNAME_SIZE];
403                         char pPassword[PASSWORD_SIZE];
404                         memset(pName, 0, PLAYERNAME_SIZE * sizeof(char));
405                         memset(pPassword, 0, PASSWORD_SIZE * sizeof(char));
406
407                         snprintf(pName, PLAYERNAME_SIZE, "%s", myplayer->getName());
408                         snprintf(pPassword, PASSWORD_SIZE, "%s", m_password.c_str());
409
410                         NetworkPacket pkt(TOSERVER_INIT_LEGACY,
411                                         1 + PLAYERNAME_SIZE + PASSWORD_SIZE + 2 + 2);
412
413                         pkt << (u8) SER_FMT_VER_HIGHEST_READ;
414                         pkt.putRawString(pName,PLAYERNAME_SIZE);
415                         pkt.putRawString(pPassword, PASSWORD_SIZE);
416                         pkt << (u16) CLIENT_PROTOCOL_VERSION_MIN << (u16) CLIENT_PROTOCOL_VERSION_MAX;
417
418                         Send(&pkt);
419                 }
420
421                 // Not connected, return
422                 return;
423         }
424
425         /*
426                 Do stuff if connected
427         */
428
429         /*
430                 Run Map's timers and unload unused data
431         */
432         const float map_timer_and_unload_dtime = 5.25;
433         if(m_map_timer_and_unload_interval.step(dtime, map_timer_and_unload_dtime)) {
434                 ScopeProfiler sp(g_profiler, "Client: map timer and unload");
435                 std::vector<v3s16> deleted_blocks;
436                 m_env.getMap().timerUpdate(map_timer_and_unload_dtime,
437                                 g_settings->getFloat("client_unload_unused_data_timeout"),
438                                 &deleted_blocks);
439
440                 /*
441                         Send info to server
442                         NOTE: This loop is intentionally iterated the way it is.
443                 */
444
445                 std::vector<v3s16>::iterator i = deleted_blocks.begin();
446                 std::vector<v3s16> sendlist;
447                 for(;;) {
448                         if(sendlist.size() == 255 || i == deleted_blocks.end()) {
449                                 if(sendlist.empty())
450                                         break;
451                                 /*
452                                         [0] u16 command
453                                         [2] u8 count
454                                         [3] v3s16 pos_0
455                                         [3+6] v3s16 pos_1
456                                         ...
457                                 */
458                                 NetworkPacket pkt(TOSERVER_DELETEDBLOCKS, 1 + sizeof(v3s16) * sendlist.size());
459
460                                 pkt << (u8) sendlist.size();
461
462                                 u32 k = 0;
463                                 for(std::vector<v3s16>::iterator
464                                                 j = sendlist.begin();
465                                                 j != sendlist.end(); ++j) {
466                                         pkt << *j;
467                                         k++;
468                                 }
469
470                                 Send(&pkt);
471
472                                 if(i == deleted_blocks.end())
473                                         break;
474
475                                 sendlist.clear();
476                         }
477
478                         sendlist.push_back(*i);
479                         ++i;
480                 }
481         }
482
483         /*
484                 Handle environment
485         */
486         // Control local player (0ms)
487         LocalPlayer *player = m_env.getLocalPlayer();
488         assert(player != NULL);
489         player->applyControl(dtime);
490
491         // Step environment
492         m_env.step(dtime);
493
494         /*
495                 Get events
496         */
497         for(;;) {
498                 ClientEnvEvent event = m_env.getClientEvent();
499                 if(event.type == CEE_NONE) {
500                         break;
501                 }
502                 else if(event.type == CEE_PLAYER_DAMAGE) {
503                         if(m_ignore_damage_timer <= 0) {
504                                 u8 damage = event.player_damage.amount;
505
506                                 if(event.player_damage.send_to_server)
507                                         sendDamage(damage);
508
509                                 // Add to ClientEvent queue
510                                 ClientEvent event;
511                                 event.type = CE_PLAYER_DAMAGE;
512                                 event.player_damage.amount = damage;
513                                 m_client_event_queue.push(event);
514                         }
515                 }
516                 else if(event.type == CEE_PLAYER_BREATH) {
517                                 u16 breath = event.player_breath.amount;
518                                 sendBreath(breath);
519                 }
520         }
521
522         /*
523                 Print some info
524         */
525         float &counter = m_avg_rtt_timer;
526         counter += dtime;
527         if(counter >= 10) {
528                 counter = 0.0;
529                 // connectedAndInitialized() is true, peer exists.
530                 float avg_rtt = getRTT();
531                 infostream << "Client: avg_rtt=" << avg_rtt << std::endl;
532         }
533
534         /*
535                 Send player position to server
536         */
537         {
538                 float &counter = m_playerpos_send_timer;
539                 counter += dtime;
540                 if((m_state == LC_Ready) && (counter >= m_recommended_send_interval))
541                 {
542                         counter = 0.0;
543                         sendPlayerPos();
544                 }
545         }
546
547         /*
548                 Replace updated meshes
549         */
550         {
551                 int num_processed_meshes = 0;
552                 while(!m_mesh_update_thread.m_queue_out.empty())
553                 {
554                         num_processed_meshes++;
555                         MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_frontNoEx();
556                         MapBlock *block = m_env.getMap().getBlockNoCreateNoEx(r.p);
557                         if(block) {
558                                 // Delete the old mesh
559                                 if(block->mesh != NULL)
560                                 {
561                                         // TODO: Remove hardware buffers of meshbuffers of block->mesh
562                                         delete block->mesh;
563                                         block->mesh = NULL;
564                                 }
565
566                                 // Replace with the new mesh
567                                 block->mesh = r.mesh;
568                         } else {
569                                 delete r.mesh;
570                         }
571
572                         if(r.ack_block_to_server) {
573                                 /*
574                                         Acknowledge block
575                                         [0] u8 count
576                                         [1] v3s16 pos_0
577                                 */
578                                 NetworkPacket pkt(TOSERVER_GOTBLOCKS, 1 + 6);
579                                 pkt << (u8) 1 << r.p;
580                                 Send(&pkt);
581                         }
582                 }
583
584                 if(num_processed_meshes > 0)
585                         g_profiler->graphAdd("num_processed_meshes", num_processed_meshes);
586         }
587
588         /*
589                 Load fetched media
590         */
591         if (m_media_downloader && m_media_downloader->isStarted()) {
592                 m_media_downloader->step(this);
593                 if (m_media_downloader->isDone()) {
594                         received_media();
595                         delete m_media_downloader;
596                         m_media_downloader = NULL;
597                 }
598         }
599
600         /*
601                 If the server didn't update the inventory in a while, revert
602                 the local inventory (so the player notices the lag problem
603                 and knows something is wrong).
604         */
605         if(m_inventory_from_server)
606         {
607                 float interval = 10.0;
608                 float count_before = floor(m_inventory_from_server_age / interval);
609
610                 m_inventory_from_server_age += dtime;
611
612                 float count_after = floor(m_inventory_from_server_age / interval);
613
614                 if(count_after != count_before)
615                 {
616                         // Do this every <interval> seconds after TOCLIENT_INVENTORY
617                         // Reset the locally changed inventory to the authoritative inventory
618                         Player *player = m_env.getLocalPlayer();
619                         player->inventory = *m_inventory_from_server;
620                         m_inventory_updated = true;
621                 }
622         }
623
624         /*
625                 Update positions of sounds attached to objects
626         */
627         {
628                 for(std::map<int, u16>::iterator
629                                 i = m_sounds_to_objects.begin();
630                                 i != m_sounds_to_objects.end(); i++)
631                 {
632                         int client_id = i->first;
633                         u16 object_id = i->second;
634                         ClientActiveObject *cao = m_env.getActiveObject(object_id);
635                         if(!cao)
636                                 continue;
637                         v3f pos = cao->getPosition();
638                         m_sound->updateSoundPosition(client_id, pos);
639                 }
640         }
641
642         /*
643                 Handle removed remotely initiated sounds
644         */
645         m_removed_sounds_check_timer += dtime;
646         if(m_removed_sounds_check_timer >= 2.32) {
647                 m_removed_sounds_check_timer = 0;
648                 // Find removed sounds and clear references to them
649                 std::set<s32> removed_server_ids;
650                 for(std::map<s32, int>::iterator
651                                 i = m_sounds_server_to_client.begin();
652                                 i != m_sounds_server_to_client.end();) {
653                         s32 server_id = i->first;
654                         int client_id = i->second;
655                         i++;
656                         if(!m_sound->soundExists(client_id)) {
657                                 m_sounds_server_to_client.erase(server_id);
658                                 m_sounds_client_to_server.erase(client_id);
659                                 m_sounds_to_objects.erase(client_id);
660                                 removed_server_ids.insert(server_id);
661                         }
662                 }
663
664                 // Sync to server
665                 if(!removed_server_ids.empty()) {
666                         size_t server_ids = removed_server_ids.size();
667                         assert(server_ids <= 0xFFFF);
668
669                         NetworkPacket pkt(TOSERVER_REMOVED_SOUNDS, 2 + server_ids * 4);
670
671                         pkt << (u16) (server_ids & 0xFFFF);
672
673                         for(std::set<s32>::iterator i = removed_server_ids.begin();
674                                         i != removed_server_ids.end(); i++)
675                                 pkt << *i;
676
677                         Send(&pkt);
678                 }
679         }
680
681         // Write server map
682         if (m_localdb && m_localdb_save_interval.step(dtime,
683                         m_cache_save_interval)) {
684                 m_localdb->endSave();
685                 m_localdb->beginSave();
686         }
687 }
688
689 bool Client::loadMedia(const std::string &data, const std::string &filename)
690 {
691         // Silly irrlicht's const-incorrectness
692         Buffer<char> data_rw(data.c_str(), data.size());
693
694         std::string name;
695
696         const char *image_ext[] = {
697                 ".png", ".jpg", ".bmp", ".tga",
698                 ".pcx", ".ppm", ".psd", ".wal", ".rgb",
699                 NULL
700         };
701         name = removeStringEnd(filename, image_ext);
702         if(name != "")
703         {
704                 verbosestream<<"Client: Attempting to load image "
705                 <<"file \""<<filename<<"\""<<std::endl;
706
707                 io::IFileSystem *irrfs = m_device->getFileSystem();
708                 video::IVideoDriver *vdrv = m_device->getVideoDriver();
709
710                 // Create an irrlicht memory file
711                 io::IReadFile *rfile = irrfs->createMemoryReadFile(
712                                 *data_rw, data_rw.getSize(), "_tempreadfile");
713
714                 FATAL_ERROR_IF(!rfile, "Could not create irrlicht memory file.");
715
716                 // Read image
717                 video::IImage *img = vdrv->createImageFromFile(rfile);
718                 if(!img){
719                         errorstream<<"Client: Cannot create image from data of "
720                                         <<"file \""<<filename<<"\""<<std::endl;
721                         rfile->drop();
722                         return false;
723                 }
724                 else {
725                         m_tsrc->insertSourceImage(filename, img);
726                         img->drop();
727                         rfile->drop();
728                         return true;
729                 }
730         }
731
732         const char *sound_ext[] = {
733                 ".0.ogg", ".1.ogg", ".2.ogg", ".3.ogg", ".4.ogg",
734                 ".5.ogg", ".6.ogg", ".7.ogg", ".8.ogg", ".9.ogg",
735                 ".ogg", NULL
736         };
737         name = removeStringEnd(filename, sound_ext);
738         if(name != "")
739         {
740                 verbosestream<<"Client: Attempting to load sound "
741                 <<"file \""<<filename<<"\""<<std::endl;
742                 m_sound->loadSoundData(name, data);
743                 return true;
744         }
745
746         const char *model_ext[] = {
747                 ".x", ".b3d", ".md2", ".obj",
748                 NULL
749         };
750         name = removeStringEnd(filename, model_ext);
751         if(name != "")
752         {
753                 verbosestream<<"Client: Storing model into memory: "
754                                 <<"\""<<filename<<"\""<<std::endl;
755                 if(m_mesh_data.count(filename))
756                         errorstream<<"Multiple models with name \""<<filename.c_str()
757                                         <<"\" found; replacing previous model"<<std::endl;
758                 m_mesh_data[filename] = data;
759                 return true;
760         }
761
762         errorstream<<"Client: Don't know how to load file \""
763                         <<filename<<"\""<<std::endl;
764         return false;
765 }
766
767 // Virtual methods from con::PeerHandler
768 void Client::peerAdded(con::Peer *peer)
769 {
770         infostream<<"Client::peerAdded(): peer->id="
771                         <<peer->id<<std::endl;
772 }
773 void Client::deletingPeer(con::Peer *peer, bool timeout)
774 {
775         infostream<<"Client::deletingPeer(): "
776                         "Server Peer is getting deleted "
777                         <<"(timeout="<<timeout<<")"<<std::endl;
778 }
779
780 /*
781         u16 command
782         u16 number of files requested
783         for each file {
784                 u16 length of name
785                 string name
786         }
787 */
788 void Client::request_media(const std::vector<std::string> &file_requests)
789 {
790         std::ostringstream os(std::ios_base::binary);
791         writeU16(os, TOSERVER_REQUEST_MEDIA);
792         size_t file_requests_size = file_requests.size();
793
794         FATAL_ERROR_IF(file_requests_size > 0xFFFF, "Unsupported number of file requests");
795
796         // Packet dynamicly resized
797         NetworkPacket pkt(TOSERVER_REQUEST_MEDIA, 2 + 0);
798
799         pkt << (u16) (file_requests_size & 0xFFFF);
800
801         for(std::vector<std::string>::const_iterator i = file_requests.begin();
802                         i != file_requests.end(); ++i) {
803                 pkt << (*i);
804         }
805
806         Send(&pkt);
807
808         infostream << "Client: Sending media request list to server ("
809                         << file_requests.size() << " files. packet size)" << std::endl;
810 }
811
812 void Client::received_media()
813 {
814         NetworkPacket pkt(TOSERVER_RECEIVED_MEDIA, 0);
815         Send(&pkt);
816         infostream << "Client: Notifying server that we received all media"
817                         << std::endl;
818 }
819
820 void Client::initLocalMapSaving(const Address &address,
821                 const std::string &hostname,
822                 bool is_local_server)
823 {
824         if (!g_settings->getBool("enable_local_map_saving") || is_local_server) {
825                 return;
826         }
827
828         const std::string world_path = porting::path_user
829                 + DIR_DELIM + "worlds"
830                 + DIR_DELIM + "server_"
831                 + hostname + "_" + to_string(address.getPort());
832
833         fs::CreateAllDirs(world_path);
834
835         m_localdb = new Database_SQLite3(world_path);
836         m_localdb->beginSave();
837         actionstream << "Local map saving started, map will be saved at '" << world_path << "'" << std::endl;
838 }
839
840 void Client::ReceiveAll()
841 {
842         DSTACK(__FUNCTION_NAME);
843         u32 start_ms = porting::getTimeMs();
844         for(;;)
845         {
846                 // Limit time even if there would be huge amounts of data to
847                 // process
848                 if(porting::getTimeMs() > start_ms + 100)
849                         break;
850
851                 try {
852                         Receive();
853                         g_profiler->graphAdd("client_received_packets", 1);
854                 }
855                 catch(con::NoIncomingDataException &e) {
856                         break;
857                 }
858                 catch(con::InvalidIncomingDataException &e) {
859                         infostream<<"Client::ReceiveAll(): "
860                                         "InvalidIncomingDataException: what()="
861                                         <<e.what()<<std::endl;
862                 }
863         }
864 }
865
866 void Client::Receive()
867 {
868         DSTACK(__FUNCTION_NAME);
869         SharedBuffer<u8> data;
870         u16 sender_peer_id;
871         u32 datasize = m_con.Receive(sender_peer_id, data);
872         ProcessData(*data, datasize, sender_peer_id);
873 }
874
875 inline void Client::handleCommand(NetworkPacket* pkt)
876 {
877         const ToClientCommandHandler& opHandle = toClientCommandTable[pkt->getCommand()];
878         (this->*opHandle.handler)(pkt);
879 }
880
881 /*
882         sender_peer_id given to this shall be quaranteed to be a valid peer
883 */
884 void Client::ProcessData(u8 *data, u32 datasize, u16 sender_peer_id)
885 {
886         DSTACK(__FUNCTION_NAME);
887
888         // Ignore packets that don't even fit a command
889         if(datasize < 2) {
890                 m_packetcounter.add(60000);
891                 return;
892         }
893
894         NetworkPacket pkt(data, datasize, sender_peer_id);
895
896         ToClientCommand command = (ToClientCommand) pkt.getCommand();
897
898         //infostream<<"Client: received command="<<command<<std::endl;
899         m_packetcounter.add((u16)command);
900
901         /*
902                 If this check is removed, be sure to change the queue
903                 system to know the ids
904         */
905         if(sender_peer_id != PEER_ID_SERVER) {
906                 infostream << "Client::ProcessData(): Discarding data not "
907                         "coming from server: peer_id=" << sender_peer_id
908                         << std::endl;
909                 return;
910         }
911
912         // Command must be handled into ToClientCommandHandler
913         if (command >= TOCLIENT_NUM_MSG_TYPES) {
914                 infostream << "Client: Ignoring unknown command "
915                         << command << std::endl;
916         }
917
918         /*
919          * Those packets are handled before m_server_ser_ver is set, it's normal
920          * But we must use the new ToClientConnectionState in the future,
921          * as a byte mask
922          */
923         if(toClientCommandTable[command].state == TOCLIENT_STATE_NOT_CONNECTED) {
924                 handleCommand(&pkt);
925                 return;
926         }
927
928         if(m_server_ser_ver == SER_FMT_VER_INVALID) {
929                 infostream << "Client: Server serialization"
930                                 " format invalid or not initialized."
931                                 " Skipping incoming command=" << command << std::endl;
932                 return;
933         }
934
935         /*
936           Handle runtime commands
937         */
938
939         handleCommand(&pkt);
940 }
941
942 void Client::Send(NetworkPacket* pkt)
943 {
944         m_con.Send(PEER_ID_SERVER,
945                 serverCommandFactoryTable[pkt->getCommand()].channel,
946                 pkt,
947                 serverCommandFactoryTable[pkt->getCommand()].reliable);
948 }
949
950 void Client::interact(u8 action, const PointedThing& pointed)
951 {
952         if(m_state != LC_Ready) {
953                 errorstream << "Client::interact() "
954                                 "Canceled (not connected)"
955                                 << std::endl;
956                 return;
957         }
958
959         /*
960                 [0] u16 command
961                 [2] u8 action
962                 [3] u16 item
963                 [5] u32 length of the next item
964                 [9] serialized PointedThing
965                 actions:
966                 0: start digging (from undersurface) or use
967                 1: stop digging (all parameters ignored)
968                 2: digging completed
969                 3: place block or item (to abovesurface)
970                 4: use item
971         */
972
973         NetworkPacket pkt(TOSERVER_INTERACT, 1 + 2 + 0);
974
975         pkt << action;
976         pkt << (u16)getPlayerItem();
977
978         std::ostringstream tmp_os(std::ios::binary);
979         pointed.serialize(tmp_os);
980
981         pkt.putLongString(tmp_os.str());
982
983         Send(&pkt);
984 }
985
986 void Client::sendNodemetaFields(v3s16 p, const std::string &formname,
987                 const std::map<std::string, std::string> &fields)
988 {
989         size_t fields_size = fields.size();
990
991         FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of nodemeta fields");
992
993         NetworkPacket pkt(TOSERVER_NODEMETA_FIELDS, 0);
994
995         pkt << p << formname << (u16) (fields_size & 0xFFFF);
996
997         for(std::map<std::string, std::string>::const_iterator
998                         i = fields.begin(); i != fields.end(); i++) {
999                 const std::string &name = i->first;
1000                 const std::string &value = i->second;
1001                 pkt << name;
1002                 pkt.putLongString(value);
1003         }
1004
1005         Send(&pkt);
1006 }
1007
1008 void Client::sendInventoryFields(const std::string &formname,
1009                 const std::map<std::string, std::string> &fields)
1010 {
1011         size_t fields_size = fields.size();
1012         FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of inventory fields");
1013
1014         NetworkPacket pkt(TOSERVER_INVENTORY_FIELDS, 0);
1015         pkt << formname << (u16) (fields_size & 0xFFFF);
1016
1017         for(std::map<std::string, std::string>::const_iterator
1018                         i = fields.begin(); i != fields.end(); i++) {
1019                 const std::string &name  = i->first;
1020                 const std::string &value = i->second;
1021                 pkt << name;
1022                 pkt.putLongString(value);
1023         }
1024
1025         Send(&pkt);
1026 }
1027
1028 void Client::sendInventoryAction(InventoryAction *a)
1029 {
1030         std::ostringstream os(std::ios_base::binary);
1031
1032         a->serialize(os);
1033
1034         // Make data buffer
1035         std::string s = os.str();
1036
1037         NetworkPacket pkt(TOSERVER_INVENTORY_ACTION, s.size());
1038         pkt.putRawString(s.c_str(),s.size());
1039
1040         Send(&pkt);
1041 }
1042
1043 void Client::sendChatMessage(const std::wstring &message)
1044 {
1045         NetworkPacket pkt(TOSERVER_CHAT_MESSAGE, 2 + message.size() * sizeof(u16));
1046
1047         pkt << message;
1048
1049         Send(&pkt);
1050 }
1051
1052 void Client::sendChangePassword(const std::wstring &oldpassword,
1053         const std::wstring &newpassword)
1054 {
1055         Player *player = m_env.getLocalPlayer();
1056         if(player == NULL)
1057                 return;
1058
1059         std::string playername = player->getName();
1060         std::string oldpwd = translatePassword(playername, oldpassword);
1061         std::string newpwd = translatePassword(playername, newpassword);
1062
1063         NetworkPacket pkt(TOSERVER_PASSWORD_LEGACY, 2 * PASSWORD_SIZE);
1064
1065         for(u8 i = 0; i < PASSWORD_SIZE; i++) {
1066                 pkt << (u8) (i < oldpwd.length() ? oldpwd[i] : 0);
1067         }
1068
1069         for(u8 i = 0; i < PASSWORD_SIZE; i++) {
1070                 pkt << (u8) (i < newpwd.length() ? newpwd[i] : 0);
1071         }
1072
1073         Send(&pkt);
1074 }
1075
1076
1077 void Client::sendDamage(u8 damage)
1078 {
1079         DSTACK(__FUNCTION_NAME);
1080
1081         NetworkPacket pkt(TOSERVER_DAMAGE, sizeof(u8));
1082         pkt << damage;
1083         Send(&pkt);
1084 }
1085
1086 void Client::sendBreath(u16 breath)
1087 {
1088         DSTACK(__FUNCTION_NAME);
1089
1090         NetworkPacket pkt(TOSERVER_BREATH, sizeof(u16));
1091         pkt << breath;
1092         Send(&pkt);
1093 }
1094
1095 void Client::sendRespawn()
1096 {
1097         DSTACK(__FUNCTION_NAME);
1098
1099         NetworkPacket pkt(TOSERVER_RESPAWN, 0);
1100         Send(&pkt);
1101 }
1102
1103 void Client::sendReady()
1104 {
1105         DSTACK(__FUNCTION_NAME);
1106
1107         NetworkPacket pkt(TOSERVER_CLIENT_READY,
1108                         1 + 1 + 1 + 1 + 2 + sizeof(char) * strlen(minetest_version_hash));
1109
1110         pkt << (u8) VERSION_MAJOR << (u8) VERSION_MINOR << (u8) VERSION_PATCH_ORIG
1111                 << (u8) 0 << (u16) strlen(minetest_version_hash);
1112
1113         pkt.putRawString(minetest_version_hash, (u16) strlen(minetest_version_hash));
1114         Send(&pkt);
1115 }
1116
1117 void Client::sendPlayerPos()
1118 {
1119         LocalPlayer *myplayer = m_env.getLocalPlayer();
1120         if(myplayer == NULL)
1121                 return;
1122
1123         // Save bandwidth by only updating position when something changed
1124         if(myplayer->last_position        == myplayer->getPosition() &&
1125                         myplayer->last_speed      == myplayer->getSpeed()    &&
1126                         myplayer->last_pitch      == myplayer->getPitch()    &&
1127                         myplayer->last_yaw        == myplayer->getYaw()      &&
1128                         myplayer->last_keyPressed == myplayer->keyPressed)
1129                 return;
1130
1131         myplayer->last_position   = myplayer->getPosition();
1132         myplayer->last_speed      = myplayer->getSpeed();
1133         myplayer->last_pitch      = myplayer->getPitch();
1134         myplayer->last_yaw        = myplayer->getYaw();
1135         myplayer->last_keyPressed = myplayer->keyPressed;
1136
1137         u16 our_peer_id;
1138         {
1139                 //JMutexAutoLock lock(m_con_mutex); //bulk comment-out
1140                 our_peer_id = m_con.GetPeerID();
1141         }
1142
1143         // Set peer id if not set already
1144         if(myplayer->peer_id == PEER_ID_INEXISTENT)
1145                 myplayer->peer_id = our_peer_id;
1146
1147         assert(myplayer->peer_id == our_peer_id);
1148
1149         v3f pf         = myplayer->getPosition();
1150         v3f sf         = myplayer->getSpeed();
1151         s32 pitch      = myplayer->getPitch() * 100;
1152         s32 yaw        = myplayer->getYaw() * 100;
1153         u32 keyPressed = myplayer->keyPressed;
1154
1155         v3s32 position(pf.X*100, pf.Y*100, pf.Z*100);
1156         v3s32 speed(sf.X*100, sf.Y*100, sf.Z*100);
1157         /*
1158                 Format:
1159                 [0] v3s32 position*100
1160                 [12] v3s32 speed*100
1161                 [12+12] s32 pitch*100
1162                 [12+12+4] s32 yaw*100
1163                 [12+12+4+4] u32 keyPressed
1164         */
1165
1166         NetworkPacket pkt(TOSERVER_PLAYERPOS, 12 + 12 + 4 + 4 + 4);
1167
1168         pkt << position << speed << pitch << yaw << keyPressed;
1169
1170         Send(&pkt);
1171 }
1172
1173 void Client::sendPlayerItem(u16 item)
1174 {
1175         Player *myplayer = m_env.getLocalPlayer();
1176         if(myplayer == NULL)
1177                 return;
1178
1179         u16 our_peer_id = m_con.GetPeerID();
1180
1181         // Set peer id if not set already
1182         if(myplayer->peer_id == PEER_ID_INEXISTENT)
1183                 myplayer->peer_id = our_peer_id;
1184         assert(myplayer->peer_id == our_peer_id);
1185
1186         NetworkPacket pkt(TOSERVER_PLAYERITEM, 2);
1187
1188         pkt << item;
1189
1190         Send(&pkt);
1191 }
1192
1193 void Client::removeNode(v3s16 p)
1194 {
1195         std::map<v3s16, MapBlock*> modified_blocks;
1196
1197         try {
1198                 m_env.getMap().removeNodeAndUpdate(p, modified_blocks);
1199         }
1200         catch(InvalidPositionException &e) {
1201         }
1202
1203         for(std::map<v3s16, MapBlock *>::iterator
1204                         i = modified_blocks.begin();
1205                         i != modified_blocks.end(); ++i) {
1206                 addUpdateMeshTaskWithEdge(i->first, false, true);
1207         }
1208 }
1209
1210 void Client::addNode(v3s16 p, MapNode n, bool remove_metadata)
1211 {
1212         //TimeTaker timer1("Client::addNode()");
1213
1214         std::map<v3s16, MapBlock*> modified_blocks;
1215
1216         try {
1217                 //TimeTaker timer3("Client::addNode(): addNodeAndUpdate");
1218                 m_env.getMap().addNodeAndUpdate(p, n, modified_blocks, remove_metadata);
1219         }
1220         catch(InvalidPositionException &e) {
1221         }
1222
1223         for(std::map<v3s16, MapBlock *>::iterator
1224                         i = modified_blocks.begin();
1225                         i != modified_blocks.end(); ++i) {
1226                 addUpdateMeshTaskWithEdge(i->first, false, true);
1227         }
1228 }
1229
1230 void Client::setPlayerControl(PlayerControl &control)
1231 {
1232         LocalPlayer *player = m_env.getLocalPlayer();
1233         assert(player != NULL);
1234         player->control = control;
1235 }
1236
1237 void Client::selectPlayerItem(u16 item)
1238 {
1239         m_playeritem = item;
1240         m_inventory_updated = true;
1241         sendPlayerItem(item);
1242 }
1243
1244 // Returns true if the inventory of the local player has been
1245 // updated from the server. If it is true, it is set to false.
1246 bool Client::getLocalInventoryUpdated()
1247 {
1248         bool updated = m_inventory_updated;
1249         m_inventory_updated = false;
1250         return updated;
1251 }
1252
1253 // Copies the inventory of the local player to parameter
1254 void Client::getLocalInventory(Inventory &dst)
1255 {
1256         Player *player = m_env.getLocalPlayer();
1257         assert(player != NULL);
1258         dst = player->inventory;
1259 }
1260
1261 Inventory* Client::getInventory(const InventoryLocation &loc)
1262 {
1263         switch(loc.type){
1264         case InventoryLocation::UNDEFINED:
1265         {}
1266         break;
1267         case InventoryLocation::CURRENT_PLAYER:
1268         {
1269                 Player *player = m_env.getLocalPlayer();
1270                 assert(player != NULL);
1271                 return &player->inventory;
1272         }
1273         break;
1274         case InventoryLocation::PLAYER:
1275         {
1276                 Player *player = m_env.getPlayer(loc.name.c_str());
1277                 if(!player)
1278                         return NULL;
1279                 return &player->inventory;
1280         }
1281         break;
1282         case InventoryLocation::NODEMETA:
1283         {
1284                 NodeMetadata *meta = m_env.getMap().getNodeMetadata(loc.p);
1285                 if(!meta)
1286                         return NULL;
1287                 return meta->getInventory();
1288         }
1289         break;
1290         case InventoryLocation::DETACHED:
1291         {
1292                 if(m_detached_inventories.count(loc.name) == 0)
1293                         return NULL;
1294                 return m_detached_inventories[loc.name];
1295         }
1296         break;
1297         default:
1298                 FATAL_ERROR("Invalid inventory location type.");
1299                 break;
1300         }
1301         return NULL;
1302 }
1303
1304 void Client::inventoryAction(InventoryAction *a)
1305 {
1306         /*
1307                 Send it to the server
1308         */
1309         sendInventoryAction(a);
1310
1311         /*
1312                 Predict some local inventory changes
1313         */
1314         a->clientApply(this, this);
1315
1316         // Remove it
1317         delete a;
1318 }
1319
1320 ClientActiveObject * Client::getSelectedActiveObject(
1321                 f32 max_d,
1322                 v3f from_pos_f_on_map,
1323                 core::line3d<f32> shootline_on_map
1324         )
1325 {
1326         std::vector<DistanceSortedActiveObject> objects;
1327
1328         m_env.getActiveObjects(from_pos_f_on_map, max_d, objects);
1329
1330         // Sort them.
1331         // After this, the closest object is the first in the array.
1332         std::sort(objects.begin(), objects.end());
1333
1334         for(unsigned int i=0; i<objects.size(); i++)
1335         {
1336                 ClientActiveObject *obj = objects[i].obj;
1337
1338                 core::aabbox3d<f32> *selection_box = obj->getSelectionBox();
1339                 if(selection_box == NULL)
1340                         continue;
1341
1342                 v3f pos = obj->getPosition();
1343
1344                 core::aabbox3d<f32> offsetted_box(
1345                                 selection_box->MinEdge + pos,
1346                                 selection_box->MaxEdge + pos
1347                 );
1348
1349                 if(offsetted_box.intersectsWithLine(shootline_on_map))
1350                 {
1351                         return obj;
1352                 }
1353         }
1354
1355         return NULL;
1356 }
1357
1358 std::list<std::string> Client::getConnectedPlayerNames()
1359 {
1360         return m_env.getPlayerNames();
1361 }
1362
1363 float Client::getAnimationTime()
1364 {
1365         return m_animation_time;
1366 }
1367
1368 int Client::getCrackLevel()
1369 {
1370         return m_crack_level;
1371 }
1372
1373 void Client::setHighlighted(v3s16 pos, bool show_highlighted)
1374 {
1375         m_show_highlighted = show_highlighted;
1376         v3s16 old_highlighted_pos = m_highlighted_pos;
1377         m_highlighted_pos = pos;
1378         addUpdateMeshTaskForNode(old_highlighted_pos, false, true);
1379         addUpdateMeshTaskForNode(m_highlighted_pos, false, true);
1380 }
1381
1382 void Client::setCrack(int level, v3s16 pos)
1383 {
1384         int old_crack_level = m_crack_level;
1385         v3s16 old_crack_pos = m_crack_pos;
1386
1387         m_crack_level = level;
1388         m_crack_pos = pos;
1389
1390         if(old_crack_level >= 0 && (level < 0 || pos != old_crack_pos))
1391         {
1392                 // remove old crack
1393                 addUpdateMeshTaskForNode(old_crack_pos, false, true);
1394         }
1395         if(level >= 0 && (old_crack_level < 0 || pos != old_crack_pos))
1396         {
1397                 // add new crack
1398                 addUpdateMeshTaskForNode(pos, false, true);
1399         }
1400 }
1401
1402 u16 Client::getHP()
1403 {
1404         Player *player = m_env.getLocalPlayer();
1405         assert(player != NULL);
1406         return player->hp;
1407 }
1408
1409 u16 Client::getBreath()
1410 {
1411         Player *player = m_env.getLocalPlayer();
1412         assert(player != NULL);
1413         return player->getBreath();
1414 }
1415
1416 bool Client::getChatMessage(std::wstring &message)
1417 {
1418         if(m_chat_queue.size() == 0)
1419                 return false;
1420         message = m_chat_queue.front();
1421         m_chat_queue.pop();
1422         return true;
1423 }
1424
1425 void Client::typeChatMessage(const std::wstring &message)
1426 {
1427         // Discard empty line
1428         if(message == L"")
1429                 return;
1430
1431         // Send to others
1432         sendChatMessage(message);
1433
1434         // Show locally
1435         if (message[0] == L'/')
1436         {
1437                 m_chat_queue.push((std::wstring)L"issued command: " + message);
1438         }
1439         else
1440         {
1441                 LocalPlayer *player = m_env.getLocalPlayer();
1442                 assert(player != NULL);
1443                 std::wstring name = narrow_to_wide(player->getName());
1444                 m_chat_queue.push((std::wstring)L"<" + name + L"> " + message);
1445         }
1446 }
1447
1448 void Client::addUpdateMeshTask(v3s16 p, bool ack_to_server, bool urgent)
1449 {
1450         MapBlock *b = m_env.getMap().getBlockNoCreateNoEx(p);
1451         if(b == NULL)
1452                 return;
1453
1454         /*
1455                 Create a task to update the mesh of the block
1456         */
1457
1458         MeshMakeData *data = new MeshMakeData(this, m_cache_enable_shaders);
1459
1460         {
1461                 //TimeTaker timer("data fill");
1462                 // Release: ~0ms
1463                 // Debug: 1-6ms, avg=2ms
1464                 data->fill(b);
1465                 data->setCrack(m_crack_level, m_crack_pos);
1466                 data->setHighlighted(m_highlighted_pos, m_show_highlighted);
1467                 data->setSmoothLighting(m_cache_smooth_lighting);
1468         }
1469
1470         // Add task to queue
1471         m_mesh_update_thread.m_queue_in.addBlock(p, data, ack_to_server, urgent);
1472 }
1473
1474 void Client::addUpdateMeshTaskWithEdge(v3s16 blockpos, bool ack_to_server, bool urgent)
1475 {
1476         try{
1477                 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1478         }
1479         catch(InvalidPositionException &e){}
1480
1481         // Leading edge
1482         for (int i=0;i<6;i++)
1483         {
1484                 try{
1485                         v3s16 p = blockpos + g_6dirs[i];
1486                         addUpdateMeshTask(p, false, urgent);
1487                 }
1488                 catch(InvalidPositionException &e){}
1489         }
1490 }
1491
1492 void Client::addUpdateMeshTaskForNode(v3s16 nodepos, bool ack_to_server, bool urgent)
1493 {
1494         {
1495                 v3s16 p = nodepos;
1496                 infostream<<"Client::addUpdateMeshTaskForNode(): "
1497                                 <<"("<<p.X<<","<<p.Y<<","<<p.Z<<")"
1498                                 <<std::endl;
1499         }
1500
1501         v3s16 blockpos          = getNodeBlockPos(nodepos);
1502         v3s16 blockpos_relative = blockpos * MAP_BLOCKSIZE;
1503
1504         try{
1505                 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1506         }
1507         catch(InvalidPositionException &e) {}
1508
1509         // Leading edge
1510         if(nodepos.X == blockpos_relative.X){
1511                 try{
1512                         v3s16 p = blockpos + v3s16(-1,0,0);
1513                         addUpdateMeshTask(p, false, urgent);
1514                 }
1515                 catch(InvalidPositionException &e){}
1516         }
1517
1518         if(nodepos.Y == blockpos_relative.Y){
1519                 try{
1520                         v3s16 p = blockpos + v3s16(0,-1,0);
1521                         addUpdateMeshTask(p, false, urgent);
1522                 }
1523                 catch(InvalidPositionException &e){}
1524         }
1525
1526         if(nodepos.Z == blockpos_relative.Z){
1527                 try{
1528                         v3s16 p = blockpos + v3s16(0,0,-1);
1529                         addUpdateMeshTask(p, false, urgent);
1530                 }
1531                 catch(InvalidPositionException &e){}
1532         }
1533 }
1534
1535 ClientEvent Client::getClientEvent()
1536 {
1537         ClientEvent event;
1538         if(m_client_event_queue.size() == 0) {
1539                 event.type = CE_NONE;
1540         }
1541         else {
1542                 event = m_client_event_queue.front();
1543                 m_client_event_queue.pop();
1544         }
1545         return event;
1546 }
1547
1548 float Client::mediaReceiveProgress()
1549 {
1550         if (m_media_downloader)
1551                 return m_media_downloader->getProgress();
1552         else
1553                 return 1.0; // downloader only exists when not yet done
1554 }
1555
1556 typedef struct TextureUpdateArgs {
1557         IrrlichtDevice *device;
1558         gui::IGUIEnvironment *guienv;
1559         u32 last_time_ms;
1560         u16 last_percent;
1561         const wchar_t* text_base;
1562 } TextureUpdateArgs;
1563
1564 void texture_update_progress(void *args, u32 progress, u32 max_progress)
1565 {
1566                 TextureUpdateArgs* targs = (TextureUpdateArgs*) args;
1567                 u16 cur_percent = ceil(progress / (double) max_progress * 100.);
1568
1569                 // update the loading menu -- if neccessary
1570                 bool do_draw = false;
1571                 u32 time_ms = targs->last_time_ms;
1572                 if (cur_percent != targs->last_percent) {
1573                         targs->last_percent = cur_percent;
1574                         time_ms = getTimeMs();
1575                         // only draw when the user will notice something:
1576                         do_draw = (time_ms - targs->last_time_ms > 100);
1577                 }
1578
1579                 if (do_draw) {
1580                         targs->last_time_ms = time_ms;
1581                         std::basic_stringstream<wchar_t> strm;
1582                         strm << targs->text_base << " " << targs->last_percent << "%...";
1583                         draw_load_screen(strm.str(), targs->device, targs->guienv, 0,
1584                                 72 + (u16) ((18. / 100.) * (double) targs->last_percent));
1585                 }
1586 }
1587
1588 void Client::afterContentReceived(IrrlichtDevice *device)
1589 {
1590         infostream<<"Client::afterContentReceived() started"<<std::endl;
1591         assert(m_itemdef_received); // pre-condition
1592         assert(m_nodedef_received); // pre-condition
1593         assert(mediaReceived()); // pre-condition
1594
1595         const wchar_t* text = wgettext("Loading textures...");
1596
1597         // Rebuild inherited images and recreate textures
1598         infostream<<"- Rebuilding images and textures"<<std::endl;
1599         draw_load_screen(text,device, guienv, 0, 70);
1600         m_tsrc->rebuildImagesAndTextures();
1601         delete[] text;
1602
1603         // Rebuild shaders
1604         infostream<<"- Rebuilding shaders"<<std::endl;
1605         text = wgettext("Rebuilding shaders...");
1606         draw_load_screen(text, device, guienv, 0, 71);
1607         m_shsrc->rebuildShaders();
1608         delete[] text;
1609
1610         // Update node aliases
1611         infostream<<"- Updating node aliases"<<std::endl;
1612         text = wgettext("Initializing nodes...");
1613         draw_load_screen(text, device, guienv, 0, 72);
1614         m_nodedef->updateAliases(m_itemdef);
1615         m_nodedef->setNodeRegistrationStatus(true);
1616         m_nodedef->runNodeResolverCallbacks();
1617         delete[] text;
1618
1619         // Update node textures and assign shaders to each tile
1620         infostream<<"- Updating node textures"<<std::endl;
1621         TextureUpdateArgs tu_args;
1622         tu_args.device = device;
1623         tu_args.guienv = guienv;
1624         tu_args.last_time_ms = getTimeMs();
1625         tu_args.last_percent = 0;
1626         tu_args.text_base =  wgettext("Initializing nodes");
1627         m_nodedef->updateTextures(this, texture_update_progress, &tu_args);
1628         delete[] tu_args.text_base;
1629
1630         // Preload item textures and meshes if configured to
1631         if(g_settings->getBool("preload_item_visuals"))
1632         {
1633                 verbosestream<<"Updating item textures and meshes"<<std::endl;
1634                 text = wgettext("Item textures...");
1635                 draw_load_screen(text, device, guienv, 0, 0);
1636                 std::set<std::string> names = m_itemdef->getAll();
1637                 size_t size = names.size();
1638                 size_t count = 0;
1639                 int percent = 0;
1640                 for(std::set<std::string>::const_iterator
1641                                 i = names.begin(); i != names.end(); ++i)
1642                 {
1643                         // Asking for these caches the result
1644                         m_itemdef->getInventoryTexture(*i, this);
1645                         m_itemdef->getWieldMesh(*i, this);
1646                         count++;
1647                         percent = (count * 100 / size * 0.2) + 80;
1648                         draw_load_screen(text, device, guienv, 0, percent);
1649                 }
1650                 delete[] text;
1651         }
1652
1653         // Start mesh update thread after setting up content definitions
1654         infostream<<"- Starting mesh update thread"<<std::endl;
1655         m_mesh_update_thread.Start();
1656
1657         m_state = LC_Ready;
1658         sendReady();
1659         text = wgettext("Done!");
1660         draw_load_screen(text, device, guienv, 0, 100);
1661         infostream<<"Client::afterContentReceived() done"<<std::endl;
1662         delete[] text;
1663 }
1664
1665 float Client::getRTT(void)
1666 {
1667         return m_con.getPeerStat(PEER_ID_SERVER,con::AVG_RTT);
1668 }
1669
1670 float Client::getCurRate(void)
1671 {
1672         return ( m_con.getLocalStat(con::CUR_INC_RATE) +
1673                         m_con.getLocalStat(con::CUR_DL_RATE));
1674 }
1675
1676 float Client::getAvgRate(void)
1677 {
1678         return ( m_con.getLocalStat(con::AVG_INC_RATE) +
1679                         m_con.getLocalStat(con::AVG_DL_RATE));
1680 }
1681
1682 void Client::makeScreenshot(IrrlichtDevice *device)
1683 {
1684         irr::video::IVideoDriver *driver = device->getVideoDriver();
1685         irr::video::IImage* const raw_image = driver->createScreenShot();
1686         if (raw_image) {
1687                 irr::video::IImage* const image = driver->createImage(video::ECF_R8G8B8,
1688                         raw_image->getDimension());
1689
1690                 if (image) {
1691                         raw_image->copyTo(image);
1692                         irr::c8 filename[256];
1693                         snprintf(filename, sizeof(filename),
1694                                 (std::string("%s") + DIR_DELIM + "screenshot_%u.png").c_str(),
1695                                  g_settings->get("screenshot_path").c_str(),
1696                                  device->getTimer()->getRealTime());
1697                         std::ostringstream sstr;
1698                         if (driver->writeImageToFile(image, filename)) {
1699                                 sstr << "Saved screenshot to '" << filename << "'";
1700                         } else {
1701                                 sstr << "Failed to save screenshot '" << filename << "'";
1702                         }
1703                         m_chat_queue.push(narrow_to_wide(sstr.str()));
1704                         infostream << sstr.str() << std::endl;
1705                         image->drop();
1706                 }
1707                 raw_image->drop();
1708         }
1709 }
1710
1711 // IGameDef interface
1712 // Under envlock
1713 IItemDefManager* Client::getItemDefManager()
1714 {
1715         return m_itemdef;
1716 }
1717 INodeDefManager* Client::getNodeDefManager()
1718 {
1719         return m_nodedef;
1720 }
1721 ICraftDefManager* Client::getCraftDefManager()
1722 {
1723         return NULL;
1724         //return m_craftdef;
1725 }
1726 ITextureSource* Client::getTextureSource()
1727 {
1728         return m_tsrc;
1729 }
1730 IShaderSource* Client::getShaderSource()
1731 {
1732         return m_shsrc;
1733 }
1734 scene::ISceneManager* Client::getSceneManager()
1735 {
1736         return m_device->getSceneManager();
1737 }
1738 u16 Client::allocateUnknownNodeId(const std::string &name)
1739 {
1740         errorstream << "Client::allocateUnknownNodeId(): "
1741                         << "Client cannot allocate node IDs" << std::endl;
1742         FATAL_ERROR("Client allocated unknown node");
1743
1744         return CONTENT_IGNORE;
1745 }
1746 ISoundManager* Client::getSoundManager()
1747 {
1748         return m_sound;
1749 }
1750 MtEventManager* Client::getEventManager()
1751 {
1752         return m_event;
1753 }
1754
1755 ParticleManager* Client::getParticleManager()
1756 {
1757         return &m_particle_manager;
1758 }
1759
1760 scene::IAnimatedMesh* Client::getMesh(const std::string &filename)
1761 {
1762         std::map<std::string, std::string>::const_iterator i =
1763                         m_mesh_data.find(filename);
1764         if(i == m_mesh_data.end()){
1765                 errorstream<<"Client::getMesh(): Mesh not found: \""<<filename<<"\""
1766                                 <<std::endl;
1767                 return NULL;
1768         }
1769         const std::string &data    = i->second;
1770         scene::ISceneManager *smgr = m_device->getSceneManager();
1771
1772         // Create the mesh, remove it from cache and return it
1773         // This allows unique vertex colors and other properties for each instance
1774         Buffer<char> data_rw(data.c_str(), data.size()); // Const-incorrect Irrlicht
1775         io::IFileSystem *irrfs = m_device->getFileSystem();
1776         io::IReadFile *rfile   = irrfs->createMemoryReadFile(
1777                         *data_rw, data_rw.getSize(), filename.c_str());
1778         FATAL_ERROR_IF(!rfile, "Could not create/open RAM file");
1779
1780         scene::IAnimatedMesh *mesh = smgr->getMesh(rfile);
1781         rfile->drop();
1782         // NOTE: By playing with Irrlicht refcounts, maybe we could cache a bunch
1783         // of uniquely named instances and re-use them
1784         mesh->grab();
1785         smgr->getMeshCache()->removeMesh(mesh);
1786         return mesh;
1787 }