For usages of assert() that are meant to persist in Release builds (when NDEBUG is...
[oweals/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
405                         snprintf(pName, PLAYERNAME_SIZE, "%s", myplayer->getName());
406                         snprintf(pPassword, PASSWORD_SIZE, "%s", m_password.c_str());
407
408                         NetworkPacket* pkt = new NetworkPacket(TOSERVER_INIT,
409                                         1 + PLAYERNAME_SIZE + PASSWORD_SIZE + 2 + 2);
410
411                         *pkt << (u8) SER_FMT_VER_HIGHEST_READ;
412                         pkt->putRawString(pName,PLAYERNAME_SIZE);
413                         pkt->putRawString(pPassword, PASSWORD_SIZE);
414                         *pkt << (u16) CLIENT_PROTOCOL_VERSION_MIN << (u16) CLIENT_PROTOCOL_VERSION_MAX;
415
416                         Send(pkt);
417                 }
418
419                 // Not connected, return
420                 return;
421         }
422
423         /*
424                 Do stuff if connected
425         */
426
427         /*
428                 Run Map's timers and unload unused data
429         */
430         const float map_timer_and_unload_dtime = 5.25;
431         if(m_map_timer_and_unload_interval.step(dtime, map_timer_and_unload_dtime)) {
432                 ScopeProfiler sp(g_profiler, "Client: map timer and unload");
433                 std::vector<v3s16> deleted_blocks;
434                 m_env.getMap().timerUpdate(map_timer_and_unload_dtime,
435                                 g_settings->getFloat("client_unload_unused_data_timeout"),
436                                 &deleted_blocks);
437
438                 /*
439                         Send info to server
440                         NOTE: This loop is intentionally iterated the way it is.
441                 */
442
443                 std::vector<v3s16>::iterator i = deleted_blocks.begin();
444                 std::vector<v3s16> sendlist;
445                 for(;;) {
446                         if(sendlist.size() == 255 || i == deleted_blocks.end()) {
447                                 if(sendlist.empty())
448                                         break;
449                                 /*
450                                         [0] u16 command
451                                         [2] u8 count
452                                         [3] v3s16 pos_0
453                                         [3+6] v3s16 pos_1
454                                         ...
455                                 */
456                                 NetworkPacket* pkt = new NetworkPacket(TOSERVER_DELETEDBLOCKS, 1 + sizeof(v3s16) * sendlist.size());
457
458                                 *pkt << (u8) sendlist.size();
459
460                                 u32 k = 0;
461                                 for(std::vector<v3s16>::iterator
462                                                 j = sendlist.begin();
463                                                 j != sendlist.end(); ++j) {
464                                         *pkt << *j;
465                                         k++;
466                                 }
467
468                                 Send(pkt);
469
470                                 if(i == deleted_blocks.end())
471                                         break;
472
473                                 sendlist.clear();
474                         }
475
476                         sendlist.push_back(*i);
477                         ++i;
478                 }
479         }
480
481         /*
482                 Handle environment
483         */
484         // Control local player (0ms)
485         LocalPlayer *player = m_env.getLocalPlayer();
486         assert(player != NULL);
487         player->applyControl(dtime);
488
489         // Step environment
490         m_env.step(dtime);
491
492         /*
493                 Get events
494         */
495         for(;;) {
496                 ClientEnvEvent event = m_env.getClientEvent();
497                 if(event.type == CEE_NONE) {
498                         break;
499                 }
500                 else if(event.type == CEE_PLAYER_DAMAGE) {
501                         if(m_ignore_damage_timer <= 0) {
502                                 u8 damage = event.player_damage.amount;
503
504                                 if(event.player_damage.send_to_server)
505                                         sendDamage(damage);
506
507                                 // Add to ClientEvent queue
508                                 ClientEvent event;
509                                 event.type = CE_PLAYER_DAMAGE;
510                                 event.player_damage.amount = damage;
511                                 m_client_event_queue.push(event);
512                         }
513                 }
514                 else if(event.type == CEE_PLAYER_BREATH) {
515                                 u16 breath = event.player_breath.amount;
516                                 sendBreath(breath);
517                 }
518         }
519
520         /*
521                 Print some info
522         */
523         float &counter = m_avg_rtt_timer;
524         counter += dtime;
525         if(counter >= 10) {
526                 counter = 0.0;
527                 // connectedAndInitialized() is true, peer exists.
528                 float avg_rtt = getRTT();
529                 infostream << "Client: avg_rtt=" << avg_rtt << std::endl;
530         }
531
532         /*
533                 Send player position to server
534         */
535         {
536                 float &counter = m_playerpos_send_timer;
537                 counter += dtime;
538                 if((m_state == LC_Ready) && (counter >= m_recommended_send_interval))
539                 {
540                         counter = 0.0;
541                         sendPlayerPos();
542                 }
543         }
544
545         /*
546                 Replace updated meshes
547         */
548         {
549                 int num_processed_meshes = 0;
550                 while(!m_mesh_update_thread.m_queue_out.empty())
551                 {
552                         num_processed_meshes++;
553                         MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_frontNoEx();
554                         MapBlock *block = m_env.getMap().getBlockNoCreateNoEx(r.p);
555                         if(block) {
556                                 // Delete the old mesh
557                                 if(block->mesh != NULL)
558                                 {
559                                         // TODO: Remove hardware buffers of meshbuffers of block->mesh
560                                         delete block->mesh;
561                                         block->mesh = NULL;
562                                 }
563
564                                 // Replace with the new mesh
565                                 block->mesh = r.mesh;
566                         } else {
567                                 delete r.mesh;
568                         }
569
570                         if(r.ack_block_to_server) {
571                                 /*
572                                         Acknowledge block
573                                         [0] u8 count
574                                         [1] v3s16 pos_0
575                                 */
576                                 NetworkPacket* pkt = new NetworkPacket(TOSERVER_GOTBLOCKS, 1 + 6);
577                                 *pkt << (u8) 1 << r.p;
578                                 Send(pkt);
579                         }
580                 }
581
582                 if(num_processed_meshes > 0)
583                         g_profiler->graphAdd("num_processed_meshes", num_processed_meshes);
584         }
585
586         /*
587                 Load fetched media
588         */
589         if (m_media_downloader && m_media_downloader->isStarted()) {
590                 m_media_downloader->step(this);
591                 if (m_media_downloader->isDone()) {
592                         received_media();
593                         delete m_media_downloader;
594                         m_media_downloader = NULL;
595                 }
596         }
597
598         /*
599                 If the server didn't update the inventory in a while, revert
600                 the local inventory (so the player notices the lag problem
601                 and knows something is wrong).
602         */
603         if(m_inventory_from_server)
604         {
605                 float interval = 10.0;
606                 float count_before = floor(m_inventory_from_server_age / interval);
607
608                 m_inventory_from_server_age += dtime;
609
610                 float count_after = floor(m_inventory_from_server_age / interval);
611
612                 if(count_after != count_before)
613                 {
614                         // Do this every <interval> seconds after TOCLIENT_INVENTORY
615                         // Reset the locally changed inventory to the authoritative inventory
616                         Player *player = m_env.getLocalPlayer();
617                         player->inventory = *m_inventory_from_server;
618                         m_inventory_updated = true;
619                 }
620         }
621
622         /*
623                 Update positions of sounds attached to objects
624         */
625         {
626                 for(std::map<int, u16>::iterator
627                                 i = m_sounds_to_objects.begin();
628                                 i != m_sounds_to_objects.end(); i++)
629                 {
630                         int client_id = i->first;
631                         u16 object_id = i->second;
632                         ClientActiveObject *cao = m_env.getActiveObject(object_id);
633                         if(!cao)
634                                 continue;
635                         v3f pos = cao->getPosition();
636                         m_sound->updateSoundPosition(client_id, pos);
637                 }
638         }
639
640         /*
641                 Handle removed remotely initiated sounds
642         */
643         m_removed_sounds_check_timer += dtime;
644         if(m_removed_sounds_check_timer >= 2.32) {
645                 m_removed_sounds_check_timer = 0;
646                 // Find removed sounds and clear references to them
647                 std::set<s32> removed_server_ids;
648                 for(std::map<s32, int>::iterator
649                                 i = m_sounds_server_to_client.begin();
650                                 i != m_sounds_server_to_client.end();) {
651                         s32 server_id = i->first;
652                         int client_id = i->second;
653                         i++;
654                         if(!m_sound->soundExists(client_id)) {
655                                 m_sounds_server_to_client.erase(server_id);
656                                 m_sounds_client_to_server.erase(client_id);
657                                 m_sounds_to_objects.erase(client_id);
658                                 removed_server_ids.insert(server_id);
659                         }
660                 }
661
662                 // Sync to server
663                 if(!removed_server_ids.empty()) {
664                         size_t server_ids = removed_server_ids.size();
665                         assert(server_ids <= 0xFFFF);
666
667                         NetworkPacket* pkt = new NetworkPacket(TOSERVER_REMOVED_SOUNDS, 2 + server_ids * 4);
668
669                         *pkt << (u16) (server_ids & 0xFFFF);
670
671                         for(std::set<s32>::iterator i = removed_server_ids.begin();
672                                         i != removed_server_ids.end(); i++)
673                                 *pkt << *i;
674
675                         Send(pkt);
676                 }
677         }
678
679         // Write server map
680         if (m_localdb && m_localdb_save_interval.step(dtime,
681                         m_cache_save_interval)) {
682                 m_localdb->endSave();
683                 m_localdb->beginSave();
684         }
685 }
686
687 bool Client::loadMedia(const std::string &data, const std::string &filename)
688 {
689         // Silly irrlicht's const-incorrectness
690         Buffer<char> data_rw(data.c_str(), data.size());
691
692         std::string name;
693
694         const char *image_ext[] = {
695                 ".png", ".jpg", ".bmp", ".tga",
696                 ".pcx", ".ppm", ".psd", ".wal", ".rgb",
697                 NULL
698         };
699         name = removeStringEnd(filename, image_ext);
700         if(name != "")
701         {
702                 verbosestream<<"Client: Attempting to load image "
703                 <<"file \""<<filename<<"\""<<std::endl;
704
705                 io::IFileSystem *irrfs = m_device->getFileSystem();
706                 video::IVideoDriver *vdrv = m_device->getVideoDriver();
707
708                 // Create an irrlicht memory file
709                 io::IReadFile *rfile = irrfs->createMemoryReadFile(
710                                 *data_rw, data_rw.getSize(), "_tempreadfile");
711
712                 FATAL_ERROR_IF(!rfile, "Could not create irrlicht memory file.");
713
714                 // Read image
715                 video::IImage *img = vdrv->createImageFromFile(rfile);
716                 if(!img){
717                         errorstream<<"Client: Cannot create image from data of "
718                                         <<"file \""<<filename<<"\""<<std::endl;
719                         rfile->drop();
720                         return false;
721                 }
722                 else {
723                         m_tsrc->insertSourceImage(filename, img);
724                         img->drop();
725                         rfile->drop();
726                         return true;
727                 }
728         }
729
730         const char *sound_ext[] = {
731                 ".0.ogg", ".1.ogg", ".2.ogg", ".3.ogg", ".4.ogg",
732                 ".5.ogg", ".6.ogg", ".7.ogg", ".8.ogg", ".9.ogg",
733                 ".ogg", NULL
734         };
735         name = removeStringEnd(filename, sound_ext);
736         if(name != "")
737         {
738                 verbosestream<<"Client: Attempting to load sound "
739                 <<"file \""<<filename<<"\""<<std::endl;
740                 m_sound->loadSoundData(name, data);
741                 return true;
742         }
743
744         const char *model_ext[] = {
745                 ".x", ".b3d", ".md2", ".obj",
746                 NULL
747         };
748         name = removeStringEnd(filename, model_ext);
749         if(name != "")
750         {
751                 verbosestream<<"Client: Storing model into memory: "
752                                 <<"\""<<filename<<"\""<<std::endl;
753                 if(m_mesh_data.count(filename))
754                         errorstream<<"Multiple models with name \""<<filename.c_str()
755                                         <<"\" found; replacing previous model"<<std::endl;
756                 m_mesh_data[filename] = data;
757                 return true;
758         }
759
760         errorstream<<"Client: Don't know how to load file \""
761                         <<filename<<"\""<<std::endl;
762         return false;
763 }
764
765 // Virtual methods from con::PeerHandler
766 void Client::peerAdded(con::Peer *peer)
767 {
768         infostream<<"Client::peerAdded(): peer->id="
769                         <<peer->id<<std::endl;
770 }
771 void Client::deletingPeer(con::Peer *peer, bool timeout)
772 {
773         infostream<<"Client::deletingPeer(): "
774                         "Server Peer is getting deleted "
775                         <<"(timeout="<<timeout<<")"<<std::endl;
776 }
777
778 /*
779         u16 command
780         u16 number of files requested
781         for each file {
782                 u16 length of name
783                 string name
784         }
785 */
786 void Client::request_media(const std::vector<std::string> &file_requests)
787 {
788         std::ostringstream os(std::ios_base::binary);
789         writeU16(os, TOSERVER_REQUEST_MEDIA);
790         size_t file_requests_size = file_requests.size();
791
792         FATAL_ERROR_IF(file_requests_size > 0xFFFF, "Unsupported number of file requests");
793
794         // Packet dynamicly resized
795         NetworkPacket* pkt = new NetworkPacket(TOSERVER_REQUEST_MEDIA, 2 + 0);
796
797         *pkt << (u16) (file_requests_size & 0xFFFF);
798
799         for(std::vector<std::string>::const_iterator i = file_requests.begin();
800                         i != file_requests.end(); ++i) {
801                 *pkt << (*i);
802         }
803
804         Send(pkt);
805
806         infostream<<"Client: Sending media request list to server ("
807                         <<file_requests.size()<<" files. packet size)"<<std::endl;
808 }
809
810 void Client::received_media()
811 {
812         NetworkPacket* pkt = new NetworkPacket(TOSERVER_RECEIVED_MEDIA, 0);
813         Send(pkt);
814         infostream<<"Client: Notifying server that we received all media"
815                         <<std::endl;
816 }
817
818 void Client::initLocalMapSaving(const Address &address,
819                 const std::string &hostname,
820                 bool is_local_server)
821 {
822         if (!g_settings->getBool("enable_local_map_saving") || is_local_server) {
823                 return;
824         }
825
826         const std::string world_path = porting::path_user
827                 + DIR_DELIM + "worlds"
828                 + DIR_DELIM + "server_"
829                 + hostname + "_" + to_string(address.getPort());
830
831         fs::CreateAllDirs(world_path);
832
833         m_localdb = new Database_SQLite3(world_path);
834         m_localdb->beginSave();
835         actionstream << "Local map saving started, map will be saved at '" << world_path << "'" << std::endl;
836 }
837
838 void Client::ReceiveAll()
839 {
840         DSTACK(__FUNCTION_NAME);
841         u32 start_ms = porting::getTimeMs();
842         for(;;)
843         {
844                 // Limit time even if there would be huge amounts of data to
845                 // process
846                 if(porting::getTimeMs() > start_ms + 100)
847                         break;
848
849                 try {
850                         Receive();
851                         g_profiler->graphAdd("client_received_packets", 1);
852                 }
853                 catch(con::NoIncomingDataException &e) {
854                         break;
855                 }
856                 catch(con::InvalidIncomingDataException &e) {
857                         infostream<<"Client::ReceiveAll(): "
858                                         "InvalidIncomingDataException: what()="
859                                         <<e.what()<<std::endl;
860                 }
861         }
862 }
863
864 void Client::Receive()
865 {
866         DSTACK(__FUNCTION_NAME);
867         SharedBuffer<u8> data;
868         u16 sender_peer_id;
869         u32 datasize = m_con.Receive(sender_peer_id, data);
870         ProcessData(*data, datasize, sender_peer_id);
871 }
872
873 inline void Client::handleCommand(NetworkPacket* pkt)
874 {
875         const ToClientCommandHandler& opHandle = toClientCommandTable[pkt->getCommand()];
876         (this->*opHandle.handler)(pkt);
877 }
878
879 /*
880         sender_peer_id given to this shall be quaranteed to be a valid peer
881 */
882 void Client::ProcessData(u8 *data, u32 datasize, u16 sender_peer_id)
883 {
884         DSTACK(__FUNCTION_NAME);
885
886         // Ignore packets that don't even fit a command
887         if(datasize < 2) {
888                 m_packetcounter.add(60000);
889                 return;
890         }
891
892         NetworkPacket* pkt = new NetworkPacket(data, datasize, sender_peer_id);
893
894         ToClientCommand command = (ToClientCommand) pkt->getCommand();
895
896         //infostream<<"Client: received command="<<command<<std::endl;
897         m_packetcounter.add((u16)command);
898
899         /*
900                 If this check is removed, be sure to change the queue
901                 system to know the ids
902         */
903         if(sender_peer_id != PEER_ID_SERVER) {
904                 infostream << "Client::ProcessData(): Discarding data not "
905                         "coming from server: peer_id=" << sender_peer_id
906                         << std::endl;
907                 delete pkt;
908                 return;
909         }
910
911         // Command must be handled into ToClientCommandHandler
912         if (command >= TOCLIENT_NUM_MSG_TYPES) {
913                 infostream << "Client: Ignoring unknown command "
914                         << command << std::endl;
915         }
916
917         /*
918          * Those packets are handled before m_server_ser_ver is set, it's normal
919          * But we must use the new ToClientConnectionState in the future,
920          * as a byte mask
921          */
922         if(toClientCommandTable[command].state == TOCLIENT_STATE_NOT_CONNECTED) {
923                 handleCommand(pkt);
924                 delete 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                 delete pkt;
933                 return;
934         }
935
936         /*
937           Handle runtime commands
938         */
939
940         handleCommand(pkt);
941         delete pkt;
942 }
943
944 void Client::Send(NetworkPacket* pkt)
945 {
946         m_con.Send(PEER_ID_SERVER,
947                 serverCommandFactoryTable[pkt->getCommand()].channel,
948                 pkt,
949                 serverCommandFactoryTable[pkt->getCommand()].reliable);
950         delete pkt;
951 }
952
953 void Client::interact(u8 action, const PointedThing& pointed)
954 {
955         if(m_state != LC_Ready) {
956                 errorstream << "Client::interact() "
957                                 "cancelled (not connected)"
958                                 << std::endl;
959                 return;
960         }
961
962         /*
963                 [0] u16 command
964                 [2] u8 action
965                 [3] u16 item
966                 [5] u32 length of the next item
967                 [9] serialized PointedThing
968                 actions:
969                 0: start digging (from undersurface) or use
970                 1: stop digging (all parameters ignored)
971                 2: digging completed
972                 3: place block or item (to abovesurface)
973                 4: use item
974         */
975
976         NetworkPacket* pkt = new NetworkPacket(TOSERVER_INTERACT, 1 + 2 + 0);
977
978         *pkt << action;
979         *pkt << (u16)getPlayerItem();
980
981         std::ostringstream tmp_os(std::ios::binary);
982         pointed.serialize(tmp_os);
983
984         pkt->putLongString(tmp_os.str());
985
986         Send(pkt);
987 }
988
989 void Client::sendNodemetaFields(v3s16 p, const std::string &formname,
990                 const std::map<std::string, std::string> &fields)
991 {
992         size_t fields_size = fields.size();
993
994         FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of nodemeta fields");
995
996         NetworkPacket* pkt = new NetworkPacket(TOSERVER_NODEMETA_FIELDS, 0);
997
998         *pkt << p << formname << (u16) (fields_size & 0xFFFF);
999
1000         for(std::map<std::string, std::string>::const_iterator
1001                         i = fields.begin(); i != fields.end(); i++) {
1002                 const std::string &name = i->first;
1003                 const std::string &value = i->second;
1004                 *pkt << name;
1005                 pkt->putLongString(value);
1006         }
1007
1008         Send(pkt);
1009 }
1010
1011 void Client::sendInventoryFields(const std::string &formname,
1012                 const std::map<std::string, std::string> &fields)
1013 {
1014         size_t fields_size = fields.size();
1015         FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of inventory fields");
1016
1017         NetworkPacket* pkt = new NetworkPacket(TOSERVER_INVENTORY_FIELDS, 0);
1018         *pkt << formname << (u16) (fields_size & 0xFFFF);
1019
1020         for(std::map<std::string, std::string>::const_iterator
1021                         i = fields.begin(); i != fields.end(); i++) {
1022                 const std::string &name  = i->first;
1023                 const std::string &value = i->second;
1024                 *pkt << name;
1025                 pkt->putLongString(value);
1026         }
1027
1028         Send(pkt);
1029 }
1030
1031 void Client::sendInventoryAction(InventoryAction *a)
1032 {
1033         std::ostringstream os(std::ios_base::binary);
1034
1035         a->serialize(os);
1036
1037         // Make data buffer
1038         std::string s = os.str();
1039
1040         NetworkPacket* pkt = new NetworkPacket(TOSERVER_INVENTORY_ACTION, s.size());
1041         pkt->putRawString(s.c_str(),s.size());
1042
1043         Send(pkt);
1044 }
1045
1046 void Client::sendChatMessage(const std::wstring &message)
1047 {
1048         NetworkPacket* pkt = new NetworkPacket(TOSERVER_CHAT_MESSAGE, 2 + message.size() * sizeof(u16));
1049
1050         *pkt << message;
1051
1052         Send(pkt);
1053 }
1054
1055 void Client::sendChangePassword(const std::wstring &oldpassword,
1056         const std::wstring &newpassword)
1057 {
1058         Player *player = m_env.getLocalPlayer();
1059         if(player == NULL)
1060                 return;
1061
1062         std::string playername = player->getName();
1063         std::string oldpwd = translatePassword(playername, oldpassword);
1064         std::string newpwd = translatePassword(playername, newpassword);
1065
1066         NetworkPacket* pkt = new NetworkPacket(TOSERVER_PASSWORD, 2 * PASSWORD_SIZE);
1067
1068         for(u8 i = 0; i < PASSWORD_SIZE; i++) {
1069                 *pkt << (u8) (i < oldpwd.length() ? oldpwd[i] : 0);
1070         }
1071
1072         for(u8 i = 0; i < PASSWORD_SIZE; i++) {
1073                 *pkt << (u8) (i < newpwd.length() ? newpwd[i] : 0);
1074         }
1075
1076         Send(pkt);
1077 }
1078
1079
1080 void Client::sendDamage(u8 damage)
1081 {
1082         DSTACK(__FUNCTION_NAME);
1083
1084         NetworkPacket* pkt = new NetworkPacket(TOSERVER_DAMAGE, sizeof(u8));
1085         *pkt << damage;
1086         Send(pkt);
1087 }
1088
1089 void Client::sendBreath(u16 breath)
1090 {
1091         DSTACK(__FUNCTION_NAME);
1092
1093         NetworkPacket* pkt = new NetworkPacket(TOSERVER_BREATH, sizeof(u16));
1094         *pkt << breath;
1095         Send(pkt);
1096 }
1097
1098 void Client::sendRespawn()
1099 {
1100         DSTACK(__FUNCTION_NAME);
1101
1102         NetworkPacket* pkt = new NetworkPacket(TOSERVER_RESPAWN, 0);
1103         Send(pkt);
1104 }
1105
1106 void Client::sendReady()
1107 {
1108         DSTACK(__FUNCTION_NAME);
1109
1110         NetworkPacket* pkt = new NetworkPacket(TOSERVER_CLIENT_READY,
1111                         1 + 1 + 1 + 1 + 2 + sizeof(char) * strlen(minetest_version_hash));
1112
1113         *pkt << (u8) VERSION_MAJOR << (u8) VERSION_MINOR << (u8) VERSION_PATCH_ORIG
1114                 << (u8) 0 << (u16) strlen(minetest_version_hash);
1115
1116         pkt->putRawString(minetest_version_hash, (u16) strlen(minetest_version_hash));
1117         Send(pkt);
1118 }
1119
1120 void Client::sendPlayerPos()
1121 {
1122         LocalPlayer *myplayer = m_env.getLocalPlayer();
1123         if(myplayer == NULL)
1124                 return;
1125
1126         // Save bandwidth by only updating position when something changed
1127         if(myplayer->last_position        == myplayer->getPosition() &&
1128                         myplayer->last_speed      == myplayer->getSpeed()    &&
1129                         myplayer->last_pitch      == myplayer->getPitch()    &&
1130                         myplayer->last_yaw        == myplayer->getYaw()      &&
1131                         myplayer->last_keyPressed == myplayer->keyPressed)
1132                 return;
1133
1134         myplayer->last_position   = myplayer->getPosition();
1135         myplayer->last_speed      = myplayer->getSpeed();
1136         myplayer->last_pitch      = myplayer->getPitch();
1137         myplayer->last_yaw        = myplayer->getYaw();
1138         myplayer->last_keyPressed = myplayer->keyPressed;
1139
1140         u16 our_peer_id;
1141         {
1142                 //JMutexAutoLock lock(m_con_mutex); //bulk comment-out
1143                 our_peer_id = m_con.GetPeerID();
1144         }
1145
1146         // Set peer id if not set already
1147         if(myplayer->peer_id == PEER_ID_INEXISTENT)
1148                 myplayer->peer_id = our_peer_id;
1149
1150         assert(myplayer->peer_id == our_peer_id);
1151
1152         v3f pf         = myplayer->getPosition();
1153         v3f sf         = myplayer->getSpeed();
1154         s32 pitch      = myplayer->getPitch() * 100;
1155         s32 yaw        = myplayer->getYaw() * 100;
1156         u32 keyPressed = myplayer->keyPressed;
1157
1158         v3s32 position(pf.X*100, pf.Y*100, pf.Z*100);
1159         v3s32 speed(sf.X*100, sf.Y*100, sf.Z*100);
1160         /*
1161                 Format:
1162                 [0] v3s32 position*100
1163                 [12] v3s32 speed*100
1164                 [12+12] s32 pitch*100
1165                 [12+12+4] s32 yaw*100
1166                 [12+12+4+4] u32 keyPressed
1167         */
1168
1169         NetworkPacket* pkt = new NetworkPacket(TOSERVER_PLAYERPOS, 12 + 12 + 4 + 4 + 4);
1170
1171         *pkt << position << speed << pitch << yaw << keyPressed;
1172
1173         Send(pkt);
1174 }
1175
1176 void Client::sendPlayerItem(u16 item)
1177 {
1178         Player *myplayer = m_env.getLocalPlayer();
1179         if(myplayer == NULL)
1180                 return;
1181
1182         u16 our_peer_id = m_con.GetPeerID();
1183
1184         // Set peer id if not set already
1185         if(myplayer->peer_id == PEER_ID_INEXISTENT)
1186                 myplayer->peer_id = our_peer_id;
1187         assert(myplayer->peer_id == our_peer_id);
1188
1189         NetworkPacket* pkt = new NetworkPacket(TOSERVER_PLAYERITEM, 2);
1190
1191         *pkt << item;
1192
1193         Send(pkt);
1194 }
1195
1196 void Client::removeNode(v3s16 p)
1197 {
1198         std::map<v3s16, MapBlock*> modified_blocks;
1199
1200         try {
1201                 m_env.getMap().removeNodeAndUpdate(p, modified_blocks);
1202         }
1203         catch(InvalidPositionException &e) {
1204         }
1205
1206         for(std::map<v3s16, MapBlock *>::iterator
1207                         i = modified_blocks.begin();
1208                         i != modified_blocks.end(); ++i) {
1209                 addUpdateMeshTaskWithEdge(i->first, false, true);
1210         }
1211 }
1212
1213 void Client::addNode(v3s16 p, MapNode n, bool remove_metadata)
1214 {
1215         //TimeTaker timer1("Client::addNode()");
1216
1217         std::map<v3s16, MapBlock*> modified_blocks;
1218
1219         try {
1220                 //TimeTaker timer3("Client::addNode(): addNodeAndUpdate");
1221                 m_env.getMap().addNodeAndUpdate(p, n, modified_blocks, remove_metadata);
1222         }
1223         catch(InvalidPositionException &e) {
1224         }
1225
1226         for(std::map<v3s16, MapBlock *>::iterator
1227                         i = modified_blocks.begin();
1228                         i != modified_blocks.end(); ++i) {
1229                 addUpdateMeshTaskWithEdge(i->first, false, true);
1230         }
1231 }
1232
1233 void Client::setPlayerControl(PlayerControl &control)
1234 {
1235         LocalPlayer *player = m_env.getLocalPlayer();
1236         assert(player != NULL);
1237         player->control = control;
1238 }
1239
1240 void Client::selectPlayerItem(u16 item)
1241 {
1242         m_playeritem = item;
1243         m_inventory_updated = true;
1244         sendPlayerItem(item);
1245 }
1246
1247 // Returns true if the inventory of the local player has been
1248 // updated from the server. If it is true, it is set to false.
1249 bool Client::getLocalInventoryUpdated()
1250 {
1251         bool updated = m_inventory_updated;
1252         m_inventory_updated = false;
1253         return updated;
1254 }
1255
1256 // Copies the inventory of the local player to parameter
1257 void Client::getLocalInventory(Inventory &dst)
1258 {
1259         Player *player = m_env.getLocalPlayer();
1260         assert(player != NULL);
1261         dst = player->inventory;
1262 }
1263
1264 Inventory* Client::getInventory(const InventoryLocation &loc)
1265 {
1266         switch(loc.type){
1267         case InventoryLocation::UNDEFINED:
1268         {}
1269         break;
1270         case InventoryLocation::CURRENT_PLAYER:
1271         {
1272                 Player *player = m_env.getLocalPlayer();
1273                 assert(player != NULL);
1274                 return &player->inventory;
1275         }
1276         break;
1277         case InventoryLocation::PLAYER:
1278         {
1279                 Player *player = m_env.getPlayer(loc.name.c_str());
1280                 if(!player)
1281                         return NULL;
1282                 return &player->inventory;
1283         }
1284         break;
1285         case InventoryLocation::NODEMETA:
1286         {
1287                 NodeMetadata *meta = m_env.getMap().getNodeMetadata(loc.p);
1288                 if(!meta)
1289                         return NULL;
1290                 return meta->getInventory();
1291         }
1292         break;
1293         case InventoryLocation::DETACHED:
1294         {
1295                 if(m_detached_inventories.count(loc.name) == 0)
1296                         return NULL;
1297                 return m_detached_inventories[loc.name];
1298         }
1299         break;
1300         default:
1301                 FATAL_ERROR("Invalid inventory location type.");
1302         }
1303         return NULL;
1304 }
1305
1306 void Client::inventoryAction(InventoryAction *a)
1307 {
1308         /*
1309                 Send it to the server
1310         */
1311         sendInventoryAction(a);
1312
1313         /*
1314                 Predict some local inventory changes
1315         */
1316         a->clientApply(this, this);
1317
1318         // Remove it
1319         delete a;
1320 }
1321
1322 ClientActiveObject * Client::getSelectedActiveObject(
1323                 f32 max_d,
1324                 v3f from_pos_f_on_map,
1325                 core::line3d<f32> shootline_on_map
1326         )
1327 {
1328         std::vector<DistanceSortedActiveObject> objects;
1329
1330         m_env.getActiveObjects(from_pos_f_on_map, max_d, objects);
1331
1332         // Sort them.
1333         // After this, the closest object is the first in the array.
1334         std::sort(objects.begin(), objects.end());
1335
1336         for(unsigned int i=0; i<objects.size(); i++)
1337         {
1338                 ClientActiveObject *obj = objects[i].obj;
1339
1340                 core::aabbox3d<f32> *selection_box = obj->getSelectionBox();
1341                 if(selection_box == NULL)
1342                         continue;
1343
1344                 v3f pos = obj->getPosition();
1345
1346                 core::aabbox3d<f32> offsetted_box(
1347                                 selection_box->MinEdge + pos,
1348                                 selection_box->MaxEdge + pos
1349                 );
1350
1351                 if(offsetted_box.intersectsWithLine(shootline_on_map))
1352                 {
1353                         return obj;
1354                 }
1355         }
1356
1357         return NULL;
1358 }
1359
1360 std::list<std::string> Client::getConnectedPlayerNames()
1361 {
1362         return m_env.getPlayerNames();
1363 }
1364
1365 float Client::getAnimationTime()
1366 {
1367         return m_animation_time;
1368 }
1369
1370 int Client::getCrackLevel()
1371 {
1372         return m_crack_level;
1373 }
1374
1375 void Client::setHighlighted(v3s16 pos, bool show_highlighted)
1376 {
1377         m_show_highlighted = show_highlighted;
1378         v3s16 old_highlighted_pos = m_highlighted_pos;
1379         m_highlighted_pos = pos;
1380         addUpdateMeshTaskForNode(old_highlighted_pos, false, true);
1381         addUpdateMeshTaskForNode(m_highlighted_pos, false, true);
1382 }
1383
1384 void Client::setCrack(int level, v3s16 pos)
1385 {
1386         int old_crack_level = m_crack_level;
1387         v3s16 old_crack_pos = m_crack_pos;
1388
1389         m_crack_level = level;
1390         m_crack_pos = pos;
1391
1392         if(old_crack_level >= 0 && (level < 0 || pos != old_crack_pos))
1393         {
1394                 // remove old crack
1395                 addUpdateMeshTaskForNode(old_crack_pos, false, true);
1396         }
1397         if(level >= 0 && (old_crack_level < 0 || pos != old_crack_pos))
1398         {
1399                 // add new crack
1400                 addUpdateMeshTaskForNode(pos, false, true);
1401         }
1402 }
1403
1404 u16 Client::getHP()
1405 {
1406         Player *player = m_env.getLocalPlayer();
1407         assert(player != NULL);
1408         return player->hp;
1409 }
1410
1411 u16 Client::getBreath()
1412 {
1413         Player *player = m_env.getLocalPlayer();
1414         assert(player != NULL);
1415         return player->getBreath();
1416 }
1417
1418 bool Client::getChatMessage(std::wstring &message)
1419 {
1420         if(m_chat_queue.size() == 0)
1421                 return false;
1422         message = m_chat_queue.front();
1423         m_chat_queue.pop();
1424         return true;
1425 }
1426
1427 void Client::typeChatMessage(const std::wstring &message)
1428 {
1429         // Discard empty line
1430         if(message == L"")
1431                 return;
1432
1433         // Send to others
1434         sendChatMessage(message);
1435
1436         // Show locally
1437         if (message[0] == L'/')
1438         {
1439                 m_chat_queue.push((std::wstring)L"issued command: " + message);
1440         }
1441         else
1442         {
1443                 LocalPlayer *player = m_env.getLocalPlayer();
1444                 assert(player != NULL);
1445                 std::wstring name = narrow_to_wide(player->getName());
1446                 m_chat_queue.push((std::wstring)L"<" + name + L"> " + message);
1447         }
1448 }
1449
1450 void Client::addUpdateMeshTask(v3s16 p, bool ack_to_server, bool urgent)
1451 {
1452         MapBlock *b = m_env.getMap().getBlockNoCreateNoEx(p);
1453         if(b == NULL)
1454                 return;
1455
1456         /*
1457                 Create a task to update the mesh of the block
1458         */
1459
1460         MeshMakeData *data = new MeshMakeData(this, m_cache_enable_shaders);
1461
1462         {
1463                 //TimeTaker timer("data fill");
1464                 // Release: ~0ms
1465                 // Debug: 1-6ms, avg=2ms
1466                 data->fill(b);
1467                 data->setCrack(m_crack_level, m_crack_pos);
1468                 data->setHighlighted(m_highlighted_pos, m_show_highlighted);
1469                 data->setSmoothLighting(m_cache_smooth_lighting);
1470         }
1471
1472         // Add task to queue
1473         m_mesh_update_thread.m_queue_in.addBlock(p, data, ack_to_server, urgent);
1474 }
1475
1476 void Client::addUpdateMeshTaskWithEdge(v3s16 blockpos, bool ack_to_server, bool urgent)
1477 {
1478         try{
1479                 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1480         }
1481         catch(InvalidPositionException &e){}
1482
1483         // Leading edge
1484         for (int i=0;i<6;i++)
1485         {
1486                 try{
1487                         v3s16 p = blockpos + g_6dirs[i];
1488                         addUpdateMeshTask(p, false, urgent);
1489                 }
1490                 catch(InvalidPositionException &e){}
1491         }
1492 }
1493
1494 void Client::addUpdateMeshTaskForNode(v3s16 nodepos, bool ack_to_server, bool urgent)
1495 {
1496         {
1497                 v3s16 p = nodepos;
1498                 infostream<<"Client::addUpdateMeshTaskForNode(): "
1499                                 <<"("<<p.X<<","<<p.Y<<","<<p.Z<<")"
1500                                 <<std::endl;
1501         }
1502
1503         v3s16 blockpos          = getNodeBlockPos(nodepos);
1504         v3s16 blockpos_relative = blockpos * MAP_BLOCKSIZE;
1505
1506         try{
1507                 addUpdateMeshTask(blockpos, ack_to_server, urgent);
1508         }
1509         catch(InvalidPositionException &e) {}
1510
1511         // Leading edge
1512         if(nodepos.X == blockpos_relative.X){
1513                 try{
1514                         v3s16 p = blockpos + v3s16(-1,0,0);
1515                         addUpdateMeshTask(p, false, urgent);
1516                 }
1517                 catch(InvalidPositionException &e){}
1518         }
1519
1520         if(nodepos.Y == blockpos_relative.Y){
1521                 try{
1522                         v3s16 p = blockpos + v3s16(0,-1,0);
1523                         addUpdateMeshTask(p, false, urgent);
1524                 }
1525                 catch(InvalidPositionException &e){}
1526         }
1527
1528         if(nodepos.Z == blockpos_relative.Z){
1529                 try{
1530                         v3s16 p = blockpos + v3s16(0,0,-1);
1531                         addUpdateMeshTask(p, false, urgent);
1532                 }
1533                 catch(InvalidPositionException &e){}
1534         }
1535 }
1536
1537 ClientEvent Client::getClientEvent()
1538 {
1539         ClientEvent event;
1540         if(m_client_event_queue.size() == 0) {
1541                 event.type = CE_NONE;
1542         }
1543         else {
1544                 event = m_client_event_queue.front();
1545                 m_client_event_queue.pop();
1546         }
1547         return event;
1548 }
1549
1550 float Client::mediaReceiveProgress()
1551 {
1552         if (m_media_downloader)
1553                 return m_media_downloader->getProgress();
1554         else
1555                 return 1.0; // downloader only exists when not yet done
1556 }
1557
1558 void Client::afterContentReceived(IrrlichtDevice *device, gui::IGUIFont* font)
1559 {
1560         infostream<<"Client::afterContentReceived() started"<<std::endl;
1561         assert(m_itemdef_received); // pre-condition
1562         assert(m_nodedef_received); // pre-condition
1563         assert(mediaReceived()); // pre-condition
1564
1565         const wchar_t* text = wgettext("Loading textures...");
1566
1567         // Rebuild inherited images and recreate textures
1568         infostream<<"- Rebuilding images and textures"<<std::endl;
1569         draw_load_screen(text,device, guienv, 0, 70);
1570         m_tsrc->rebuildImagesAndTextures();
1571         delete[] text;
1572
1573         // Rebuild shaders
1574         infostream<<"- Rebuilding shaders"<<std::endl;
1575         text = wgettext("Rebuilding shaders...");
1576         draw_load_screen(text, device, guienv, 0, 75);
1577         m_shsrc->rebuildShaders();
1578         delete[] text;
1579
1580         // Update node aliases
1581         infostream<<"- Updating node aliases"<<std::endl;
1582         text = wgettext("Initializing nodes...");
1583         draw_load_screen(text, device, guienv, 0, 80);
1584         m_nodedef->updateAliases(m_itemdef);
1585         m_nodedef->setNodeRegistrationStatus(true);
1586         m_nodedef->runNodeResolverCallbacks();
1587         delete[] text;
1588
1589         // Update node textures and assign shaders to each tile
1590         infostream<<"- Updating node textures"<<std::endl;
1591         m_nodedef->updateTextures(this);
1592
1593         // Preload item textures and meshes if configured to
1594         if(g_settings->getBool("preload_item_visuals"))
1595         {
1596                 verbosestream<<"Updating item textures and meshes"<<std::endl;
1597                 text = wgettext("Item textures...");
1598                 draw_load_screen(text, device, guienv, 0, 0);
1599                 std::set<std::string> names = m_itemdef->getAll();
1600                 size_t size = names.size();
1601                 size_t count = 0;
1602                 int percent = 0;
1603                 for(std::set<std::string>::const_iterator
1604                                 i = names.begin(); i != names.end(); ++i)
1605                 {
1606                         // Asking for these caches the result
1607                         m_itemdef->getInventoryTexture(*i, this);
1608                         m_itemdef->getWieldMesh(*i, this);
1609                         count++;
1610                         percent = (count * 100 / size * 0.2) + 80;
1611                         draw_load_screen(text, device, guienv, 0, percent);
1612                 }
1613                 delete[] text;
1614         }
1615
1616         // Start mesh update thread after setting up content definitions
1617         infostream<<"- Starting mesh update thread"<<std::endl;
1618         m_mesh_update_thread.Start();
1619
1620         m_state = LC_Ready;
1621         sendReady();
1622         text = wgettext("Done!");
1623         draw_load_screen(text, device, guienv, 0, 100);
1624         infostream<<"Client::afterContentReceived() done"<<std::endl;
1625         delete[] text;
1626 }
1627
1628 float Client::getRTT(void)
1629 {
1630         return m_con.getPeerStat(PEER_ID_SERVER,con::AVG_RTT);
1631 }
1632
1633 float Client::getCurRate(void)
1634 {
1635         return ( m_con.getLocalStat(con::CUR_INC_RATE) +
1636                         m_con.getLocalStat(con::CUR_DL_RATE));
1637 }
1638
1639 float Client::getAvgRate(void)
1640 {
1641         return ( m_con.getLocalStat(con::AVG_INC_RATE) +
1642                         m_con.getLocalStat(con::AVG_DL_RATE));
1643 }
1644
1645 void Client::makeScreenshot(IrrlichtDevice *device)
1646 {
1647         irr::video::IVideoDriver *driver = device->getVideoDriver();
1648         irr::video::IImage* const raw_image = driver->createScreenShot();
1649         if (raw_image) {
1650                 irr::video::IImage* const image = driver->createImage(video::ECF_R8G8B8,
1651                         raw_image->getDimension());
1652
1653                 if (image) {
1654                         raw_image->copyTo(image);
1655                         irr::c8 filename[256];
1656                         snprintf(filename, sizeof(filename),
1657                                 (std::string("%s") + DIR_DELIM + "screenshot_%u.png").c_str(),
1658                                  g_settings->get("screenshot_path").c_str(),
1659                                  device->getTimer()->getRealTime());
1660                         std::ostringstream sstr;
1661                         if (driver->writeImageToFile(image, filename)) {
1662                                 sstr << "Saved screenshot to '" << filename << "'";
1663                         } else {
1664                                 sstr << "Failed to save screenshot '" << filename << "'";
1665                         }
1666                         m_chat_queue.push(narrow_to_wide(sstr.str()));
1667                         infostream << sstr.str() << std::endl;
1668                         image->drop();
1669                 }
1670                 raw_image->drop();
1671         }
1672 }
1673
1674 // IGameDef interface
1675 // Under envlock
1676 IItemDefManager* Client::getItemDefManager()
1677 {
1678         return m_itemdef;
1679 }
1680 INodeDefManager* Client::getNodeDefManager()
1681 {
1682         return m_nodedef;
1683 }
1684 ICraftDefManager* Client::getCraftDefManager()
1685 {
1686         return NULL;
1687         //return m_craftdef;
1688 }
1689 ITextureSource* Client::getTextureSource()
1690 {
1691         return m_tsrc;
1692 }
1693 IShaderSource* Client::getShaderSource()
1694 {
1695         return m_shsrc;
1696 }
1697 scene::ISceneManager* Client::getSceneManager()
1698 {
1699         return m_device->getSceneManager();
1700 }
1701 u16 Client::allocateUnknownNodeId(const std::string &name)
1702 {
1703         errorstream << "Client::allocateUnknownNodeId(): "
1704                         << "Client cannot allocate node IDs" << std::endl;
1705         FATAL_ERROR("Client allocated unknown node");
1706
1707         return CONTENT_IGNORE;
1708 }
1709 ISoundManager* Client::getSoundManager()
1710 {
1711         return m_sound;
1712 }
1713 MtEventManager* Client::getEventManager()
1714 {
1715         return m_event;
1716 }
1717
1718 ParticleManager* Client::getParticleManager()
1719 {
1720         return &m_particle_manager;
1721 }
1722
1723 scene::IAnimatedMesh* Client::getMesh(const std::string &filename)
1724 {
1725         std::map<std::string, std::string>::const_iterator i =
1726                         m_mesh_data.find(filename);
1727         if(i == m_mesh_data.end()){
1728                 errorstream<<"Client::getMesh(): Mesh not found: \""<<filename<<"\""
1729                                 <<std::endl;
1730                 return NULL;
1731         }
1732         const std::string &data    = i->second;
1733         scene::ISceneManager *smgr = m_device->getSceneManager();
1734
1735         // Create the mesh, remove it from cache and return it
1736         // This allows unique vertex colors and other properties for each instance
1737         Buffer<char> data_rw(data.c_str(), data.size()); // Const-incorrect Irrlicht
1738         io::IFileSystem *irrfs = m_device->getFileSystem();
1739         io::IReadFile *rfile   = irrfs->createMemoryReadFile(
1740                         *data_rw, data_rw.getSize(), filename.c_str());
1741         FATAL_ERROR_IF(!rfile, "Could not create/open RAM file");
1742
1743         scene::IAnimatedMesh *mesh = smgr->getMesh(rfile);
1744         rfile->drop();
1745         // NOTE: By playing with Irrlicht refcounts, maybe we could cache a bunch
1746         // of uniquely named instances and re-use them
1747         mesh->grab();
1748         smgr->getMeshCache()->removeMesh(mesh);
1749         return mesh;
1750 }