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