2a9aac32beccc5e376746fddbac28da963a37756
[oweals/minetest.git] / src / server.cpp
1 /*
2 Minetest-c55
3 Copyright (C) 2010-2011 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 General Public License as published by
7 the Free Software Foundation; either version 2 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 General Public License for more details.
14
15 You should have received a copy of the GNU 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 "server.h"
21 #include "utility.h"
22 #include <iostream>
23 #include "clientserver.h"
24 #include "map.h"
25 #include "jmutexautolock.h"
26 #include "main.h"
27 #include "constants.h"
28 #include "voxel.h"
29 #include "materials.h"
30 #include "mineral.h"
31 #include "config.h"
32 #include "servercommand.h"
33 #include "filesys.h"
34 #include "content_mapnode.h"
35 #include "content_craft.h"
36 #include "content_nodemeta.h"
37 #include "mapblock.h"
38 #include "serverobject.h"
39 #include "settings.h"
40 #include "profiler.h"
41 #include "log.h"
42 #include "script.h"
43 #include "scriptapi.h"
44 #include "nodedef.h"
45 #include "tooldef.h"
46
47 #define PP(x) "("<<(x).X<<","<<(x).Y<<","<<(x).Z<<")"
48
49 #define BLOCK_EMERGE_FLAG_FROMDISK (1<<0)
50
51 class MapEditEventIgnorer
52 {
53 public:
54         MapEditEventIgnorer(bool *flag):
55                 m_flag(flag)
56         {
57                 if(*m_flag == false)
58                         *m_flag = true;
59                 else
60                         m_flag = NULL;
61         }
62
63         ~MapEditEventIgnorer()
64         {
65                 if(m_flag)
66                 {
67                         assert(*m_flag);
68                         *m_flag = false;
69                 }
70         }
71         
72 private:
73         bool *m_flag;
74 };
75
76 void * ServerThread::Thread()
77 {
78         ThreadStarted();
79
80         log_register_thread("ServerThread");
81
82         DSTACK(__FUNCTION_NAME);
83
84         BEGIN_DEBUG_EXCEPTION_HANDLER
85
86         while(getRun())
87         {
88                 try{
89                         //TimeTaker timer("AsyncRunStep() + Receive()");
90
91                         {
92                                 //TimeTaker timer("AsyncRunStep()");
93                                 m_server->AsyncRunStep();
94                         }
95                 
96                         //infostream<<"Running m_server->Receive()"<<std::endl;
97                         m_server->Receive();
98                 }
99                 catch(con::NoIncomingDataException &e)
100                 {
101                 }
102                 catch(con::PeerNotFoundException &e)
103                 {
104                         infostream<<"Server: PeerNotFoundException"<<std::endl;
105                 }
106         }
107         
108         END_DEBUG_EXCEPTION_HANDLER(errorstream)
109
110         return NULL;
111 }
112
113 void * EmergeThread::Thread()
114 {
115         ThreadStarted();
116
117         log_register_thread("EmergeThread");
118
119         DSTACK(__FUNCTION_NAME);
120
121         BEGIN_DEBUG_EXCEPTION_HANDLER
122
123         bool enable_mapgen_debug_info = g_settings->getBool("enable_mapgen_debug_info");
124         
125         /*
126                 Get block info from queue, emerge them and send them
127                 to clients.
128
129                 After queue is empty, exit.
130         */
131         while(getRun())
132         {
133                 QueuedBlockEmerge *qptr = m_server->m_emerge_queue.pop();
134                 if(qptr == NULL)
135                         break;
136                 
137                 SharedPtr<QueuedBlockEmerge> q(qptr);
138
139                 v3s16 &p = q->pos;
140                 v2s16 p2d(p.X,p.Z);
141
142                 /*
143                         Do not generate over-limit
144                 */
145                 if(p.X < -MAP_GENERATION_LIMIT / MAP_BLOCKSIZE
146                 || p.X > MAP_GENERATION_LIMIT / MAP_BLOCKSIZE
147                 || p.Y < -MAP_GENERATION_LIMIT / MAP_BLOCKSIZE
148                 || p.Y > MAP_GENERATION_LIMIT / MAP_BLOCKSIZE
149                 || p.Z < -MAP_GENERATION_LIMIT / MAP_BLOCKSIZE
150                 || p.Z > MAP_GENERATION_LIMIT / MAP_BLOCKSIZE)
151                         continue;
152                         
153                 //infostream<<"EmergeThread::Thread(): running"<<std::endl;
154
155                 //TimeTaker timer("block emerge");
156                 
157                 /*
158                         Try to emerge it from somewhere.
159
160                         If it is only wanted as optional, only loading from disk
161                         will be allowed.
162                 */
163                 
164                 /*
165                         Check if any peer wants it as non-optional. In that case it
166                         will be generated.
167
168                         Also decrement the emerge queue count in clients.
169                 */
170
171                 bool only_from_disk = true;
172
173                 {
174                         core::map<u16, u8>::Iterator i;
175                         for(i=q->peer_ids.getIterator(); i.atEnd()==false; i++)
176                         {
177                                 //u16 peer_id = i.getNode()->getKey();
178
179                                 // Check flags
180                                 u8 flags = i.getNode()->getValue();
181                                 if((flags & BLOCK_EMERGE_FLAG_FROMDISK) == false)
182                                         only_from_disk = false;
183                                 
184                         }
185                 }
186                 
187                 if(enable_mapgen_debug_info)
188                         infostream<<"EmergeThread: p="
189                                         <<"("<<p.X<<","<<p.Y<<","<<p.Z<<") "
190                                         <<"only_from_disk="<<only_from_disk<<std::endl;
191                 
192                 ServerMap &map = ((ServerMap&)m_server->m_env->getMap());
193                         
194                 //core::map<v3s16, MapBlock*> changed_blocks;
195                 //core::map<v3s16, MapBlock*> lighting_invalidated_blocks;
196
197                 MapBlock *block = NULL;
198                 bool got_block = true;
199                 core::map<v3s16, MapBlock*> modified_blocks;
200                 
201                 /*
202                         Fetch block from map or generate a single block
203                 */
204                 {
205                         JMutexAutoLock envlock(m_server->m_env_mutex);
206                         
207                         // Load sector if it isn't loaded
208                         if(map.getSectorNoGenerateNoEx(p2d) == NULL)
209                                 //map.loadSectorFull(p2d);
210                                 map.loadSectorMeta(p2d);
211
212                         block = map.getBlockNoCreateNoEx(p);
213                         if(!block || block->isDummy() || !block->isGenerated())
214                         {
215                                 if(enable_mapgen_debug_info)
216                                         infostream<<"EmergeThread: not in memory, loading"<<std::endl;
217
218                                 // Get, load or create sector
219                                 /*ServerMapSector *sector =
220                                                 (ServerMapSector*)map.createSector(p2d);*/
221
222                                 // Load/generate block
223
224                                 /*block = map.emergeBlock(p, sector, changed_blocks,
225                                                 lighting_invalidated_blocks);*/
226
227                                 block = map.loadBlock(p);
228                                 
229                                 if(only_from_disk == false)
230                                 {
231                                         if(block == NULL || block->isGenerated() == false)
232                                         {
233                                                 if(enable_mapgen_debug_info)
234                                                         infostream<<"EmergeThread: generating"<<std::endl;
235                                                 block = map.generateBlock(p, modified_blocks);
236                                         }
237                                 }
238
239                                 if(enable_mapgen_debug_info)
240                                         infostream<<"EmergeThread: ended up with: "
241                                                         <<analyze_block(block)<<std::endl;
242
243                                 if(block == NULL)
244                                 {
245                                         got_block = false;
246                                 }
247                                 else
248                                 {
249                                         /*
250                                                 Ignore map edit events, they will not need to be
251                                                 sent to anybody because the block hasn't been sent
252                                                 to anybody
253                                         */
254                                         MapEditEventIgnorer ign(&m_server->m_ignore_map_edit_events);
255                                         
256                                         // Activate objects and stuff
257                                         m_server->m_env->activateBlock(block, 3600);
258                                 }
259                         }
260                         else
261                         {
262                                 /*if(block->getLightingExpired()){
263                                         lighting_invalidated_blocks[block->getPos()] = block;
264                                 }*/
265                         }
266
267                         // TODO: Some additional checking and lighting updating,
268                         //       see emergeBlock
269                 }
270
271                 {//envlock
272                 JMutexAutoLock envlock(m_server->m_env_mutex);
273                 
274                 if(got_block)
275                 {
276                         /*
277                                 Collect a list of blocks that have been modified in
278                                 addition to the fetched one.
279                         */
280
281 #if 0
282                         if(lighting_invalidated_blocks.size() > 0)
283                         {
284                                 /*infostream<<"lighting "<<lighting_invalidated_blocks.size()
285                                                 <<" blocks"<<std::endl;*/
286                         
287                                 // 50-100ms for single block generation
288                                 //TimeTaker timer("** EmergeThread updateLighting");
289                                 
290                                 // Update lighting without locking the environment mutex,
291                                 // add modified blocks to changed blocks
292                                 map.updateLighting(lighting_invalidated_blocks, modified_blocks);
293                         }
294                                 
295                         // Add all from changed_blocks to modified_blocks
296                         for(core::map<v3s16, MapBlock*>::Iterator i = changed_blocks.getIterator();
297                                         i.atEnd() == false; i++)
298                         {
299                                 MapBlock *block = i.getNode()->getValue();
300                                 modified_blocks.insert(block->getPos(), block);
301                         }
302 #endif
303                 }
304                 // If we got no block, there should be no invalidated blocks
305                 else
306                 {
307                         //assert(lighting_invalidated_blocks.size() == 0);
308                 }
309
310                 }//envlock
311
312                 /*
313                         Set sent status of modified blocks on clients
314                 */
315         
316                 // NOTE: Server's clients are also behind the connection mutex
317                 JMutexAutoLock lock(m_server->m_con_mutex);
318
319                 /*
320                         Add the originally fetched block to the modified list
321                 */
322                 if(got_block)
323                 {
324                         modified_blocks.insert(p, block);
325                 }
326                 
327                 /*
328                         Set the modified blocks unsent for all the clients
329                 */
330                 
331                 for(core::map<u16, RemoteClient*>::Iterator
332                                 i = m_server->m_clients.getIterator();
333                                 i.atEnd() == false; i++)
334                 {
335                         RemoteClient *client = i.getNode()->getValue();
336                         
337                         if(modified_blocks.size() > 0)
338                         {
339                                 // Remove block from sent history
340                                 client->SetBlocksNotSent(modified_blocks);
341                         }
342                 }
343                 
344         }
345
346         END_DEBUG_EXCEPTION_HANDLER(errorstream)
347
348         return NULL;
349 }
350
351 void RemoteClient::GetNextBlocks(Server *server, float dtime,
352                 core::array<PrioritySortedBlockTransfer> &dest)
353 {
354         DSTACK(__FUNCTION_NAME);
355         
356         /*u32 timer_result;
357         TimeTaker timer("RemoteClient::GetNextBlocks", &timer_result);*/
358         
359         // Increment timers
360         m_nothing_to_send_pause_timer -= dtime;
361         m_nearest_unsent_reset_timer += dtime;
362         
363         if(m_nothing_to_send_pause_timer >= 0)
364         {
365                 return;
366         }
367
368         // Won't send anything if already sending
369         if(m_blocks_sending.size() >= g_settings->getU16
370                         ("max_simultaneous_block_sends_per_client"))
371         {
372                 //infostream<<"Not sending any blocks, Queue full."<<std::endl;
373                 return;
374         }
375
376         //TimeTaker timer("RemoteClient::GetNextBlocks");
377         
378         Player *player = server->m_env->getPlayer(peer_id);
379
380         assert(player != NULL);
381
382         v3f playerpos = player->getPosition();
383         v3f playerspeed = player->getSpeed();
384         v3f playerspeeddir(0,0,0);
385         if(playerspeed.getLength() > 1.0*BS)
386                 playerspeeddir = playerspeed / playerspeed.getLength();
387         // Predict to next block
388         v3f playerpos_predicted = playerpos + playerspeeddir*MAP_BLOCKSIZE*BS;
389
390         v3s16 center_nodepos = floatToInt(playerpos_predicted, BS);
391
392         v3s16 center = getNodeBlockPos(center_nodepos);
393         
394         // Camera position and direction
395         v3f camera_pos = player->getEyePosition();
396         v3f camera_dir = v3f(0,0,1);
397         camera_dir.rotateYZBy(player->getPitch());
398         camera_dir.rotateXZBy(player->getYaw());
399
400         /*infostream<<"camera_dir=("<<camera_dir.X<<","<<camera_dir.Y<<","
401                         <<camera_dir.Z<<")"<<std::endl;*/
402
403         /*
404                 Get the starting value of the block finder radius.
405         */
406                 
407         if(m_last_center != center)
408         {
409                 m_nearest_unsent_d = 0;
410                 m_last_center = center;
411         }
412
413         /*infostream<<"m_nearest_unsent_reset_timer="
414                         <<m_nearest_unsent_reset_timer<<std::endl;*/
415                         
416         // Reset periodically to workaround for some bugs or stuff
417         if(m_nearest_unsent_reset_timer > 20.0)
418         {
419                 m_nearest_unsent_reset_timer = 0;
420                 m_nearest_unsent_d = 0;
421                 //infostream<<"Resetting m_nearest_unsent_d for "
422                 //              <<server->getPlayerName(peer_id)<<std::endl;
423         }
424
425         //s16 last_nearest_unsent_d = m_nearest_unsent_d;
426         s16 d_start = m_nearest_unsent_d;
427
428         //infostream<<"d_start="<<d_start<<std::endl;
429
430         u16 max_simul_sends_setting = g_settings->getU16
431                         ("max_simultaneous_block_sends_per_client");
432         u16 max_simul_sends_usually = max_simul_sends_setting;
433
434         /*
435                 Check the time from last addNode/removeNode.
436                 
437                 Decrease send rate if player is building stuff.
438         */
439         m_time_from_building += dtime;
440         if(m_time_from_building < g_settings->getFloat(
441                                 "full_block_send_enable_min_time_from_building"))
442         {
443                 max_simul_sends_usually
444                         = LIMITED_MAX_SIMULTANEOUS_BLOCK_SENDS;
445         }
446         
447         /*
448                 Number of blocks sending + number of blocks selected for sending
449         */
450         u32 num_blocks_selected = m_blocks_sending.size();
451         
452         /*
453                 next time d will be continued from the d from which the nearest
454                 unsent block was found this time.
455
456                 This is because not necessarily any of the blocks found this
457                 time are actually sent.
458         */
459         s32 new_nearest_unsent_d = -1;
460
461         s16 d_max = g_settings->getS16("max_block_send_distance");
462         s16 d_max_gen = g_settings->getS16("max_block_generate_distance");
463         
464         // Don't loop very much at a time
465         s16 max_d_increment_at_time = 2;
466         if(d_max > d_start + max_d_increment_at_time)
467                 d_max = d_start + max_d_increment_at_time;
468         /*if(d_max_gen > d_start+2)
469                 d_max_gen = d_start+2;*/
470         
471         //infostream<<"Starting from "<<d_start<<std::endl;
472
473         s32 nearest_emerged_d = -1;
474         s32 nearest_emergefull_d = -1;
475         s32 nearest_sent_d = -1;
476         bool queue_is_full = false;
477         
478         s16 d;
479         for(d = d_start; d <= d_max; d++)
480         {
481                 /*errorstream<<"checking d="<<d<<" for "
482                                 <<server->getPlayerName(peer_id)<<std::endl;*/
483                 //infostream<<"RemoteClient::SendBlocks(): d="<<d<<std::endl;
484                 
485                 /*
486                         If m_nearest_unsent_d was changed by the EmergeThread
487                         (it can change it to 0 through SetBlockNotSent),
488                         update our d to it.
489                         Else update m_nearest_unsent_d
490                 */
491                 /*if(m_nearest_unsent_d != last_nearest_unsent_d)
492                 {
493                         d = m_nearest_unsent_d;
494                         last_nearest_unsent_d = m_nearest_unsent_d;
495                 }*/
496
497                 /*
498                         Get the border/face dot coordinates of a "d-radiused"
499                         box
500                 */
501                 core::list<v3s16> list;
502                 getFacePositions(list, d);
503                 
504                 core::list<v3s16>::Iterator li;
505                 for(li=list.begin(); li!=list.end(); li++)
506                 {
507                         v3s16 p = *li + center;
508                         
509                         /*
510                                 Send throttling
511                                 - Don't allow too many simultaneous transfers
512                                 - EXCEPT when the blocks are very close
513
514                                 Also, don't send blocks that are already flying.
515                         */
516                         
517                         // Start with the usual maximum
518                         u16 max_simul_dynamic = max_simul_sends_usually;
519                         
520                         // If block is very close, allow full maximum
521                         if(d <= BLOCK_SEND_DISABLE_LIMITS_MAX_D)
522                                 max_simul_dynamic = max_simul_sends_setting;
523
524                         // Don't select too many blocks for sending
525                         if(num_blocks_selected >= max_simul_dynamic)
526                         {
527                                 queue_is_full = true;
528                                 goto queue_full_break;
529                         }
530                         
531                         // Don't send blocks that are currently being transferred
532                         if(m_blocks_sending.find(p) != NULL)
533                                 continue;
534                 
535                         /*
536                                 Do not go over-limit
537                         */
538                         if(p.X < -MAP_GENERATION_LIMIT / MAP_BLOCKSIZE
539                         || p.X > MAP_GENERATION_LIMIT / MAP_BLOCKSIZE
540                         || p.Y < -MAP_GENERATION_LIMIT / MAP_BLOCKSIZE
541                         || p.Y > MAP_GENERATION_LIMIT / MAP_BLOCKSIZE
542                         || p.Z < -MAP_GENERATION_LIMIT / MAP_BLOCKSIZE
543                         || p.Z > MAP_GENERATION_LIMIT / MAP_BLOCKSIZE)
544                                 continue;
545                 
546                         // If this is true, inexistent block will be made from scratch
547                         bool generate = d <= d_max_gen;
548                         
549                         {
550                                 /*// Limit the generating area vertically to 2/3
551                                 if(abs(p.Y - center.Y) > d_max_gen - d_max_gen / 3)
552                                         generate = false;*/
553
554                                 // Limit the send area vertically to 1/2
555                                 if(abs(p.Y - center.Y) > d_max / 2)
556                                         continue;
557                         }
558
559 #if 0
560                         /*
561                                 If block is far away, don't generate it unless it is
562                                 near ground level.
563                         */
564                         if(d >= 4)
565                         {
566         #if 1
567                                 // Block center y in nodes
568                                 f32 y = (f32)(p.Y * MAP_BLOCKSIZE + MAP_BLOCKSIZE/2);
569                                 // Don't generate if it's very high or very low
570                                 if(y < -64 || y > 64)
571                                         generate = false;
572         #endif
573         #if 0
574                                 v2s16 p2d_nodes_center(
575                                         MAP_BLOCKSIZE*p.X,
576                                         MAP_BLOCKSIZE*p.Z);
577                                 
578                                 // Get ground height in nodes
579                                 s16 gh = server->m_env->getServerMap().findGroundLevel(
580                                                 p2d_nodes_center);
581
582                                 // If differs a lot, don't generate
583                                 if(fabs(gh - y) > MAP_BLOCKSIZE*2)
584                                         generate = false;
585                                         // Actually, don't even send it
586                                         //continue;
587         #endif
588                         }
589 #endif
590
591                         //infostream<<"d="<<d<<std::endl;
592 #if 1
593                         /*
594                                 Don't generate or send if not in sight
595                                 FIXME This only works if the client uses a small enough
596                                 FOV setting. The default of 72 degrees is fine.
597                         */
598
599                         float camera_fov = (72.0*PI/180) * 4./3.;
600                         if(isBlockInSight(p, camera_pos, camera_dir, camera_fov, 10000*BS) == false)
601                         {
602                                 continue;
603                         }
604 #endif
605                         /*
606                                 Don't send already sent blocks
607                         */
608                         {
609                                 if(m_blocks_sent.find(p) != NULL)
610                                 {
611                                         continue;
612                                 }
613                         }
614
615                         /*
616                                 Check if map has this block
617                         */
618                         MapBlock *block = server->m_env->getMap().getBlockNoCreateNoEx(p);
619                         
620                         bool surely_not_found_on_disk = false;
621                         bool block_is_invalid = false;
622                         if(block != NULL)
623                         {
624                                 // Reset usage timer, this block will be of use in the future.
625                                 block->resetUsageTimer();
626
627                                 // Block is dummy if data doesn't exist.
628                                 // It means it has been not found from disk and not generated
629                                 if(block->isDummy())
630                                 {
631                                         surely_not_found_on_disk = true;
632                                 }
633                                 
634                                 // Block is valid if lighting is up-to-date and data exists
635                                 if(block->isValid() == false)
636                                 {
637                                         block_is_invalid = true;
638                                 }
639                                 
640                                 /*if(block->isFullyGenerated() == false)
641                                 {
642                                         block_is_invalid = true;
643                                 }*/
644
645 #if 0
646                                 v2s16 p2d(p.X, p.Z);
647                                 ServerMap *map = (ServerMap*)(&server->m_env->getMap());
648                                 v2s16 chunkpos = map->sector_to_chunk(p2d);
649                                 if(map->chunkNonVolatile(chunkpos) == false)
650                                         block_is_invalid = true;
651 #endif
652                                 if(block->isGenerated() == false)
653                                         block_is_invalid = true;
654 #if 1
655                                 /*
656                                         If block is not close, don't send it unless it is near
657                                         ground level.
658
659                                         Block is near ground level if night-time mesh
660                                         differs from day-time mesh.
661                                 */
662                                 if(d >= 4)
663                                 {
664                                         if(block->dayNightDiffed() == false)
665                                                 continue;
666                                 }
667 #endif
668                         }
669
670                         /*
671                                 If block has been marked to not exist on disk (dummy)
672                                 and generating new ones is not wanted, skip block.
673                         */
674                         if(generate == false && surely_not_found_on_disk == true)
675                         {
676                                 // get next one.
677                                 continue;
678                         }
679
680                         /*
681                                 Add inexistent block to emerge queue.
682                         */
683                         if(block == NULL || surely_not_found_on_disk || block_is_invalid)
684                         {
685                                 //TODO: Get value from somewhere
686                                 // Allow only one block in emerge queue
687                                 //if(server->m_emerge_queue.peerItemCount(peer_id) < 1)
688                                 // Allow two blocks in queue per client
689                                 //if(server->m_emerge_queue.peerItemCount(peer_id) < 2)
690                                 if(server->m_emerge_queue.peerItemCount(peer_id) < 25)
691                                 {
692                                         //infostream<<"Adding block to emerge queue"<<std::endl;
693                                         
694                                         // Add it to the emerge queue and trigger the thread
695                                         
696                                         u8 flags = 0;
697                                         if(generate == false)
698                                                 flags |= BLOCK_EMERGE_FLAG_FROMDISK;
699                                         
700                                         server->m_emerge_queue.addBlock(peer_id, p, flags);
701                                         server->m_emergethread.trigger();
702
703                                         if(nearest_emerged_d == -1)
704                                                 nearest_emerged_d = d;
705                                 } else {
706                                         if(nearest_emergefull_d == -1)
707                                                 nearest_emergefull_d = d;
708                                 }
709                                 
710                                 // get next one.
711                                 continue;
712                         }
713
714                         if(nearest_sent_d == -1)
715                                 nearest_sent_d = d;
716
717                         /*
718                                 Add block to send queue
719                         */
720
721                         /*errorstream<<"sending from d="<<d<<" to "
722                                         <<server->getPlayerName(peer_id)<<std::endl;*/
723
724                         PrioritySortedBlockTransfer q((float)d, p, peer_id);
725
726                         dest.push_back(q);
727
728                         num_blocks_selected += 1;
729                 }
730         }
731 queue_full_break:
732
733         //infostream<<"Stopped at "<<d<<std::endl;
734         
735         // If nothing was found for sending and nothing was queued for
736         // emerging, continue next time browsing from here
737         if(nearest_emerged_d != -1){
738                 new_nearest_unsent_d = nearest_emerged_d;
739         } else if(nearest_emergefull_d != -1){
740                 new_nearest_unsent_d = nearest_emergefull_d;
741         } else {
742                 if(d > g_settings->getS16("max_block_send_distance")){
743                         new_nearest_unsent_d = 0;
744                         m_nothing_to_send_pause_timer = 2.0;
745                         /*infostream<<"GetNextBlocks(): d wrapped around for "
746                                         <<server->getPlayerName(peer_id)
747                                         <<"; setting to 0 and pausing"<<std::endl;*/
748                 } else {
749                         if(nearest_sent_d != -1)
750                                 new_nearest_unsent_d = nearest_sent_d;
751                         else
752                                 new_nearest_unsent_d = d;
753                 }
754         }
755
756         if(new_nearest_unsent_d != -1)
757                 m_nearest_unsent_d = new_nearest_unsent_d;
758
759         /*timer_result = timer.stop(true);
760         if(timer_result != 0)
761                 infostream<<"GetNextBlocks duration: "<<timer_result<<" (!=0)"<<std::endl;*/
762 }
763
764 void RemoteClient::SendObjectData(
765                 Server *server,
766                 float dtime,
767                 core::map<v3s16, bool> &stepped_blocks
768         )
769 {
770         DSTACK(__FUNCTION_NAME);
771
772         // Can't send anything without knowing version
773         if(serialization_version == SER_FMT_VER_INVALID)
774         {
775                 infostream<<"RemoteClient::SendObjectData(): Not sending, no version."
776                                 <<std::endl;
777                 return;
778         }
779
780         /*
781                 Send a TOCLIENT_OBJECTDATA packet.
782                 Sent as unreliable.
783
784                 u16 command
785                 u16 number of player positions
786                 for each player:
787                         u16 peer_id
788                         v3s32 position*100
789                         v3s32 speed*100
790                         s32 pitch*100
791                         s32 yaw*100
792                 u16 count of blocks
793                 for each block:
794                         block objects
795         */
796
797         std::ostringstream os(std::ios_base::binary);
798         u8 buf[12];
799         
800         // Write command
801         writeU16(buf, TOCLIENT_OBJECTDATA);
802         os.write((char*)buf, 2);
803         
804         /*
805                 Get and write player data
806         */
807         
808         // Get connected players
809         core::list<Player*> players = server->m_env->getPlayers(true);
810
811         // Write player count
812         u16 playercount = players.size();
813         writeU16(buf, playercount);
814         os.write((char*)buf, 2);
815
816         core::list<Player*>::Iterator i;
817         for(i = players.begin();
818                         i != players.end(); i++)
819         {
820                 Player *player = *i;
821
822                 v3f pf = player->getPosition();
823                 v3f sf = player->getSpeed();
824
825                 v3s32 position_i(pf.X*100, pf.Y*100, pf.Z*100);
826                 v3s32 speed_i   (sf.X*100, sf.Y*100, sf.Z*100);
827                 s32   pitch_i   (player->getPitch() * 100);
828                 s32   yaw_i     (player->getYaw() * 100);
829                 
830                 writeU16(buf, player->peer_id);
831                 os.write((char*)buf, 2);
832                 writeV3S32(buf, position_i);
833                 os.write((char*)buf, 12);
834                 writeV3S32(buf, speed_i);
835                 os.write((char*)buf, 12);
836                 writeS32(buf, pitch_i);
837                 os.write((char*)buf, 4);
838                 writeS32(buf, yaw_i);
839                 os.write((char*)buf, 4);
840         }
841         
842         /*
843                 Get and write object data (dummy, for compatibility)
844         */
845
846         // Write block count
847         writeU16(buf, 0);
848         os.write((char*)buf, 2);
849
850         /*
851                 Send data
852         */
853         
854         //infostream<<"Server: Sending object data to "<<peer_id<<std::endl;
855
856         // Make data buffer
857         std::string s = os.str();
858         SharedBuffer<u8> data((u8*)s.c_str(), s.size());
859         // Send as unreliable
860         server->m_con.Send(peer_id, 0, data, false);
861 }
862
863 void RemoteClient::GotBlock(v3s16 p)
864 {
865         if(m_blocks_sending.find(p) != NULL)
866                 m_blocks_sending.remove(p);
867         else
868         {
869                 /*infostream<<"RemoteClient::GotBlock(): Didn't find in"
870                                 " m_blocks_sending"<<std::endl;*/
871                 m_excess_gotblocks++;
872         }
873         m_blocks_sent.insert(p, true);
874 }
875
876 void RemoteClient::SentBlock(v3s16 p)
877 {
878         if(m_blocks_sending.find(p) == NULL)
879                 m_blocks_sending.insert(p, 0.0);
880         else
881                 infostream<<"RemoteClient::SentBlock(): Sent block"
882                                 " already in m_blocks_sending"<<std::endl;
883 }
884
885 void RemoteClient::SetBlockNotSent(v3s16 p)
886 {
887         m_nearest_unsent_d = 0;
888         
889         if(m_blocks_sending.find(p) != NULL)
890                 m_blocks_sending.remove(p);
891         if(m_blocks_sent.find(p) != NULL)
892                 m_blocks_sent.remove(p);
893 }
894
895 void RemoteClient::SetBlocksNotSent(core::map<v3s16, MapBlock*> &blocks)
896 {
897         m_nearest_unsent_d = 0;
898         
899         for(core::map<v3s16, MapBlock*>::Iterator
900                         i = blocks.getIterator();
901                         i.atEnd()==false; i++)
902         {
903                 v3s16 p = i.getNode()->getKey();
904
905                 if(m_blocks_sending.find(p) != NULL)
906                         m_blocks_sending.remove(p);
907                 if(m_blocks_sent.find(p) != NULL)
908                         m_blocks_sent.remove(p);
909         }
910 }
911
912 /*
913         PlayerInfo
914 */
915
916 PlayerInfo::PlayerInfo()
917 {
918         name[0] = 0;
919         avg_rtt = 0;
920 }
921
922 void PlayerInfo::PrintLine(std::ostream *s)
923 {
924         (*s)<<id<<": ";
925         (*s)<<"\""<<name<<"\" ("
926                         <<(position.X/10)<<","<<(position.Y/10)
927                         <<","<<(position.Z/10)<<") ";
928         address.print(s);
929         (*s)<<" avg_rtt="<<avg_rtt;
930         (*s)<<std::endl;
931 }
932
933 u32 PIChecksum(core::list<PlayerInfo> &l)
934 {
935         core::list<PlayerInfo>::Iterator i;
936         u32 checksum = 1;
937         u32 a = 10;
938         for(i=l.begin(); i!=l.end(); i++)
939         {
940                 checksum += a * (i->id+1);
941                 checksum ^= 0x435aafcd;
942                 a *= 10;
943         }
944         return checksum;
945 }
946
947 struct ModSpec
948 {
949         std::string name;
950         std::string path;
951
952         ModSpec(const std::string &name_="", const std::string path_=""):
953                 name(name_),
954                 path(path_)
955         {}
956 };
957
958 static core::list<ModSpec> getMods(core::list<std::string> &modspaths)
959 {
960         core::list<ModSpec> mods;
961         for(core::list<std::string>::Iterator i = modspaths.begin();
962                         i != modspaths.end(); i++){
963                 std::string modspath = *i;
964                 std::vector<fs::DirListNode> dirlist = fs::GetDirListing(modspath);
965                 for(u32 j=0; j<dirlist.size(); j++){
966                         if(!dirlist[j].dir)
967                                 continue;
968                         std::string modname = dirlist[j].name;
969                         std::string modpath = modspath + DIR_DELIM + modname;
970                         mods.push_back(ModSpec(modname, modpath));
971                 }
972         }
973         return mods;
974 }
975
976 /*
977         Server
978 */
979
980 Server::Server(
981                 std::string mapsavedir,
982                 std::string configpath
983         ):
984         m_env(NULL),
985         m_con(PROTOCOL_ID, 512, CONNECTION_TIMEOUT, this),
986         m_authmanager(mapsavedir+DIR_DELIM+"auth.txt"),
987         m_banmanager(mapsavedir+DIR_DELIM+"ipban.txt"),
988         m_lua(NULL),
989         m_toolmgr(createToolDefManager()),
990         m_nodemgr(createNodeDefManager()),
991         m_thread(this),
992         m_emergethread(this),
993         m_time_counter(0),
994         m_time_of_day_send_timer(0),
995         m_uptime(0),
996         m_mapsavedir(mapsavedir),
997         m_configpath(configpath),
998         m_shutdown_requested(false),
999         m_ignore_map_edit_events(false),
1000         m_ignore_map_edit_events_peer_id(0)
1001 {
1002         m_liquid_transform_timer = 0.0;
1003         m_print_info_timer = 0.0;
1004         m_objectdata_timer = 0.0;
1005         m_emergethread_trigger_timer = 0.0;
1006         m_savemap_timer = 0.0;
1007         
1008         m_env_mutex.Init();
1009         m_con_mutex.Init();
1010         m_step_dtime_mutex.Init();
1011         m_step_dtime = 0.0;
1012
1013         JMutexAutoLock envlock(m_env_mutex);
1014         JMutexAutoLock conlock(m_con_mutex);
1015
1016         infostream<<"m_nodemgr="<<m_nodemgr<<std::endl;
1017         
1018         // Initialize default node definitions
1019         content_mapnode_init(m_nodemgr);
1020         
1021         // Add default global mod path
1022         m_modspaths.push_back(porting::path_data + DIR_DELIM + "mods");
1023
1024         // Initialize scripting
1025         
1026         infostream<<"Server: Initializing scripting"<<std::endl;
1027         m_lua = script_init();
1028         assert(m_lua);
1029         // Export API
1030         scriptapi_export(m_lua, this);
1031         // Load and run scripts
1032         core::list<ModSpec> mods = getMods(m_modspaths);
1033         for(core::list<ModSpec>::Iterator i = mods.begin();
1034                         i != mods.end(); i++){
1035                 ModSpec mod = *i;
1036                 infostream<<"Server: Loading mod \""<<mod.name<<"\""<<std::endl;
1037                 std::string scriptpath = mod.path + DIR_DELIM + "init.lua";
1038                 bool success = script_load(m_lua, scriptpath.c_str());
1039                 if(!success){
1040                         errorstream<<"Server: Failed to load and run "
1041                                         <<scriptpath<<std::endl;
1042                         assert(0);
1043                 }
1044         }
1045         
1046         // Initialize Environment
1047         
1048         m_env = new ServerEnvironment(new ServerMap(mapsavedir, this), m_lua, this);
1049
1050         // Give environment reference to scripting api
1051         scriptapi_add_environment(m_lua, m_env);
1052         
1053         // Register us to receive map edit events
1054         m_env->getMap().addEventReceiver(this);
1055
1056         // If file exists, load environment metadata
1057         if(fs::PathExists(m_mapsavedir+DIR_DELIM+"env_meta.txt"))
1058         {
1059                 infostream<<"Server: Loading environment metadata"<<std::endl;
1060                 m_env->loadMeta(m_mapsavedir);
1061         }
1062
1063         // Load players
1064         infostream<<"Server: Loading players"<<std::endl;
1065         m_env->deSerializePlayers(m_mapsavedir);
1066 }
1067
1068 Server::~Server()
1069 {
1070         infostream<<"Server::~Server()"<<std::endl;
1071
1072         /*
1073                 Send shutdown message
1074         */
1075         {
1076                 JMutexAutoLock conlock(m_con_mutex);
1077                 
1078                 std::wstring line = L"*** Server shutting down";
1079
1080                 /*
1081                         Send the message to clients
1082                 */
1083                 for(core::map<u16, RemoteClient*>::Iterator
1084                         i = m_clients.getIterator();
1085                         i.atEnd() == false; i++)
1086                 {
1087                         // Get client and check that it is valid
1088                         RemoteClient *client = i.getNode()->getValue();
1089                         assert(client->peer_id == i.getNode()->getKey());
1090                         if(client->serialization_version == SER_FMT_VER_INVALID)
1091                                 continue;
1092
1093                         try{
1094                                 SendChatMessage(client->peer_id, line);
1095                         }
1096                         catch(con::PeerNotFoundException &e)
1097                         {}
1098                 }
1099         }
1100         
1101         {
1102                 JMutexAutoLock envlock(m_env_mutex);
1103
1104                 /*
1105                         Save players
1106                 */
1107                 infostream<<"Server: Saving players"<<std::endl;
1108                 m_env->serializePlayers(m_mapsavedir);
1109
1110                 /*
1111                         Save environment metadata
1112                 */
1113                 infostream<<"Server: Saving environment metadata"<<std::endl;
1114                 m_env->saveMeta(m_mapsavedir);
1115         }
1116                 
1117         /*
1118                 Stop threads
1119         */
1120         stop();
1121         
1122         /*
1123                 Delete clients
1124         */
1125         {
1126                 JMutexAutoLock clientslock(m_con_mutex);
1127
1128                 for(core::map<u16, RemoteClient*>::Iterator
1129                         i = m_clients.getIterator();
1130                         i.atEnd() == false; i++)
1131                 {
1132                         /*// Delete player
1133                         // NOTE: These are removed by env destructor
1134                         {
1135                                 u16 peer_id = i.getNode()->getKey();
1136                                 JMutexAutoLock envlock(m_env_mutex);
1137                                 m_env->removePlayer(peer_id);
1138                         }*/
1139                         
1140                         // Delete client
1141                         delete i.getNode()->getValue();
1142                 }
1143         }
1144
1145         // Delete Environment
1146         delete m_env;
1147
1148         delete m_toolmgr;
1149         delete m_nodemgr;
1150         
1151         // Deinitialize scripting
1152         infostream<<"Server: Deinitializing scripting"<<std::endl;
1153         script_deinit(m_lua);
1154 }
1155
1156 void Server::start(unsigned short port)
1157 {
1158         DSTACK(__FUNCTION_NAME);
1159         // Stop thread if already running
1160         m_thread.stop();
1161         
1162         // Initialize connection
1163         m_con.SetTimeoutMs(30);
1164         m_con.Serve(port);
1165
1166         // Start thread
1167         m_thread.setRun(true);
1168         m_thread.Start();
1169         
1170         infostream<<"Server: Started on port "<<port<<std::endl;
1171 }
1172
1173 void Server::stop()
1174 {
1175         DSTACK(__FUNCTION_NAME);
1176         
1177         infostream<<"Server: Stopping and waiting threads"<<std::endl;
1178
1179         // Stop threads (set run=false first so both start stopping)
1180         m_thread.setRun(false);
1181         m_emergethread.setRun(false);
1182         m_thread.stop();
1183         m_emergethread.stop();
1184         
1185         infostream<<"Server: Threads stopped"<<std::endl;
1186 }
1187
1188 void Server::step(float dtime)
1189 {
1190         DSTACK(__FUNCTION_NAME);
1191         // Limit a bit
1192         if(dtime > 2.0)
1193                 dtime = 2.0;
1194         {
1195                 JMutexAutoLock lock(m_step_dtime_mutex);
1196                 m_step_dtime += dtime;
1197         }
1198 }
1199
1200 void Server::AsyncRunStep()
1201 {
1202         DSTACK(__FUNCTION_NAME);
1203         
1204         g_profiler->add("Server::AsyncRunStep (num)", 1);
1205         
1206         float dtime;
1207         {
1208                 JMutexAutoLock lock1(m_step_dtime_mutex);
1209                 dtime = m_step_dtime;
1210         }
1211         
1212         {
1213                 ScopeProfiler sp(g_profiler, "Server: sel and send blocks to clients");
1214                 // Send blocks to clients
1215                 SendBlocks(dtime);
1216         }
1217         
1218         if(dtime < 0.001)
1219                 return;
1220         
1221         g_profiler->add("Server::AsyncRunStep with dtime (num)", 1);
1222
1223         //infostream<<"Server steps "<<dtime<<std::endl;
1224         //infostream<<"Server::AsyncRunStep(): dtime="<<dtime<<std::endl;
1225         
1226         {
1227                 JMutexAutoLock lock1(m_step_dtime_mutex);
1228                 m_step_dtime -= dtime;
1229         }
1230
1231         /*
1232                 Update uptime
1233         */
1234         {
1235                 m_uptime.set(m_uptime.get() + dtime);
1236         }
1237         
1238         {
1239                 // Process connection's timeouts
1240                 JMutexAutoLock lock2(m_con_mutex);
1241                 ScopeProfiler sp(g_profiler, "Server: connection timeout processing");
1242                 m_con.RunTimeouts(dtime);
1243         }
1244         
1245         {
1246                 // This has to be called so that the client list gets synced
1247                 // with the peer list of the connection
1248                 handlePeerChanges();
1249         }
1250
1251         /*
1252                 Update m_time_of_day and overall game time
1253         */
1254         {
1255                 JMutexAutoLock envlock(m_env_mutex);
1256
1257                 m_time_counter += dtime;
1258                 f32 speed = g_settings->getFloat("time_speed") * 24000./(24.*3600);
1259                 u32 units = (u32)(m_time_counter*speed);
1260                 m_time_counter -= (f32)units / speed;
1261                 
1262                 m_env->setTimeOfDay((m_env->getTimeOfDay() + units) % 24000);
1263                 
1264                 //infostream<<"Server: m_time_of_day = "<<m_time_of_day.get()<<std::endl;
1265
1266                 /*
1267                         Send to clients at constant intervals
1268                 */
1269
1270                 m_time_of_day_send_timer -= dtime;
1271                 if(m_time_of_day_send_timer < 0.0)
1272                 {
1273                         m_time_of_day_send_timer = g_settings->getFloat("time_send_interval");
1274
1275                         //JMutexAutoLock envlock(m_env_mutex);
1276                         JMutexAutoLock conlock(m_con_mutex);
1277
1278                         for(core::map<u16, RemoteClient*>::Iterator
1279                                 i = m_clients.getIterator();
1280                                 i.atEnd() == false; i++)
1281                         {
1282                                 RemoteClient *client = i.getNode()->getValue();
1283                                 //Player *player = m_env->getPlayer(client->peer_id);
1284                                 
1285                                 SharedBuffer<u8> data = makePacket_TOCLIENT_TIME_OF_DAY(
1286                                                 m_env->getTimeOfDay());
1287                                 // Send as reliable
1288                                 m_con.Send(client->peer_id, 0, data, true);
1289                         }
1290                 }
1291         }
1292
1293         {
1294                 JMutexAutoLock lock(m_env_mutex);
1295                 // Step environment
1296                 ScopeProfiler sp(g_profiler, "SEnv step");
1297                 ScopeProfiler sp2(g_profiler, "SEnv step avg", SPT_AVG);
1298                 m_env->step(dtime);
1299         }
1300                 
1301         const float map_timer_and_unload_dtime = 5.15;
1302         if(m_map_timer_and_unload_interval.step(dtime, map_timer_and_unload_dtime))
1303         {
1304                 JMutexAutoLock lock(m_env_mutex);
1305                 // Run Map's timers and unload unused data
1306                 ScopeProfiler sp(g_profiler, "Server: map timer and unload");
1307                 m_env->getMap().timerUpdate(map_timer_and_unload_dtime,
1308                                 g_settings->getFloat("server_unload_unused_data_timeout"));
1309         }
1310         
1311         /*
1312                 Do background stuff
1313         */
1314         
1315         /*
1316                 Transform liquids
1317         */
1318         m_liquid_transform_timer += dtime;
1319         if(m_liquid_transform_timer >= 1.00)
1320         {
1321                 m_liquid_transform_timer -= 1.00;
1322                 
1323                 JMutexAutoLock lock(m_env_mutex);
1324
1325                 ScopeProfiler sp(g_profiler, "Server: liquid transform");
1326
1327                 core::map<v3s16, MapBlock*> modified_blocks;
1328                 m_env->getMap().transformLiquids(modified_blocks);
1329 #if 0           
1330                 /*
1331                         Update lighting
1332                 */
1333                 core::map<v3s16, MapBlock*> lighting_modified_blocks;
1334                 ServerMap &map = ((ServerMap&)m_env->getMap());
1335                 map.updateLighting(modified_blocks, lighting_modified_blocks);
1336                 
1337                 // Add blocks modified by lighting to modified_blocks
1338                 for(core::map<v3s16, MapBlock*>::Iterator
1339                                 i = lighting_modified_blocks.getIterator();
1340                                 i.atEnd() == false; i++)
1341                 {
1342                         MapBlock *block = i.getNode()->getValue();
1343                         modified_blocks.insert(block->getPos(), block);
1344                 }
1345 #endif
1346                 /*
1347                         Set the modified blocks unsent for all the clients
1348                 */
1349                 
1350                 JMutexAutoLock lock2(m_con_mutex);
1351
1352                 for(core::map<u16, RemoteClient*>::Iterator
1353                                 i = m_clients.getIterator();
1354                                 i.atEnd() == false; i++)
1355                 {
1356                         RemoteClient *client = i.getNode()->getValue();
1357                         
1358                         if(modified_blocks.size() > 0)
1359                         {
1360                                 // Remove block from sent history
1361                                 client->SetBlocksNotSent(modified_blocks);
1362                         }
1363                 }
1364         }
1365
1366         // Periodically print some info
1367         {
1368                 float &counter = m_print_info_timer;
1369                 counter += dtime;
1370                 if(counter >= 30.0)
1371                 {
1372                         counter = 0.0;
1373
1374                         JMutexAutoLock lock2(m_con_mutex);
1375                         
1376                         if(m_clients.size() != 0)
1377                                 infostream<<"Players:"<<std::endl;
1378                         for(core::map<u16, RemoteClient*>::Iterator
1379                                 i = m_clients.getIterator();
1380                                 i.atEnd() == false; i++)
1381                         {
1382                                 //u16 peer_id = i.getNode()->getKey();
1383                                 RemoteClient *client = i.getNode()->getValue();
1384                                 Player *player = m_env->getPlayer(client->peer_id);
1385                                 if(player==NULL)
1386                                         continue;
1387                                 infostream<<"* "<<player->getName()<<"\t";
1388                                 client->PrintInfo(infostream);
1389                         }
1390                 }
1391         }
1392
1393         //if(g_settings->getBool("enable_experimental"))
1394         {
1395
1396         /*
1397                 Check added and deleted active objects
1398         */
1399         {
1400                 //infostream<<"Server: Checking added and deleted active objects"<<std::endl;
1401                 JMutexAutoLock envlock(m_env_mutex);
1402                 JMutexAutoLock conlock(m_con_mutex);
1403
1404                 ScopeProfiler sp(g_profiler, "Server: checking added and deleted objs");
1405
1406                 // Radius inside which objects are active
1407                 s16 radius = g_settings->getS16("active_object_send_range_blocks");
1408                 radius *= MAP_BLOCKSIZE;
1409
1410                 for(core::map<u16, RemoteClient*>::Iterator
1411                         i = m_clients.getIterator();
1412                         i.atEnd() == false; i++)
1413                 {
1414                         RemoteClient *client = i.getNode()->getValue();
1415                         Player *player = m_env->getPlayer(client->peer_id);
1416                         if(player==NULL)
1417                         {
1418                                 // This can happen if the client timeouts somehow
1419                                 /*infostream<<"WARNING: "<<__FUNCTION_NAME<<": Client "
1420                                                 <<client->peer_id
1421                                                 <<" has no associated player"<<std::endl;*/
1422                                 continue;
1423                         }
1424                         v3s16 pos = floatToInt(player->getPosition(), BS);
1425
1426                         core::map<u16, bool> removed_objects;
1427                         core::map<u16, bool> added_objects;
1428                         m_env->getRemovedActiveObjects(pos, radius,
1429                                         client->m_known_objects, removed_objects);
1430                         m_env->getAddedActiveObjects(pos, radius,
1431                                         client->m_known_objects, added_objects);
1432                         
1433                         // Ignore if nothing happened
1434                         if(removed_objects.size() == 0 && added_objects.size() == 0)
1435                         {
1436                                 //infostream<<"active objects: none changed"<<std::endl;
1437                                 continue;
1438                         }
1439                         
1440                         std::string data_buffer;
1441
1442                         char buf[4];
1443                         
1444                         // Handle removed objects
1445                         writeU16((u8*)buf, removed_objects.size());
1446                         data_buffer.append(buf, 2);
1447                         for(core::map<u16, bool>::Iterator
1448                                         i = removed_objects.getIterator();
1449                                         i.atEnd()==false; i++)
1450                         {
1451                                 // Get object
1452                                 u16 id = i.getNode()->getKey();
1453                                 ServerActiveObject* obj = m_env->getActiveObject(id);
1454
1455                                 // Add to data buffer for sending
1456                                 writeU16((u8*)buf, i.getNode()->getKey());
1457                                 data_buffer.append(buf, 2);
1458                                 
1459                                 // Remove from known objects
1460                                 client->m_known_objects.remove(i.getNode()->getKey());
1461
1462                                 if(obj && obj->m_known_by_count > 0)
1463                                         obj->m_known_by_count--;
1464                         }
1465
1466                         // Handle added objects
1467                         writeU16((u8*)buf, added_objects.size());
1468                         data_buffer.append(buf, 2);
1469                         for(core::map<u16, bool>::Iterator
1470                                         i = added_objects.getIterator();
1471                                         i.atEnd()==false; i++)
1472                         {
1473                                 // Get object
1474                                 u16 id = i.getNode()->getKey();
1475                                 ServerActiveObject* obj = m_env->getActiveObject(id);
1476                                 
1477                                 // Get object type
1478                                 u8 type = ACTIVEOBJECT_TYPE_INVALID;
1479                                 if(obj == NULL)
1480                                         infostream<<"WARNING: "<<__FUNCTION_NAME
1481                                                         <<": NULL object"<<std::endl;
1482                                 else
1483                                         type = obj->getType();
1484
1485                                 // Add to data buffer for sending
1486                                 writeU16((u8*)buf, id);
1487                                 data_buffer.append(buf, 2);
1488                                 writeU8((u8*)buf, type);
1489                                 data_buffer.append(buf, 1);
1490                                 
1491                                 if(obj)
1492                                         data_buffer.append(serializeLongString(
1493                                                         obj->getClientInitializationData()));
1494                                 else
1495                                         data_buffer.append(serializeLongString(""));
1496
1497                                 // Add to known objects
1498                                 client->m_known_objects.insert(i.getNode()->getKey(), false);
1499
1500                                 if(obj)
1501                                         obj->m_known_by_count++;
1502                         }
1503
1504                         // Send packet
1505                         SharedBuffer<u8> reply(2 + data_buffer.size());
1506                         writeU16(&reply[0], TOCLIENT_ACTIVE_OBJECT_REMOVE_ADD);
1507                         memcpy((char*)&reply[2], data_buffer.c_str(),
1508                                         data_buffer.size());
1509                         // Send as reliable
1510                         m_con.Send(client->peer_id, 0, reply, true);
1511
1512                         infostream<<"Server: Sent object remove/add: "
1513                                         <<removed_objects.size()<<" removed, "
1514                                         <<added_objects.size()<<" added, "
1515                                         <<"packet size is "<<reply.getSize()<<std::endl;
1516                 }
1517
1518 #if 0
1519                 /*
1520                         Collect a list of all the objects known by the clients
1521                         and report it back to the environment.
1522                 */
1523
1524                 core::map<u16, bool> all_known_objects;
1525
1526                 for(core::map<u16, RemoteClient*>::Iterator
1527                         i = m_clients.getIterator();
1528                         i.atEnd() == false; i++)
1529                 {
1530                         RemoteClient *client = i.getNode()->getValue();
1531                         // Go through all known objects of client
1532                         for(core::map<u16, bool>::Iterator
1533                                         i = client->m_known_objects.getIterator();
1534                                         i.atEnd()==false; i++)
1535                         {
1536                                 u16 id = i.getNode()->getKey();
1537                                 all_known_objects[id] = true;
1538                         }
1539                 }
1540                 
1541                 m_env->setKnownActiveObjects(whatever);
1542 #endif
1543
1544         }
1545
1546         /*
1547                 Send object messages
1548         */
1549         {
1550                 JMutexAutoLock envlock(m_env_mutex);
1551                 JMutexAutoLock conlock(m_con_mutex);
1552
1553                 //ScopeProfiler sp(g_profiler, "Server: sending object messages");
1554
1555                 // Key = object id
1556                 // Value = data sent by object
1557                 core::map<u16, core::list<ActiveObjectMessage>* > buffered_messages;
1558
1559                 // Get active object messages from environment
1560                 for(;;)
1561                 {
1562                         ActiveObjectMessage aom = m_env->getActiveObjectMessage();
1563                         if(aom.id == 0)
1564                                 break;
1565                         
1566                         core::list<ActiveObjectMessage>* message_list = NULL;
1567                         core::map<u16, core::list<ActiveObjectMessage>* >::Node *n;
1568                         n = buffered_messages.find(aom.id);
1569                         if(n == NULL)
1570                         {
1571                                 message_list = new core::list<ActiveObjectMessage>;
1572                                 buffered_messages.insert(aom.id, message_list);
1573                         }
1574                         else
1575                         {
1576                                 message_list = n->getValue();
1577                         }
1578                         message_list->push_back(aom);
1579                 }
1580                 
1581                 // Route data to every client
1582                 for(core::map<u16, RemoteClient*>::Iterator
1583                         i = m_clients.getIterator();
1584                         i.atEnd()==false; i++)
1585                 {
1586                         RemoteClient *client = i.getNode()->getValue();
1587                         std::string reliable_data;
1588                         std::string unreliable_data;
1589                         // Go through all objects in message buffer
1590                         for(core::map<u16, core::list<ActiveObjectMessage>* >::Iterator
1591                                         j = buffered_messages.getIterator();
1592                                         j.atEnd()==false; j++)
1593                         {
1594                                 // If object is not known by client, skip it
1595                                 u16 id = j.getNode()->getKey();
1596                                 if(client->m_known_objects.find(id) == NULL)
1597                                         continue;
1598                                 // Get message list of object
1599                                 core::list<ActiveObjectMessage>* list = j.getNode()->getValue();
1600                                 // Go through every message
1601                                 for(core::list<ActiveObjectMessage>::Iterator
1602                                                 k = list->begin(); k != list->end(); k++)
1603                                 {
1604                                         // Compose the full new data with header
1605                                         ActiveObjectMessage aom = *k;
1606                                         std::string new_data;
1607                                         // Add object id
1608                                         char buf[2];
1609                                         writeU16((u8*)&buf[0], aom.id);
1610                                         new_data.append(buf, 2);
1611                                         // Add data
1612                                         new_data += serializeString(aom.datastring);
1613                                         // Add data to buffer
1614                                         if(aom.reliable)
1615                                                 reliable_data += new_data;
1616                                         else
1617                                                 unreliable_data += new_data;
1618                                 }
1619                         }
1620                         /*
1621                                 reliable_data and unreliable_data are now ready.
1622                                 Send them.
1623                         */
1624                         if(reliable_data.size() > 0)
1625                         {
1626                                 SharedBuffer<u8> reply(2 + reliable_data.size());
1627                                 writeU16(&reply[0], TOCLIENT_ACTIVE_OBJECT_MESSAGES);
1628                                 memcpy((char*)&reply[2], reliable_data.c_str(),
1629                                                 reliable_data.size());
1630                                 // Send as reliable
1631                                 m_con.Send(client->peer_id, 0, reply, true);
1632                         }
1633                         if(unreliable_data.size() > 0)
1634                         {
1635                                 SharedBuffer<u8> reply(2 + unreliable_data.size());
1636                                 writeU16(&reply[0], TOCLIENT_ACTIVE_OBJECT_MESSAGES);
1637                                 memcpy((char*)&reply[2], unreliable_data.c_str(),
1638                                                 unreliable_data.size());
1639                                 // Send as unreliable
1640                                 m_con.Send(client->peer_id, 0, reply, false);
1641                         }
1642
1643                         /*if(reliable_data.size() > 0 || unreliable_data.size() > 0)
1644                         {
1645                                 infostream<<"Server: Size of object message data: "
1646                                                 <<"reliable: "<<reliable_data.size()
1647                                                 <<", unreliable: "<<unreliable_data.size()
1648                                                 <<std::endl;
1649                         }*/
1650                 }
1651
1652                 // Clear buffered_messages
1653                 for(core::map<u16, core::list<ActiveObjectMessage>* >::Iterator
1654                                 i = buffered_messages.getIterator();
1655                                 i.atEnd()==false; i++)
1656                 {
1657                         delete i.getNode()->getValue();
1658                 }
1659         }
1660
1661         } // enable_experimental
1662
1663         /*
1664                 Send queued-for-sending map edit events.
1665         */
1666         {
1667                 // Don't send too many at a time
1668                 //u32 count = 0;
1669
1670                 // Single change sending is disabled if queue size is not small
1671                 bool disable_single_change_sending = false;
1672                 if(m_unsent_map_edit_queue.size() >= 4)
1673                         disable_single_change_sending = true;
1674
1675                 bool got_any_events = false;
1676
1677                 // We'll log the amount of each
1678                 Profiler prof;
1679
1680                 while(m_unsent_map_edit_queue.size() != 0)
1681                 {
1682                         got_any_events = true;
1683
1684                         MapEditEvent* event = m_unsent_map_edit_queue.pop_front();
1685                         
1686                         // Players far away from the change are stored here.
1687                         // Instead of sending the changes, MapBlocks are set not sent
1688                         // for them.
1689                         core::list<u16> far_players;
1690
1691                         if(event->type == MEET_ADDNODE)
1692                         {
1693                                 //infostream<<"Server: MEET_ADDNODE"<<std::endl;
1694                                 prof.add("MEET_ADDNODE", 1);
1695                                 if(disable_single_change_sending)
1696                                         sendAddNode(event->p, event->n, event->already_known_by_peer,
1697                                                         &far_players, 5);
1698                                 else
1699                                         sendAddNode(event->p, event->n, event->already_known_by_peer,
1700                                                         &far_players, 30);
1701                         }
1702                         else if(event->type == MEET_REMOVENODE)
1703                         {
1704                                 //infostream<<"Server: MEET_REMOVENODE"<<std::endl;
1705                                 prof.add("MEET_REMOVENODE", 1);
1706                                 if(disable_single_change_sending)
1707                                         sendRemoveNode(event->p, event->already_known_by_peer,
1708                                                         &far_players, 5);
1709                                 else
1710                                         sendRemoveNode(event->p, event->already_known_by_peer,
1711                                                         &far_players, 30);
1712                         }
1713                         else if(event->type == MEET_BLOCK_NODE_METADATA_CHANGED)
1714                         {
1715                                 infostream<<"Server: MEET_BLOCK_NODE_METADATA_CHANGED"<<std::endl;
1716                                 prof.add("MEET_BLOCK_NODE_METADATA_CHANGED", 1);
1717                                 setBlockNotSent(event->p);
1718                         }
1719                         else if(event->type == MEET_OTHER)
1720                         {
1721                                 infostream<<"Server: MEET_OTHER"<<std::endl;
1722                                 prof.add("MEET_OTHER", 1);
1723                                 for(core::map<v3s16, bool>::Iterator
1724                                                 i = event->modified_blocks.getIterator();
1725                                                 i.atEnd()==false; i++)
1726                                 {
1727                                         v3s16 p = i.getNode()->getKey();
1728                                         setBlockNotSent(p);
1729                                 }
1730                         }
1731                         else
1732                         {
1733                                 prof.add("unknown", 1);
1734                                 infostream<<"WARNING: Server: Unknown MapEditEvent "
1735                                                 <<((u32)event->type)<<std::endl;
1736                         }
1737                         
1738                         /*
1739                                 Set blocks not sent to far players
1740                         */
1741                         if(far_players.size() > 0)
1742                         {
1743                                 // Convert list format to that wanted by SetBlocksNotSent
1744                                 core::map<v3s16, MapBlock*> modified_blocks2;
1745                                 for(core::map<v3s16, bool>::Iterator
1746                                                 i = event->modified_blocks.getIterator();
1747                                                 i.atEnd()==false; i++)
1748                                 {
1749                                         v3s16 p = i.getNode()->getKey();
1750                                         modified_blocks2.insert(p,
1751                                                         m_env->getMap().getBlockNoCreateNoEx(p));
1752                                 }
1753                                 // Set blocks not sent
1754                                 for(core::list<u16>::Iterator
1755                                                 i = far_players.begin();
1756                                                 i != far_players.end(); i++)
1757                                 {
1758                                         u16 peer_id = *i;
1759                                         RemoteClient *client = getClient(peer_id);
1760                                         if(client==NULL)
1761                                                 continue;
1762                                         client->SetBlocksNotSent(modified_blocks2);
1763                                 }
1764                         }
1765
1766                         delete event;
1767
1768                         /*// Don't send too many at a time
1769                         count++;
1770                         if(count >= 1 && m_unsent_map_edit_queue.size() < 100)
1771                                 break;*/
1772                 }
1773
1774                 if(got_any_events)
1775                 {
1776                         infostream<<"Server: MapEditEvents:"<<std::endl;
1777                         prof.print(infostream);
1778                 }
1779                 
1780         }
1781
1782         /*
1783                 Send object positions
1784         */
1785         {
1786                 float &counter = m_objectdata_timer;
1787                 counter += dtime;
1788                 if(counter >= g_settings->getFloat("objectdata_interval"))
1789                 {
1790                         JMutexAutoLock lock1(m_env_mutex);
1791                         JMutexAutoLock lock2(m_con_mutex);
1792
1793                         //ScopeProfiler sp(g_profiler, "Server: sending player positions");
1794
1795                         SendObjectData(counter);
1796
1797                         counter = 0.0;
1798                 }
1799         }
1800         
1801         /*
1802                 Trigger emergethread (it somehow gets to a non-triggered but
1803                 bysy state sometimes)
1804         */
1805         {
1806                 float &counter = m_emergethread_trigger_timer;
1807                 counter += dtime;
1808                 if(counter >= 2.0)
1809                 {
1810                         counter = 0.0;
1811                         
1812                         m_emergethread.trigger();
1813                 }
1814         }
1815
1816         // Save map, players and auth stuff
1817         {
1818                 float &counter = m_savemap_timer;
1819                 counter += dtime;
1820                 if(counter >= g_settings->getFloat("server_map_save_interval"))
1821                 {
1822                         counter = 0.0;
1823
1824                         ScopeProfiler sp(g_profiler, "Server: saving stuff");
1825
1826                         // Auth stuff
1827                         if(m_authmanager.isModified())
1828                                 m_authmanager.save();
1829
1830                         //Bann stuff
1831                         if(m_banmanager.isModified())
1832                                 m_banmanager.save();
1833                         
1834                         // Map
1835                         JMutexAutoLock lock(m_env_mutex);
1836
1837                         /*// Unload unused data (delete from memory)
1838                         m_env->getMap().unloadUnusedData(
1839                                         g_settings->getFloat("server_unload_unused_sectors_timeout"));
1840                                         */
1841                         /*u32 deleted_count = m_env->getMap().unloadUnusedData(
1842                                         g_settings->getFloat("server_unload_unused_sectors_timeout"));
1843                                         */
1844
1845                         // Save only changed parts
1846                         m_env->getMap().save(true);
1847
1848                         /*if(deleted_count > 0)
1849                         {
1850                                 infostream<<"Server: Unloaded "<<deleted_count
1851                                                 <<" blocks from memory"<<std::endl;
1852                         }*/
1853
1854                         // Save players
1855                         m_env->serializePlayers(m_mapsavedir);
1856                         
1857                         // Save environment metadata
1858                         m_env->saveMeta(m_mapsavedir);
1859                 }
1860         }
1861 }
1862
1863 void Server::Receive()
1864 {
1865         DSTACK(__FUNCTION_NAME);
1866         SharedBuffer<u8> data;
1867         u16 peer_id;
1868         u32 datasize;
1869         try{
1870                 {
1871                         JMutexAutoLock conlock(m_con_mutex);
1872                         datasize = m_con.Receive(peer_id, data);
1873                 }
1874
1875                 // This has to be called so that the client list gets synced
1876                 // with the peer list of the connection
1877                 handlePeerChanges();
1878
1879                 ProcessData(*data, datasize, peer_id);
1880         }
1881         catch(con::InvalidIncomingDataException &e)
1882         {
1883                 infostream<<"Server::Receive(): "
1884                                 "InvalidIncomingDataException: what()="
1885                                 <<e.what()<<std::endl;
1886         }
1887         catch(con::PeerNotFoundException &e)
1888         {
1889                 //NOTE: This is not needed anymore
1890                 
1891                 // The peer has been disconnected.
1892                 // Find the associated player and remove it.
1893
1894                 /*JMutexAutoLock envlock(m_env_mutex);
1895
1896                 infostream<<"ServerThread: peer_id="<<peer_id
1897                                 <<" has apparently closed connection. "
1898                                 <<"Removing player."<<std::endl;
1899
1900                 m_env->removePlayer(peer_id);*/
1901         }
1902 }
1903
1904 void Server::ProcessData(u8 *data, u32 datasize, u16 peer_id)
1905 {
1906         DSTACK(__FUNCTION_NAME);
1907         // Environment is locked first.
1908         JMutexAutoLock envlock(m_env_mutex);
1909         JMutexAutoLock conlock(m_con_mutex);
1910         
1911         try{
1912                 Address address = m_con.GetPeerAddress(peer_id);
1913
1914                 // drop player if is ip is banned
1915                 if(m_banmanager.isIpBanned(address.serializeString())){
1916                         SendAccessDenied(m_con, peer_id,
1917                                         L"Your ip is banned. Banned name was "
1918                                         +narrow_to_wide(m_banmanager.getBanName(
1919                                                 address.serializeString())));
1920                         m_con.DeletePeer(peer_id);
1921                         return;
1922                 }
1923         }
1924         catch(con::PeerNotFoundException &e)
1925         {
1926                 infostream<<"Server::ProcessData(): Cancelling: peer "
1927                                 <<peer_id<<" not found"<<std::endl;
1928                 return;
1929         }
1930
1931         u8 peer_ser_ver = getClient(peer_id)->serialization_version;
1932
1933         try
1934         {
1935
1936         if(datasize < 2)
1937                 return;
1938
1939         ToServerCommand command = (ToServerCommand)readU16(&data[0]);
1940         
1941         if(command == TOSERVER_INIT)
1942         {
1943                 // [0] u16 TOSERVER_INIT
1944                 // [2] u8 SER_FMT_VER_HIGHEST
1945                 // [3] u8[20] player_name
1946                 // [23] u8[28] password <--- can be sent without this, from old versions
1947
1948                 if(datasize < 2+1+PLAYERNAME_SIZE)
1949                         return;
1950
1951                 infostream<<"Server: Got TOSERVER_INIT from "
1952                                 <<peer_id<<std::endl;
1953
1954                 // First byte after command is maximum supported
1955                 // serialization version
1956                 u8 client_max = data[2];
1957                 u8 our_max = SER_FMT_VER_HIGHEST;
1958                 // Use the highest version supported by both
1959                 u8 deployed = core::min_(client_max, our_max);
1960                 // If it's lower than the lowest supported, give up.
1961                 if(deployed < SER_FMT_VER_LOWEST)
1962                         deployed = SER_FMT_VER_INVALID;
1963
1964                 //peer->serialization_version = deployed;
1965                 getClient(peer_id)->pending_serialization_version = deployed;
1966                 
1967                 if(deployed == SER_FMT_VER_INVALID)
1968                 {
1969                         infostream<<"Server: Cannot negotiate "
1970                                         "serialization version with peer "
1971                                         <<peer_id<<std::endl;
1972                         SendAccessDenied(m_con, peer_id,
1973                                         L"Your client is too old (map format)");
1974                         return;
1975                 }
1976                 
1977                 /*
1978                         Read and check network protocol version
1979                 */
1980
1981                 u16 net_proto_version = 0;
1982                 if(datasize >= 2+1+PLAYERNAME_SIZE+PASSWORD_SIZE+2)
1983                 {
1984                         net_proto_version = readU16(&data[2+1+PLAYERNAME_SIZE+PASSWORD_SIZE]);
1985                 }
1986
1987                 getClient(peer_id)->net_proto_version = net_proto_version;
1988
1989                 if(net_proto_version == 0)
1990                 {
1991                         SendAccessDenied(m_con, peer_id,
1992                                         L"Your client is too old. Please upgrade.");
1993                         return;
1994                 }
1995                 
1996                 /* Uhh... this should actually be a warning but let's do it like this */
1997                 if(g_settings->getBool("strict_protocol_version_checking"))
1998                 {
1999                         if(net_proto_version < PROTOCOL_VERSION)
2000                         {
2001                                 SendAccessDenied(m_con, peer_id,
2002                                                 L"Your client is too old. Please upgrade.");
2003                                 return;
2004                         }
2005                 }
2006
2007                 /*
2008                         Set up player
2009                 */
2010                 
2011                 // Get player name
2012                 char playername[PLAYERNAME_SIZE];
2013                 for(u32 i=0; i<PLAYERNAME_SIZE-1; i++)
2014                 {
2015                         playername[i] = data[3+i];
2016                 }
2017                 playername[PLAYERNAME_SIZE-1] = 0;
2018                 
2019                 if(playername[0]=='\0')
2020                 {
2021                         infostream<<"Server: Player has empty name"<<std::endl;
2022                         SendAccessDenied(m_con, peer_id,
2023                                         L"Empty name");
2024                         return;
2025                 }
2026
2027                 if(string_allowed(playername, PLAYERNAME_ALLOWED_CHARS)==false)
2028                 {
2029                         infostream<<"Server: Player has invalid name"<<std::endl;
2030                         SendAccessDenied(m_con, peer_id,
2031                                         L"Name contains unallowed characters");
2032                         return;
2033                 }
2034
2035                 // Get password
2036                 char password[PASSWORD_SIZE];
2037                 if(datasize < 2+1+PLAYERNAME_SIZE+PASSWORD_SIZE)
2038                 {
2039                         // old version - assume blank password
2040                         password[0] = 0;
2041                 }
2042                 else
2043                 {
2044                                 for(u32 i=0; i<PASSWORD_SIZE-1; i++)
2045                                 {
2046                                         password[i] = data[23+i];
2047                                 }
2048                                 password[PASSWORD_SIZE-1] = 0;
2049                 }
2050                 
2051                 std::string checkpwd;
2052                 if(m_authmanager.exists(playername))
2053                 {
2054                         checkpwd = m_authmanager.getPassword(playername);
2055                 }
2056                 else
2057                 {
2058                         checkpwd = g_settings->get("default_password");
2059                 }
2060                 
2061                 /*infostream<<"Server: Client gave password '"<<password
2062                                 <<"', the correct one is '"<<checkpwd<<"'"<<std::endl;*/
2063                 
2064                 if(password != checkpwd && m_authmanager.exists(playername))
2065                 {
2066                         infostream<<"Server: peer_id="<<peer_id
2067                                         <<": supplied invalid password for "
2068                                         <<playername<<std::endl;
2069                         SendAccessDenied(m_con, peer_id, L"Invalid password");
2070                         return;
2071                 }
2072                 
2073                 // Add player to auth manager
2074                 if(m_authmanager.exists(playername) == false)
2075                 {
2076                         infostream<<"Server: adding player "<<playername
2077                                         <<" to auth manager"<<std::endl;
2078                         m_authmanager.add(playername);
2079                         m_authmanager.setPassword(playername, checkpwd);
2080                         m_authmanager.setPrivs(playername,
2081                                         stringToPrivs(g_settings->get("default_privs")));
2082                         m_authmanager.save();
2083                 }
2084                 
2085                 // Enforce user limit.
2086                 // Don't enforce for users that have some admin right
2087                 if(m_clients.size() >= g_settings->getU16("max_users") &&
2088                                 (m_authmanager.getPrivs(playername)
2089                                         & (PRIV_SERVER|PRIV_BAN|PRIV_PRIVS)) == 0 &&
2090                                 playername != g_settings->get("name"))
2091                 {
2092                         SendAccessDenied(m_con, peer_id, L"Too many users.");
2093                         return;
2094                 }
2095
2096                 // Get player
2097                 Player *player = emergePlayer(playername, password, peer_id);
2098
2099                 // If failed, cancel
2100                 if(player == NULL)
2101                 {
2102                         infostream<<"Server: peer_id="<<peer_id
2103                                         <<": failed to emerge player"<<std::endl;
2104                         return;
2105                 }
2106
2107                 /*
2108                         Answer with a TOCLIENT_INIT
2109                 */
2110                 {
2111                         SharedBuffer<u8> reply(2+1+6+8);
2112                         writeU16(&reply[0], TOCLIENT_INIT);
2113                         writeU8(&reply[2], deployed);
2114                         writeV3S16(&reply[2+1], floatToInt(player->getPosition()+v3f(0,BS/2,0), BS));
2115                         writeU64(&reply[2+1+6], m_env->getServerMap().getSeed());
2116                         
2117                         // Send as reliable
2118                         m_con.Send(peer_id, 0, reply, true);
2119                 }
2120
2121                 /*
2122                         Send complete position information
2123                 */
2124                 SendMovePlayer(player);
2125
2126                 return;
2127         }
2128
2129         if(command == TOSERVER_INIT2)
2130         {
2131                 infostream<<"Server: Got TOSERVER_INIT2 from "
2132                                 <<peer_id<<std::endl;
2133
2134
2135                 getClient(peer_id)->serialization_version
2136                                 = getClient(peer_id)->pending_serialization_version;
2137
2138                 /*
2139                         Send some initialization data
2140                 */
2141
2142                 // Send tool definitions
2143                 SendToolDef(m_con, peer_id, m_toolmgr);
2144                 
2145                 // Send node definitions
2146                 SendNodeDef(m_con, peer_id, m_nodemgr);
2147                 
2148                 // Send textures
2149                 SendTextures(peer_id);
2150                 
2151                 // Send player info to all players
2152                 SendPlayerInfos();
2153
2154                 // Send inventory to player
2155                 UpdateCrafting(peer_id);
2156                 SendInventory(peer_id);
2157
2158                 // Send player items to all players
2159                 SendPlayerItems();
2160
2161                 Player *player = m_env->getPlayer(peer_id);
2162
2163                 // Send HP
2164                 SendPlayerHP(player);
2165                 
2166                 // Send time of day
2167                 {
2168                         SharedBuffer<u8> data = makePacket_TOCLIENT_TIME_OF_DAY(
2169                                         m_env->getTimeOfDay());
2170                         m_con.Send(peer_id, 0, data, true);
2171                 }
2172                 
2173                 // Send information about server to player in chat
2174                 SendChatMessage(peer_id, getStatusString());
2175                 
2176                 // Send information about joining in chat
2177                 {
2178                         std::wstring name = L"unknown";
2179                         Player *player = m_env->getPlayer(peer_id);
2180                         if(player != NULL)
2181                                 name = narrow_to_wide(player->getName());
2182                         
2183                         std::wstring message;
2184                         message += L"*** ";
2185                         message += name;
2186                         message += L" joined game";
2187                         BroadcastChatMessage(message);
2188                 }
2189                 
2190                 // Warnings about protocol version can be issued here
2191                 if(getClient(peer_id)->net_proto_version < PROTOCOL_VERSION)
2192                 {
2193                         SendChatMessage(peer_id, L"# Server: WARNING: YOUR CLIENT IS OLD AND MAY WORK PROPERLY WITH THIS SERVER");
2194                 }
2195
2196                 /*
2197                         Check HP, respawn if necessary
2198                 */
2199                 HandlePlayerHP(player, 0);
2200
2201                 /*
2202                         Print out action
2203                 */
2204                 {
2205                         std::ostringstream os(std::ios_base::binary);
2206                         for(core::map<u16, RemoteClient*>::Iterator
2207                                 i = m_clients.getIterator();
2208                                 i.atEnd() == false; i++)
2209                         {
2210                                 RemoteClient *client = i.getNode()->getValue();
2211                                 assert(client->peer_id == i.getNode()->getKey());
2212                                 if(client->serialization_version == SER_FMT_VER_INVALID)
2213                                         continue;
2214                                 // Get player
2215                                 Player *player = m_env->getPlayer(client->peer_id);
2216                                 if(!player)
2217                                         continue;
2218                                 // Get name of player
2219                                 os<<player->getName()<<" ";
2220                         }
2221
2222                         actionstream<<player->getName()<<" joins game. List of players: "
2223                                         <<os.str()<<std::endl;
2224                 }
2225
2226                 return;
2227         }
2228
2229         if(peer_ser_ver == SER_FMT_VER_INVALID)
2230         {
2231                 infostream<<"Server::ProcessData(): Cancelling: Peer"
2232                                 " serialization format invalid or not initialized."
2233                                 " Skipping incoming command="<<command<<std::endl;
2234                 return;
2235         }
2236         
2237         Player *player = m_env->getPlayer(peer_id);
2238
2239         if(player == NULL){
2240                 infostream<<"Server::ProcessData(): Cancelling: "
2241                                 "No player for peer_id="<<peer_id
2242                                 <<std::endl;
2243                 return;
2244         }
2245         if(command == TOSERVER_PLAYERPOS)
2246         {
2247                 if(datasize < 2+12+12+4+4)
2248                         return;
2249         
2250                 u32 start = 0;
2251                 v3s32 ps = readV3S32(&data[start+2]);
2252                 v3s32 ss = readV3S32(&data[start+2+12]);
2253                 f32 pitch = (f32)readS32(&data[2+12+12]) / 100.0;
2254                 f32 yaw = (f32)readS32(&data[2+12+12+4]) / 100.0;
2255                 v3f position((f32)ps.X/100., (f32)ps.Y/100., (f32)ps.Z/100.);
2256                 v3f speed((f32)ss.X/100., (f32)ss.Y/100., (f32)ss.Z/100.);
2257                 pitch = wrapDegrees(pitch);
2258                 yaw = wrapDegrees(yaw);
2259
2260                 player->setPosition(position);
2261                 player->setSpeed(speed);
2262                 player->setPitch(pitch);
2263                 player->setYaw(yaw);
2264                 
2265                 /*infostream<<"Server::ProcessData(): Moved player "<<peer_id<<" to "
2266                                 <<"("<<position.X<<","<<position.Y<<","<<position.Z<<")"
2267                                 <<" pitch="<<pitch<<" yaw="<<yaw<<std::endl;*/
2268         }
2269         else if(command == TOSERVER_GOTBLOCKS)
2270         {
2271                 if(datasize < 2+1)
2272                         return;
2273                 
2274                 /*
2275                         [0] u16 command
2276                         [2] u8 count
2277                         [3] v3s16 pos_0
2278                         [3+6] v3s16 pos_1
2279                         ...
2280                 */
2281
2282                 u16 count = data[2];
2283                 for(u16 i=0; i<count; i++)
2284                 {
2285                         if((s16)datasize < 2+1+(i+1)*6)
2286                                 throw con::InvalidIncomingDataException
2287                                         ("GOTBLOCKS length is too short");
2288                         v3s16 p = readV3S16(&data[2+1+i*6]);
2289                         /*infostream<<"Server: GOTBLOCKS ("
2290                                         <<p.X<<","<<p.Y<<","<<p.Z<<")"<<std::endl;*/
2291                         RemoteClient *client = getClient(peer_id);
2292                         client->GotBlock(p);
2293                 }
2294         }
2295         else if(command == TOSERVER_DELETEDBLOCKS)
2296         {
2297                 if(datasize < 2+1)
2298                         return;
2299                 
2300                 /*
2301                         [0] u16 command
2302                         [2] u8 count
2303                         [3] v3s16 pos_0
2304                         [3+6] v3s16 pos_1
2305                         ...
2306                 */
2307
2308                 u16 count = data[2];
2309                 for(u16 i=0; i<count; i++)
2310                 {
2311                         if((s16)datasize < 2+1+(i+1)*6)
2312                                 throw con::InvalidIncomingDataException
2313                                         ("DELETEDBLOCKS length is too short");
2314                         v3s16 p = readV3S16(&data[2+1+i*6]);
2315                         /*infostream<<"Server: DELETEDBLOCKS ("
2316                                         <<p.X<<","<<p.Y<<","<<p.Z<<")"<<std::endl;*/
2317                         RemoteClient *client = getClient(peer_id);
2318                         client->SetBlockNotSent(p);
2319                 }
2320         }
2321         else if(command == TOSERVER_CLICK_OBJECT)
2322         {
2323                 infostream<<"Server: CLICK_OBJECT not supported anymore"<<std::endl;
2324                 return;
2325         }
2326         else if(command == TOSERVER_CLICK_ACTIVEOBJECT)
2327         {
2328                 if(datasize < 7)
2329                         return;
2330
2331                 if((getPlayerPrivs(player) & PRIV_BUILD) == 0)
2332                         return;
2333
2334                 /*
2335                         length: 7
2336                         [0] u16 command
2337                         [2] u8 button (0=left, 1=right)
2338                         [3] u16 id
2339                         [5] u16 item
2340                 */
2341                 u8 button = readU8(&data[2]);
2342                 u16 id = readS16(&data[3]);
2343                 u16 item_i = readU16(&data[5]);
2344         
2345                 ServerActiveObject *obj = m_env->getActiveObject(id);
2346
2347                 if(obj == NULL)
2348                 {
2349                         infostream<<"Server: CLICK_ACTIVEOBJECT: object not found"
2350                                         <<std::endl;
2351                         return;
2352                 }
2353
2354                 // Skip if object has been removed
2355                 if(obj->m_removed)
2356                         return;
2357                 
2358                 //TODO: Check that object is reasonably close
2359         
2360                 // Get ServerRemotePlayer
2361                 ServerRemotePlayer *srp = (ServerRemotePlayer*)player;
2362
2363                 // Update wielded item
2364                 srp->wieldItem(item_i);
2365                 
2366                 // Left click, pick/punch
2367                 if(button == 0)
2368                 {
2369                         actionstream<<player->getName()<<" punches object "
2370                                         <<obj->getId()<<std::endl;
2371                         
2372                         // Do stuff
2373                         obj->punch(srp);
2374                         
2375 #if 0
2376                         /*
2377                                 Try creating inventory item
2378                         */
2379                         InventoryItem *item = obj->createPickedUpItem();
2380                         
2381                         if(item)
2382                         {
2383                                 InventoryList *ilist = player->inventory.getList("main");
2384                                 if(ilist != NULL)
2385                                 {
2386                                         actionstream<<player->getName()<<" picked up "
2387                                                         <<item->getName()<<std::endl;
2388                                         if(g_settings->getBool("creative_mode") == false)
2389                                         {
2390                                                 // Skip if inventory has no free space
2391                                                 if(ilist->roomForItem(item) == false)
2392                                                 {
2393                                                         infostream<<"Player inventory has no free space"<<std::endl;
2394                                                         return;
2395                                                 }
2396
2397                                                 // Add to inventory and send inventory
2398                                                 ilist->addItem(item);
2399                                                 UpdateCrafting(player->peer_id);
2400                                                 SendInventory(player->peer_id);
2401                                         }
2402
2403                                         // Remove object from environment
2404                                         obj->m_removed = true;
2405                                 }
2406                         }
2407                         else
2408                         {
2409                                 /*
2410                                         Item cannot be picked up. Punch it instead.
2411                                 */
2412
2413                                 actionstream<<player->getName()<<" punches object "
2414                                                 <<obj->getId()<<std::endl;
2415
2416                                 ToolItem *titem = NULL;
2417                                 std::string toolname = "";
2418
2419                                 InventoryList *mlist = player->inventory.getList("main");
2420                                 if(mlist != NULL)
2421                                 {
2422                                         InventoryItem *item = mlist->getItem(item_i);
2423                                         if(item && (std::string)item->getName() == "ToolItem")
2424                                         {
2425                                                 titem = (ToolItem*)item;
2426                                                 toolname = titem->getToolName();
2427                                         }
2428                                 }
2429
2430                                 v3f playerpos = player->getPosition();
2431                                 v3f objpos = obj->getBasePosition();
2432                                 v3f dir = (objpos - playerpos).normalize();
2433                                 
2434                                 u16 wear = obj->punch(toolname, dir, player->getName());
2435                                 
2436                                 if(titem)
2437                                 {
2438                                         bool weared_out = titem->addWear(wear);
2439                                         if(weared_out)
2440                                                 mlist->deleteItem(item_i);
2441                                         SendInventory(player->peer_id);
2442                                 }
2443                         }
2444 #endif
2445                 }
2446                 // Right click, do something with object
2447                 if(button == 1)
2448                 {
2449                         actionstream<<player->getName()<<" right clicks object "
2450                                         <<obj->getId()<<std::endl;
2451
2452                         // Do stuff
2453                         obj->rightClick(srp);
2454                 }
2455
2456                 /*
2457                         Update player state to client
2458                 */
2459                 SendPlayerHP(player);
2460                 UpdateCrafting(player->peer_id);
2461                 SendInventory(player->peer_id);
2462         }
2463         else if(command == TOSERVER_GROUND_ACTION)
2464         {
2465                 if(datasize < 17)
2466                         return;
2467                 /*
2468                         length: 17
2469                         [0] u16 command
2470                         [2] u8 action
2471                         [3] v3s16 nodepos_undersurface
2472                         [9] v3s16 nodepos_abovesurface
2473                         [15] u16 item
2474                         actions:
2475                         0: start digging
2476                         1: place block
2477                         2: stop digging (all parameters ignored)
2478                         3: digging completed
2479                 */
2480                 u8 action = readU8(&data[2]);
2481                 v3s16 p_under;
2482                 p_under.X = readS16(&data[3]);
2483                 p_under.Y = readS16(&data[5]);
2484                 p_under.Z = readS16(&data[7]);
2485                 v3s16 p_over;
2486                 p_over.X = readS16(&data[9]);
2487                 p_over.Y = readS16(&data[11]);
2488                 p_over.Z = readS16(&data[13]);
2489                 u16 item_i = readU16(&data[15]);
2490
2491                 //TODO: Check that target is reasonably close
2492                 
2493                 /*
2494                         0: start digging
2495                 */
2496                 if(action == 0)
2497                 {
2498                         /*
2499                                 NOTE: This can be used in the future to check if
2500                                 somebody is cheating, by checking the timing.
2501                         */
2502                 } // action == 0
2503
2504                 /*
2505                         2: stop digging
2506                 */
2507                 else if(action == 2)
2508                 {
2509 #if 0
2510                         RemoteClient *client = getClient(peer_id);
2511                         JMutexAutoLock digmutex(client->m_dig_mutex);
2512                         client->m_dig_tool_item = -1;
2513 #endif
2514                 }
2515
2516                 /*
2517                         3: Digging completed
2518                 */
2519                 else if(action == 3)
2520                 {
2521                         // Mandatory parameter; actually used for nothing
2522                         core::map<v3s16, MapBlock*> modified_blocks;
2523
2524                         content_t material = CONTENT_IGNORE;
2525                         u8 mineral = MINERAL_NONE;
2526
2527                         bool cannot_remove_node = false;
2528
2529                         try
2530                         {
2531                                 MapNode n = m_env->getMap().getNode(p_under);
2532                                 // Get mineral
2533                                 mineral = n.getMineral(m_nodemgr);
2534                                 // Get material at position
2535                                 material = n.getContent();
2536                                 // If not yet cancelled
2537                                 if(cannot_remove_node == false)
2538                                 {
2539                                         // If it's not diggable, do nothing
2540                                         if(m_nodemgr->get(material).diggable == false)
2541                                         {
2542                                                 infostream<<"Server: Not finishing digging: "
2543                                                                 <<"Node not diggable"
2544                                                                 <<std::endl;
2545                                                 cannot_remove_node = true;
2546                                         }
2547                                 }
2548                                 // If not yet cancelled
2549                                 if(cannot_remove_node == false)
2550                                 {
2551                                         // Get node metadata
2552                                         NodeMetadata *meta = m_env->getMap().getNodeMetadata(p_under);
2553                                         if(meta && meta->nodeRemovalDisabled() == true)
2554                                         {
2555                                                 infostream<<"Server: Not finishing digging: "
2556                                                                 <<"Node metadata disables removal"
2557                                                                 <<std::endl;
2558                                                 cannot_remove_node = true;
2559                                         }
2560                                 }
2561                         }
2562                         catch(InvalidPositionException &e)
2563                         {
2564                                 infostream<<"Server: Not finishing digging: Node not found."
2565                                                 <<" Adding block to emerge queue."
2566                                                 <<std::endl;
2567                                 m_emerge_queue.addBlock(peer_id,
2568                                                 getNodeBlockPos(p_over), BLOCK_EMERGE_FLAG_FROMDISK);
2569                                 cannot_remove_node = true;
2570                         }
2571
2572                         // Make sure the player is allowed to do it
2573                         if((getPlayerPrivs(player) & PRIV_BUILD) == 0)
2574                         {
2575                                 infostream<<"Player "<<player->getName()<<" cannot remove node"
2576                                                 <<" because privileges are "<<getPlayerPrivs(player)
2577                                                 <<std::endl;
2578                                 cannot_remove_node = true;
2579                         }
2580
2581                         /*
2582                                 If node can't be removed, set block to be re-sent to
2583                                 client and quit.
2584                         */
2585                         if(cannot_remove_node)
2586                         {
2587                                 infostream<<"Server: Not finishing digging."<<std::endl;
2588
2589                                 // Client probably has wrong data.
2590                                 // Set block not sent, so that client will get
2591                                 // a valid one.
2592                                 infostream<<"Client "<<peer_id<<" tried to dig "
2593                                                 <<"node; but node cannot be removed."
2594                                                 <<" setting MapBlock not sent."<<std::endl;
2595                                 RemoteClient *client = getClient(peer_id);
2596                                 v3s16 blockpos = getNodeBlockPos(p_under);
2597                                 client->SetBlockNotSent(blockpos);
2598                                         
2599                                 return;
2600                         }
2601                         
2602                         actionstream<<player->getName()<<" digs "<<PP(p_under)
2603                                         <<", gets material "<<(int)material<<", mineral "
2604                                         <<(int)mineral<<std::endl;
2605                         
2606                         /*
2607                                 Send the removal to all close-by players.
2608                                 - If other player is close, send REMOVENODE
2609                                 - Otherwise set blocks not sent
2610                         */
2611                         core::list<u16> far_players;
2612                         sendRemoveNode(p_under, peer_id, &far_players, 30);
2613                         
2614                         /*
2615                                 Update and send inventory
2616                         */
2617
2618                         if(g_settings->getBool("creative_mode") == false)
2619                         {
2620                                 /*
2621                                         Wear out tool
2622                                 */
2623                                 InventoryList *mlist = player->inventory.getList("main");
2624                                 if(mlist != NULL)
2625                                 {
2626                                         InventoryItem *item = mlist->getItem(item_i);
2627                                         if(item && (std::string)item->getName() == "ToolItem")
2628                                         {
2629                                                 ToolItem *titem = (ToolItem*)item;
2630                                                 std::string toolname = titem->getToolName();
2631
2632                                                 // Get digging properties for material and tool
2633                                                 ToolDiggingProperties tp =
2634                                                                 m_toolmgr->getDiggingProperties(toolname);
2635                                                 DiggingProperties prop =
2636                                                                 getDiggingProperties(material, &tp, m_nodemgr);
2637
2638                                                 if(prop.diggable == false)
2639                                                 {
2640                                                         infostream<<"Server: WARNING: Player digged"
2641                                                                         <<" with impossible material + tool"
2642                                                                         <<" combination"<<std::endl;
2643                                                 }
2644                                                 
2645                                                 bool weared_out = titem->addWear(prop.wear);
2646
2647                                                 if(weared_out)
2648                                                 {
2649                                                         mlist->deleteItem(item_i);
2650                                                 }
2651                                         }
2652                                 }
2653
2654                                 /*
2655                                         Add dug item to inventory
2656                                 */
2657
2658                                 InventoryItem *item = NULL;
2659
2660                                 if(mineral != MINERAL_NONE)
2661                                         item = getDiggedMineralItem(mineral, this);
2662                                 
2663                                 // If not mineral
2664                                 if(item == NULL)
2665                                 {
2666                                         const std::string &dug_s = m_nodemgr->get(material).dug_item;
2667                                         if(dug_s != "")
2668                                         {
2669                                                 std::istringstream is(dug_s, std::ios::binary);
2670                                                 item = InventoryItem::deSerialize(is, this);
2671                                         }
2672                                 }
2673                                 
2674                                 if(item != NULL)
2675                                 {
2676                                         // Add a item to inventory
2677                                         player->inventory.addItem("main", item);
2678
2679                                         // Send inventory
2680                                         UpdateCrafting(player->peer_id);
2681                                         SendInventory(player->peer_id);
2682                                 }
2683
2684                                 item = NULL;
2685
2686                                 if(mineral != MINERAL_NONE)
2687                                   item = getDiggedMineralItem(mineral, this);
2688                         
2689                                 // If not mineral
2690                                 if(item == NULL)
2691                                 {
2692                                         const std::string &extra_dug_s = m_nodemgr->get(material).extra_dug_item;
2693                                         s32 extra_rarity = m_nodemgr->get(material).extra_dug_item_rarity;
2694                                         if(extra_dug_s != "" && extra_rarity != 0
2695                                            && myrand() % extra_rarity == 0)
2696                                         {
2697                                                 std::istringstream is(extra_dug_s, std::ios::binary);
2698                                                 item = InventoryItem::deSerialize(is, this);
2699                                         }
2700                                 }
2701                         
2702                                 if(item != NULL)
2703                                 {
2704                                         // Add a item to inventory
2705                                         player->inventory.addItem("main", item);
2706
2707                                         // Send inventory
2708                                         UpdateCrafting(player->peer_id);
2709                                         SendInventory(player->peer_id);
2710                                 }
2711                         }
2712
2713                         /*
2714                                 Remove the node
2715                                 (this takes some time so it is done after the quick stuff)
2716                         */
2717                         {
2718                                 MapEditEventIgnorer ign(&m_ignore_map_edit_events);
2719
2720                                 m_env->getMap().removeNodeAndUpdate(p_under, modified_blocks);
2721                         }
2722                         /*
2723                                 Set blocks not sent to far players
2724                         */
2725                         for(core::list<u16>::Iterator
2726                                         i = far_players.begin();
2727                                         i != far_players.end(); i++)
2728                         {
2729                                 u16 peer_id = *i;
2730                                 RemoteClient *client = getClient(peer_id);
2731                                 if(client==NULL)
2732                                         continue;
2733                                 client->SetBlocksNotSent(modified_blocks);
2734                         }
2735                 }
2736                 
2737                 /*
2738                         1: place block
2739                 */
2740                 else if(action == 1)
2741                 {
2742
2743                         InventoryList *ilist = player->inventory.getList("main");
2744                         if(ilist == NULL)
2745                                 return;
2746
2747                         // Get item
2748                         InventoryItem *item = ilist->getItem(item_i);
2749                         
2750                         // If there is no item, it is not possible to add it anywhere
2751                         if(item == NULL)
2752                                 return;
2753                         
2754                         /*
2755                                 Handle material items
2756                         */
2757                         if(std::string("MaterialItem") == item->getName())
2758                         {
2759                                 try{
2760                                         // Don't add a node if this is not a free space
2761                                         MapNode n2 = m_env->getMap().getNode(p_over);
2762                                         bool no_enough_privs =
2763                                                         ((getPlayerPrivs(player) & PRIV_BUILD)==0);
2764                                         if(no_enough_privs)
2765                                                 infostream<<"Player "<<player->getName()<<" cannot add node"
2766                                                         <<" because privileges are "<<getPlayerPrivs(player)
2767                                                         <<std::endl;
2768
2769                                         if(m_nodemgr->get(n2).buildable_to == false
2770                                                 || no_enough_privs)
2771                                         {
2772                                                 // Client probably has wrong data.
2773                                                 // Set block not sent, so that client will get
2774                                                 // a valid one.
2775                                                 infostream<<"Client "<<peer_id<<" tried to place"
2776                                                                 <<" node in invalid position; setting"
2777                                                                 <<" MapBlock not sent."<<std::endl;
2778                                                 RemoteClient *client = getClient(peer_id);
2779                                                 v3s16 blockpos = getNodeBlockPos(p_over);
2780                                                 client->SetBlockNotSent(blockpos);
2781                                                 return;
2782                                         }
2783                                 }
2784                                 catch(InvalidPositionException &e)
2785                                 {
2786                                         infostream<<"Server: Ignoring ADDNODE: Node not found"
2787                                                         <<" Adding block to emerge queue."
2788                                                         <<std::endl;
2789                                         m_emerge_queue.addBlock(peer_id,
2790                                                         getNodeBlockPos(p_over), BLOCK_EMERGE_FLAG_FROMDISK);
2791                                         return;
2792                                 }
2793
2794                                 // Reset build time counter
2795                                 getClient(peer_id)->m_time_from_building = 0.0;
2796                                 
2797                                 // Create node data
2798                                 MaterialItem *mitem = (MaterialItem*)item;
2799                                 MapNode n;
2800                                 n.setContent(mitem->getMaterial());
2801
2802                                 actionstream<<player->getName()<<" places material "
2803                                                 <<(int)mitem->getMaterial()
2804                                                 <<" at "<<PP(p_under)<<std::endl;
2805                         
2806                                 // Calculate direction for wall mounted stuff
2807                                 if(m_nodemgr->get(n).wall_mounted)
2808                                         n.param2 = packDir(p_under - p_over);
2809
2810                                 // Calculate the direction for furnaces and chests and stuff
2811                                 if(m_nodemgr->get(n).param_type == CPT_FACEDIR_SIMPLE)
2812                                 {
2813                                         v3f playerpos = player->getPosition();
2814                                         v3f blockpos = intToFloat(p_over, BS) - playerpos;
2815                                         blockpos = blockpos.normalize();
2816                                         n.param1 = 0;
2817                                         if (fabs(blockpos.X) > fabs(blockpos.Z)) {
2818                                                 if (blockpos.X < 0)
2819                                                         n.param1 = 3;
2820                                                 else
2821                                                         n.param1 = 1;
2822                                         } else {
2823                                                 if (blockpos.Z < 0)
2824                                                         n.param1 = 2;
2825                                                 else
2826                                                         n.param1 = 0;
2827                                         }
2828                                 }
2829
2830                                 /*
2831                                         Send to all close-by players
2832                                 */
2833                                 core::list<u16> far_players;
2834                                 sendAddNode(p_over, n, 0, &far_players, 30);
2835                                 
2836                                 /*
2837                                         Handle inventory
2838                                 */
2839                                 InventoryList *ilist = player->inventory.getList("main");
2840                                 if(g_settings->getBool("creative_mode") == false && ilist)
2841                                 {
2842                                         // Remove from inventory and send inventory
2843                                         if(mitem->getCount() == 1)
2844                                                 ilist->deleteItem(item_i);
2845                                         else
2846                                                 mitem->remove(1);
2847                                         // Send inventory
2848                                         UpdateCrafting(peer_id);
2849                                         SendInventory(peer_id);
2850                                 }
2851                                 
2852                                 /*
2853                                         Add node.
2854
2855                                         This takes some time so it is done after the quick stuff
2856                                 */
2857                                 core::map<v3s16, MapBlock*> modified_blocks;
2858                                 {
2859                                         MapEditEventIgnorer ign(&m_ignore_map_edit_events);
2860
2861                                         std::string p_name = std::string(player->getName());
2862                                         m_env->getMap().addNodeAndUpdate(p_over, n, modified_blocks, p_name);
2863                                 }
2864                                 /*
2865                                         Set blocks not sent to far players
2866                                 */
2867                                 for(core::list<u16>::Iterator
2868                                                 i = far_players.begin();
2869                                                 i != far_players.end(); i++)
2870                                 {
2871                                         u16 peer_id = *i;
2872                                         RemoteClient *client = getClient(peer_id);
2873                                         if(client==NULL)
2874                                                 continue;
2875                                         client->SetBlocksNotSent(modified_blocks);
2876                                 }
2877
2878                                 /*
2879                                         Calculate special events
2880                                 */
2881                                 
2882                                 /*if(n.d == CONTENT_MESE)
2883                                 {
2884                                         u32 count = 0;
2885                                         for(s16 z=-1; z<=1; z++)
2886                                         for(s16 y=-1; y<=1; y++)
2887                                         for(s16 x=-1; x<=1; x++)
2888                                         {
2889                                                 
2890                                         }
2891                                 }*/
2892                         }
2893                         /*
2894                                 Place other item (not a block)
2895                         */
2896                         else
2897                         {
2898                                 v3s16 blockpos = getNodeBlockPos(p_over);
2899                                 
2900                                 /*
2901                                         Check that the block is loaded so that the item
2902                                         can properly be added to the static list too
2903                                 */
2904                                 MapBlock *block = m_env->getMap().getBlockNoCreateNoEx(blockpos);
2905                                 if(block==NULL)
2906                                 {
2907                                         infostream<<"Error while placing object: "
2908                                                         "block not found"<<std::endl;
2909                                         return;
2910                                 }
2911
2912                                 /*
2913                                         If in creative mode, item dropping is disabled unless
2914                                         player has build privileges
2915                                 */
2916                                 if(g_settings->getBool("creative_mode") &&
2917                                         (getPlayerPrivs(player) & PRIV_BUILD) == 0)
2918                                 {
2919                                         infostream<<"Not allowing player to drop item: "
2920                                                         "creative mode and no build privs"<<std::endl;
2921                                         return;
2922                                 }
2923
2924                                 // Calculate a position for it
2925                                 v3f pos = intToFloat(p_over, BS);
2926                                 //pos.Y -= BS*0.45;
2927                                 /*pos.Y -= BS*0.25; // let it drop a bit
2928                                 // Randomize a bit
2929                                 pos.X += BS*0.2*(float)myrand_range(-1000,1000)/1000.0;
2930                                 pos.Z += BS*0.2*(float)myrand_range(-1000,1000)/1000.0;*/
2931
2932                                 /*
2933                                         Create the object
2934                                 */
2935                                 ServerActiveObject *obj = item->createSAO(m_env, 0, pos);
2936
2937                                 if(obj == NULL)
2938                                 {
2939                                         infostream<<"WARNING: item resulted in NULL object, "
2940                                                         <<"not placing onto map"
2941                                                         <<std::endl;
2942                                 }
2943                                 else
2944                                 {
2945                                         actionstream<<player->getName()<<" places "<<item->getName()
2946                                                         <<" at "<<PP(p_over)<<std::endl;
2947                                 
2948                                         // Add the object to the environment
2949                                         m_env->addActiveObject(obj);
2950                                         
2951                                         infostream<<"Placed object"<<std::endl;
2952
2953                                         if(g_settings->getBool("creative_mode") == false)
2954                                         {
2955                                                 // Delete the right amount of items from the slot
2956                                                 u16 dropcount = item->getDropCount();
2957                                                 
2958                                                 // Delete item if all gone
2959                                                 if(item->getCount() <= dropcount)
2960                                                 {
2961                                                         if(item->getCount() < dropcount)
2962                                                                 infostream<<"WARNING: Server: dropped more items"
2963                                                                                 <<" than the slot contains"<<std::endl;
2964                                                         
2965                                                         InventoryList *ilist = player->inventory.getList("main");
2966                                                         if(ilist)
2967                                                                 // Remove from inventory and send inventory
2968                                                                 ilist->deleteItem(item_i);
2969                                                 }
2970                                                 // Else decrement it
2971                                                 else
2972                                                         item->remove(dropcount);
2973                                                 
2974                                                 // Send inventory
2975                                                 UpdateCrafting(peer_id);
2976                                                 SendInventory(peer_id);
2977                                         }
2978                                 }
2979                         }
2980
2981                 } // action == 1
2982
2983                 /*
2984                         Catch invalid actions
2985                 */
2986                 else
2987                 {
2988                         infostream<<"WARNING: Server: Invalid action "
2989                                         <<action<<std::endl;
2990                 }
2991         }
2992 #if 0
2993         else if(command == TOSERVER_RELEASE)
2994         {
2995                 if(datasize < 3)
2996                         return;
2997                 /*
2998                         length: 3
2999                         [0] u16 command
3000                         [2] u8 button
3001                 */
3002                 infostream<<"TOSERVER_RELEASE ignored"<<std::endl;
3003         }
3004 #endif
3005         else if(command == TOSERVER_SIGNTEXT)
3006         {
3007                 infostream<<"Server: TOSERVER_SIGNTEXT not supported anymore"
3008                                 <<std::endl;
3009                 return;
3010         }
3011         else if(command == TOSERVER_SIGNNODETEXT)
3012         {
3013                 if((getPlayerPrivs(player) & PRIV_BUILD) == 0)
3014                         return;
3015                 /*
3016                         u16 command
3017                         v3s16 p
3018                         u16 textlen
3019                         textdata
3020                 */
3021                 std::string datastring((char*)&data[2], datasize-2);
3022                 std::istringstream is(datastring, std::ios_base::binary);
3023                 u8 buf[6];
3024                 // Read stuff
3025                 is.read((char*)buf, 6);
3026                 v3s16 p = readV3S16(buf);
3027                 is.read((char*)buf, 2);
3028                 u16 textlen = readU16(buf);
3029                 std::string text;
3030                 for(u16 i=0; i<textlen; i++)
3031                 {
3032                         is.read((char*)buf, 1);
3033                         text += (char)buf[0];
3034                 }
3035
3036                 NodeMetadata *meta = m_env->getMap().getNodeMetadata(p);
3037                 if(!meta)
3038                         return;
3039                 if(meta->typeId() != CONTENT_SIGN_WALL)
3040                         return;
3041                 SignNodeMetadata *signmeta = (SignNodeMetadata*)meta;
3042                 signmeta->setText(text);
3043                 
3044                 actionstream<<player->getName()<<" writes \""<<text<<"\" to sign "
3045                                 <<" at "<<PP(p)<<std::endl;
3046                                 
3047                 v3s16 blockpos = getNodeBlockPos(p);
3048                 MapBlock *block = m_env->getMap().getBlockNoCreateNoEx(blockpos);
3049                 if(block)
3050                 {
3051                         block->setChangedFlag();
3052                 }
3053
3054                 for(core::map<u16, RemoteClient*>::Iterator
3055                         i = m_clients.getIterator();
3056                         i.atEnd()==false; i++)
3057                 {
3058                         RemoteClient *client = i.getNode()->getValue();
3059                         client->SetBlockNotSent(blockpos);
3060                 }
3061         }
3062         else if(command == TOSERVER_INVENTORY_ACTION)
3063         {
3064                 /*// Ignore inventory changes if in creative mode
3065                 if(g_settings->getBool("creative_mode") == true)
3066                 {
3067                         infostream<<"TOSERVER_INVENTORY_ACTION: ignoring in creative mode"
3068                                         <<std::endl;
3069                         return;
3070                 }*/
3071                 // Strip command and create a stream
3072                 std::string datastring((char*)&data[2], datasize-2);
3073                 infostream<<"TOSERVER_INVENTORY_ACTION: data="<<datastring<<std::endl;
3074                 std::istringstream is(datastring, std::ios_base::binary);
3075                 // Create an action
3076                 InventoryAction *a = InventoryAction::deSerialize(is);
3077                 if(a != NULL)
3078                 {
3079                         // Create context
3080                         InventoryContext c;
3081                         c.current_player = player;
3082
3083                         /*
3084                                 Handle craftresult specially if not in creative mode
3085                         */
3086                         bool disable_action = false;
3087                         if(a->getType() == IACTION_MOVE
3088                                         && g_settings->getBool("creative_mode") == false)
3089                         {
3090                                 IMoveAction *ma = (IMoveAction*)a;
3091                                 if(ma->to_inv == "current_player" &&
3092                                                 ma->from_inv == "current_player")
3093                                 {
3094                                         InventoryList *rlist = player->inventory.getList("craftresult");
3095                                         assert(rlist);
3096                                         InventoryList *clist = player->inventory.getList("craft");
3097                                         assert(clist);
3098                                         InventoryList *mlist = player->inventory.getList("main");
3099                                         assert(mlist);
3100                                         /*
3101                                                 Craftresult is no longer preview if something
3102                                                 is moved into it
3103                                         */
3104                                         if(ma->to_list == "craftresult"
3105                                                         && ma->from_list != "craftresult")
3106                                         {
3107                                                 // If it currently is a preview, remove
3108                                                 // its contents
3109                                                 if(player->craftresult_is_preview)
3110                                                 {
3111                                                         rlist->deleteItem(0);
3112                                                 }
3113                                                 player->craftresult_is_preview = false;
3114                                         }
3115                                         /*
3116                                                 Crafting takes place if this condition is true.
3117                                         */
3118                                         if(player->craftresult_is_preview &&
3119                                                         ma->from_list == "craftresult")
3120                                         {
3121                                                 player->craftresult_is_preview = false;
3122                                                 clist->decrementMaterials(1);
3123                                                 
3124                                                 /* Print out action */
3125                                                 InventoryList *list =
3126                                                                 player->inventory.getList("craftresult");
3127                                                 assert(list);
3128                                                 InventoryItem *item = list->getItem(0);
3129                                                 std::string itemname = "NULL";
3130                                                 if(item)
3131                                                         itemname = item->getName();
3132                                                 actionstream<<player->getName()<<" crafts "
3133                                                                 <<itemname<<std::endl;
3134                                         }
3135                                         /*
3136                                                 If the craftresult is placed on itself, move it to
3137                                                 main inventory instead of doing the action
3138                                         */
3139                                         if(ma->to_list == "craftresult"
3140                                                         && ma->from_list == "craftresult")
3141                                         {
3142                                                 disable_action = true;
3143                                                 
3144                                                 InventoryItem *item1 = rlist->changeItem(0, NULL);
3145                                                 mlist->addItem(item1);
3146                                         }
3147                                 }
3148                                 // Disallow moving items if not allowed to build
3149                                 else if((getPlayerPrivs(player) & PRIV_BUILD) == 0)
3150                                 {
3151                                         return;
3152                                 }
3153                                 // if it's a locking chest, only allow the owner or server admins to move items
3154                                 else if (ma->from_inv != "current_player" && (getPlayerPrivs(player) & PRIV_SERVER) == 0)
3155                                 {
3156                                         Strfnd fn(ma->from_inv);
3157                                         std::string id0 = fn.next(":");
3158                                         if(id0 == "nodemeta")
3159                                         {
3160                                                 v3s16 p;
3161                                                 p.X = stoi(fn.next(","));
3162                                                 p.Y = stoi(fn.next(","));
3163                                                 p.Z = stoi(fn.next(","));
3164                                                 NodeMetadata *meta = m_env->getMap().getNodeMetadata(p);
3165                                                 if(meta && meta->typeId() == CONTENT_LOCKABLE_CHEST) {
3166                                                         LockingChestNodeMetadata *lcm = (LockingChestNodeMetadata*)meta;
3167                                                         if (lcm->getOwner() != player->getName())
3168                                                                 return;
3169                                                 }
3170                                         }
3171                                 }
3172                                 else if (ma->to_inv != "current_player" && (getPlayerPrivs(player) & PRIV_SERVER) == 0)
3173                                 {
3174                                         Strfnd fn(ma->to_inv);
3175                                         std::string id0 = fn.next(":");
3176                                         if(id0 == "nodemeta")
3177                                         {
3178                                                 v3s16 p;
3179                                                 p.X = stoi(fn.next(","));
3180                                                 p.Y = stoi(fn.next(","));
3181                                                 p.Z = stoi(fn.next(","));
3182                                                 NodeMetadata *meta = m_env->getMap().getNodeMetadata(p);
3183                                                 if(meta && meta->typeId() == CONTENT_LOCKABLE_CHEST) {
3184                                                         LockingChestNodeMetadata *lcm = (LockingChestNodeMetadata*)meta;
3185                                                         if (lcm->getOwner() != player->getName())
3186                                                                 return;
3187                                                 }
3188                                         }
3189                                 }
3190                         }
3191                         
3192                         if(disable_action == false)
3193                         {
3194                                 // Feed action to player inventory
3195                                 a->apply(&c, this);
3196                                 // Eat the action
3197                                 delete a;
3198                         }
3199                         else
3200                         {
3201                                 // Send inventory
3202                                 UpdateCrafting(player->peer_id);
3203                                 SendInventory(player->peer_id);
3204                         }
3205                 }
3206                 else
3207                 {
3208                         infostream<<"TOSERVER_INVENTORY_ACTION: "
3209                                         <<"InventoryAction::deSerialize() returned NULL"
3210                                         <<std::endl;
3211                 }
3212         }
3213         else if(command == TOSERVER_CHAT_MESSAGE)
3214         {
3215                 /*
3216                         u16 command
3217                         u16 length
3218                         wstring message
3219                 */
3220                 u8 buf[6];
3221                 std::string datastring((char*)&data[2], datasize-2);
3222                 std::istringstream is(datastring, std::ios_base::binary);
3223                 
3224                 // Read stuff
3225                 is.read((char*)buf, 2);
3226                 u16 len = readU16(buf);
3227                 
3228                 std::wstring message;
3229                 for(u16 i=0; i<len; i++)
3230                 {
3231                         is.read((char*)buf, 2);
3232                         message += (wchar_t)readU16(buf);
3233                 }
3234
3235                 // Get player name of this client
3236                 std::wstring name = narrow_to_wide(player->getName());
3237                 
3238                 // Line to send to players
3239                 std::wstring line;
3240                 // Whether to send to the player that sent the line
3241                 bool send_to_sender = false;
3242                 // Whether to send to other players
3243                 bool send_to_others = false;
3244                 
3245                 // Local player gets all privileges regardless of
3246                 // what's set on their account.
3247                 u64 privs = getPlayerPrivs(player);
3248
3249                 // Parse commands
3250                 if(message[0] == L'/')
3251                 {
3252                         size_t strip_size = 1;
3253                         if (message[1] == L'#') // support old-style commans
3254                                 ++strip_size;
3255                         message = message.substr(strip_size);
3256
3257                         WStrfnd f1(message);
3258                         f1.next(L" "); // Skip over /#whatever
3259                         std::wstring paramstring = f1.next(L"");
3260
3261                         ServerCommandContext *ctx = new ServerCommandContext(
3262                                 str_split(message, L' '),
3263                                 paramstring,
3264                                 this,
3265                                 m_env,
3266                                 player,
3267                                 privs);
3268
3269                         std::wstring reply(processServerCommand(ctx));
3270                         send_to_sender = ctx->flags & SEND_TO_SENDER;
3271                         send_to_others = ctx->flags & SEND_TO_OTHERS;
3272
3273                         if (ctx->flags & SEND_NO_PREFIX)
3274                                 line += reply;
3275                         else
3276                                 line += L"Server: " + reply;
3277
3278                         delete ctx;
3279
3280                 }
3281                 else
3282                 {
3283                         if(privs & PRIV_SHOUT)
3284                         {
3285                                 line += L"<";
3286                                 line += name;
3287                                 line += L"> ";
3288                                 line += message;
3289                                 send_to_others = true;
3290                         }
3291                         else
3292                         {
3293                                 line += L"Server: You are not allowed to shout";
3294                                 send_to_sender = true;
3295                         }
3296                 }
3297                 
3298                 if(line != L"")
3299                 {
3300                         if(send_to_others)
3301                                 actionstream<<"CHAT: "<<wide_to_narrow(line)<<std::endl;
3302
3303                         /*
3304                                 Send the message to clients
3305                         */
3306                         for(core::map<u16, RemoteClient*>::Iterator
3307                                 i = m_clients.getIterator();
3308                                 i.atEnd() == false; i++)
3309                         {
3310                                 // Get client and check that it is valid
3311                                 RemoteClient *client = i.getNode()->getValue();
3312                                 assert(client->peer_id == i.getNode()->getKey());
3313                                 if(client->serialization_version == SER_FMT_VER_INVALID)
3314                                         continue;
3315
3316                                 // Filter recipient
3317                                 bool sender_selected = (peer_id == client->peer_id);
3318                                 if(sender_selected == true && send_to_sender == false)
3319                                         continue;
3320                                 if(sender_selected == false && send_to_others == false)
3321                                         continue;
3322
3323                                 SendChatMessage(client->peer_id, line);
3324                         }
3325                 }
3326         }
3327         else if(command == TOSERVER_DAMAGE)
3328         {
3329                 std::string datastring((char*)&data[2], datasize-2);
3330                 std::istringstream is(datastring, std::ios_base::binary);
3331                 u8 damage = readU8(is);
3332
3333                 if(g_settings->getBool("enable_damage"))
3334                 {
3335                         actionstream<<player->getName()<<" damaged by "
3336                                         <<(int)damage<<" hp at "<<PP(player->getPosition()/BS)
3337                                         <<std::endl;
3338                                 
3339                         HandlePlayerHP(player, damage);
3340                 }
3341                 else
3342                 {
3343                         SendPlayerHP(player);
3344                 }
3345         }
3346         else if(command == TOSERVER_PASSWORD)
3347         {
3348                 /*
3349                         [0] u16 TOSERVER_PASSWORD
3350                         [2] u8[28] old password
3351                         [30] u8[28] new password
3352                 */
3353
3354                 if(datasize != 2+PASSWORD_SIZE*2)
3355                         return;
3356                 /*char password[PASSWORD_SIZE];
3357                 for(u32 i=0; i<PASSWORD_SIZE-1; i++)
3358                         password[i] = data[2+i];
3359                 password[PASSWORD_SIZE-1] = 0;*/
3360                 std::string oldpwd;
3361                 for(u32 i=0; i<PASSWORD_SIZE-1; i++)
3362                 {
3363                         char c = data[2+i];
3364                         if(c == 0)
3365                                 break;
3366                         oldpwd += c;
3367                 }
3368                 std::string newpwd;
3369                 for(u32 i=0; i<PASSWORD_SIZE-1; i++)
3370                 {
3371                         char c = data[2+PASSWORD_SIZE+i];
3372                         if(c == 0)
3373                                 break;
3374                         newpwd += c;
3375                 }
3376
3377                 infostream<<"Server: Client requests a password change from "
3378                                 <<"'"<<oldpwd<<"' to '"<<newpwd<<"'"<<std::endl;
3379
3380                 std::string playername = player->getName();
3381
3382                 if(m_authmanager.exists(playername) == false)
3383                 {
3384                         infostream<<"Server: playername not found in authmanager"<<std::endl;
3385                         // Wrong old password supplied!!
3386                         SendChatMessage(peer_id, L"playername not found in authmanager");
3387                         return;
3388                 }
3389
3390                 std::string checkpwd = m_authmanager.getPassword(playername);
3391
3392                 if(oldpwd != checkpwd)
3393                 {
3394                         infostream<<"Server: invalid old password"<<std::endl;
3395                         // Wrong old password supplied!!
3396                         SendChatMessage(peer_id, L"Invalid old password supplied. Password NOT changed.");
3397                         return;
3398                 }
3399
3400                 actionstream<<player->getName()<<" changes password"<<std::endl;
3401
3402                 m_authmanager.setPassword(playername, newpwd);
3403                 
3404                 infostream<<"Server: password change successful for "<<playername
3405                                 <<std::endl;
3406                 SendChatMessage(peer_id, L"Password change successful");
3407         }
3408         else if(command == TOSERVER_PLAYERITEM)
3409         {
3410                 if (datasize < 2+2)
3411                         return;
3412
3413                 u16 item = readU16(&data[2]);
3414                 player->wieldItem(item);
3415                 SendWieldedItem(player);
3416         }
3417         else if(command == TOSERVER_RESPAWN)
3418         {
3419                 if(player->hp != 0)
3420                         return;
3421                 
3422                 RespawnPlayer(player);
3423                 
3424                 actionstream<<player->getName()<<" respawns at "
3425                                 <<PP(player->getPosition()/BS)<<std::endl;
3426         }
3427         else
3428         {
3429                 infostream<<"Server::ProcessData(): Ignoring "
3430                                 "unknown command "<<command<<std::endl;
3431         }
3432         
3433         } //try
3434         catch(SendFailedException &e)
3435         {
3436                 errorstream<<"Server::ProcessData(): SendFailedException: "
3437                                 <<"what="<<e.what()
3438                                 <<std::endl;
3439         }
3440 }
3441
3442 void Server::onMapEditEvent(MapEditEvent *event)
3443 {
3444         //infostream<<"Server::onMapEditEvent()"<<std::endl;
3445         if(m_ignore_map_edit_events)
3446                 return;
3447         MapEditEvent *e = event->clone();
3448         m_unsent_map_edit_queue.push_back(e);
3449 }
3450
3451 Inventory* Server::getInventory(InventoryContext *c, std::string id)
3452 {
3453         if(id == "current_player")
3454         {
3455                 assert(c->current_player);
3456                 return &(c->current_player->inventory);
3457         }
3458         
3459         Strfnd fn(id);
3460         std::string id0 = fn.next(":");
3461
3462         if(id0 == "nodemeta")
3463         {
3464                 v3s16 p;
3465                 p.X = stoi(fn.next(","));
3466                 p.Y = stoi(fn.next(","));
3467                 p.Z = stoi(fn.next(","));
3468                 NodeMetadata *meta = m_env->getMap().getNodeMetadata(p);
3469                 if(meta)
3470                         return meta->getInventory();
3471                 infostream<<"nodemeta at ("<<p.X<<","<<p.Y<<","<<p.Z<<"): "
3472                                 <<"no metadata found"<<std::endl;
3473                 return NULL;
3474         }
3475
3476         infostream<<__FUNCTION_NAME<<": unknown id "<<id<<std::endl;
3477         return NULL;
3478 }
3479 void Server::inventoryModified(InventoryContext *c, std::string id)
3480 {
3481         if(id == "current_player")
3482         {
3483                 assert(c->current_player);
3484                 // Send inventory
3485                 UpdateCrafting(c->current_player->peer_id);
3486                 SendInventory(c->current_player->peer_id);
3487                 return;
3488         }
3489         
3490         Strfnd fn(id);
3491         std::string id0 = fn.next(":");
3492
3493         if(id0 == "nodemeta")
3494         {
3495                 v3s16 p;
3496                 p.X = stoi(fn.next(","));
3497                 p.Y = stoi(fn.next(","));
3498                 p.Z = stoi(fn.next(","));
3499                 v3s16 blockpos = getNodeBlockPos(p);
3500
3501                 NodeMetadata *meta = m_env->getMap().getNodeMetadata(p);
3502                 if(meta)
3503                         meta->inventoryModified();
3504
3505                 for(core::map<u16, RemoteClient*>::Iterator
3506                         i = m_clients.getIterator();
3507                         i.atEnd()==false; i++)
3508                 {
3509                         RemoteClient *client = i.getNode()->getValue();
3510                         client->SetBlockNotSent(blockpos);
3511                 }
3512
3513                 return;
3514         }
3515
3516         infostream<<__FUNCTION_NAME<<": unknown id "<<id<<std::endl;
3517 }
3518
3519 core::list<PlayerInfo> Server::getPlayerInfo()
3520 {
3521         DSTACK(__FUNCTION_NAME);
3522         JMutexAutoLock envlock(m_env_mutex);
3523         JMutexAutoLock conlock(m_con_mutex);
3524         
3525         core::list<PlayerInfo> list;
3526
3527         core::list<Player*> players = m_env->getPlayers();
3528         
3529         core::list<Player*>::Iterator i;
3530         for(i = players.begin();
3531                         i != players.end(); i++)
3532         {
3533                 PlayerInfo info;
3534
3535                 Player *player = *i;
3536
3537                 try{
3538                         // Copy info from connection to info struct
3539                         info.id = player->peer_id;
3540                         info.address = m_con.GetPeerAddress(player->peer_id);
3541                         info.avg_rtt = m_con.GetPeerAvgRTT(player->peer_id);
3542                 }
3543                 catch(con::PeerNotFoundException &e)
3544                 {
3545                         // Set dummy peer info
3546                         info.id = 0;
3547                         info.address = Address(0,0,0,0,0);
3548                         info.avg_rtt = 0.0;
3549                 }
3550
3551                 snprintf(info.name, PLAYERNAME_SIZE, "%s", player->getName());
3552                 info.position = player->getPosition();
3553
3554                 list.push_back(info);
3555         }
3556
3557         return list;
3558 }
3559
3560
3561 void Server::peerAdded(con::Peer *peer)
3562 {
3563         DSTACK(__FUNCTION_NAME);
3564         infostream<<"Server::peerAdded(): peer->id="
3565                         <<peer->id<<std::endl;
3566         
3567         PeerChange c;
3568         c.type = PEER_ADDED;
3569         c.peer_id = peer->id;
3570         c.timeout = false;
3571         m_peer_change_queue.push_back(c);
3572 }
3573
3574 void Server::deletingPeer(con::Peer *peer, bool timeout)
3575 {
3576         DSTACK(__FUNCTION_NAME);
3577         infostream<<"Server::deletingPeer(): peer->id="
3578                         <<peer->id<<", timeout="<<timeout<<std::endl;
3579         
3580         PeerChange c;
3581         c.type = PEER_REMOVED;
3582         c.peer_id = peer->id;
3583         c.timeout = timeout;
3584         m_peer_change_queue.push_back(c);
3585 }
3586
3587 /*
3588         Static send methods
3589 */
3590
3591 void Server::SendHP(con::Connection &con, u16 peer_id, u8 hp)
3592 {
3593         DSTACK(__FUNCTION_NAME);
3594         std::ostringstream os(std::ios_base::binary);
3595
3596         writeU16(os, TOCLIENT_HP);
3597         writeU8(os, hp);
3598
3599         // Make data buffer
3600         std::string s = os.str();
3601         SharedBuffer<u8> data((u8*)s.c_str(), s.size());
3602         // Send as reliable
3603         con.Send(peer_id, 0, data, true);
3604 }
3605
3606 void Server::SendAccessDenied(con::Connection &con, u16 peer_id,
3607                 const std::wstring &reason)
3608 {
3609         DSTACK(__FUNCTION_NAME);
3610         std::ostringstream os(std::ios_base::binary);
3611
3612         writeU16(os, TOCLIENT_ACCESS_DENIED);
3613         os<<serializeWideString(reason);
3614
3615         // Make data buffer
3616         std::string s = os.str();
3617         SharedBuffer<u8> data((u8*)s.c_str(), s.size());
3618         // Send as reliable
3619         con.Send(peer_id, 0, data, true);
3620 }
3621
3622 void Server::SendDeathscreen(con::Connection &con, u16 peer_id,
3623                 bool set_camera_point_target, v3f camera_point_target)
3624 {
3625         DSTACK(__FUNCTION_NAME);
3626         std::ostringstream os(std::ios_base::binary);
3627
3628         writeU16(os, TOCLIENT_DEATHSCREEN);
3629         writeU8(os, set_camera_point_target);
3630         writeV3F1000(os, camera_point_target);
3631
3632         // Make data buffer
3633         std::string s = os.str();
3634         SharedBuffer<u8> data((u8*)s.c_str(), s.size());
3635         // Send as reliable
3636         con.Send(peer_id, 0, data, true);
3637 }
3638
3639 void Server::SendToolDef(con::Connection &con, u16 peer_id,
3640                 IToolDefManager *tooldef)
3641 {
3642         DSTACK(__FUNCTION_NAME);
3643         infostream<<"Server: Sending tool definitions"<<std::endl;
3644         std::ostringstream os(std::ios_base::binary);
3645
3646         /*
3647                 u16 command
3648                 u32 length of the next item
3649                 serialized ToolDefManager
3650         */
3651         writeU16(os, TOCLIENT_TOOLDEF);
3652         std::ostringstream tmp_os(std::ios::binary);
3653         tooldef->serialize(tmp_os);
3654         os<<serializeLongString(tmp_os.str());
3655
3656         // Make data buffer
3657         std::string s = os.str();
3658         infostream<<"Server: Sending tool definitions: data size: "
3659                         <<s.size()<<std::endl;
3660         SharedBuffer<u8> data((u8*)s.c_str(), s.size());
3661         // Send as reliable
3662         con.Send(peer_id, 0, data, true);
3663 }
3664
3665 void Server::SendNodeDef(con::Connection &con, u16 peer_id,
3666                 INodeDefManager *nodedef)
3667 {
3668         DSTACK(__FUNCTION_NAME);
3669         infostream<<"Server: Sending node definitions"<<std::endl;
3670         std::ostringstream os(std::ios_base::binary);
3671
3672         /*
3673                 u16 command
3674                 u32 length of the next item
3675                 serialized NodeDefManager
3676         */
3677         writeU16(os, TOCLIENT_NODEDEF);
3678         std::ostringstream tmp_os(std::ios::binary);
3679         nodedef->serialize(tmp_os);
3680         os<<serializeLongString(tmp_os.str());
3681
3682         // Make data buffer
3683         std::string s = os.str();
3684         infostream<<"Server: Sending node definitions: data size: "
3685                         <<s.size()<<std::endl;
3686         SharedBuffer<u8> data((u8*)s.c_str(), s.size());
3687         // Send as reliable
3688         con.Send(peer_id, 0, data, true);
3689 }
3690
3691 /*
3692         Non-static send methods
3693 */
3694
3695 void Server::SendObjectData(float dtime)
3696 {
3697         DSTACK(__FUNCTION_NAME);
3698
3699         core::map<v3s16, bool> stepped_blocks;
3700         
3701         for(core::map<u16, RemoteClient*>::Iterator
3702                 i = m_clients.getIterator();
3703                 i.atEnd() == false; i++)
3704         {
3705                 u16 peer_id = i.getNode()->getKey();
3706                 RemoteClient *client = i.getNode()->getValue();
3707                 assert(client->peer_id == peer_id);
3708                 
3709                 if(client->serialization_version == SER_FMT_VER_INVALID)
3710                         continue;
3711                 
3712                 client->SendObjectData(this, dtime, stepped_blocks);
3713         }
3714 }
3715
3716 void Server::SendPlayerInfos()
3717 {
3718         DSTACK(__FUNCTION_NAME);
3719
3720         //JMutexAutoLock envlock(m_env_mutex);
3721         
3722         // Get connected players
3723         core::list<Player*> players = m_env->getPlayers(true);
3724         
3725         u32 player_count = players.getSize();
3726         u32 datasize = 2+(2+PLAYERNAME_SIZE)*player_count;
3727
3728         SharedBuffer<u8> data(datasize);
3729         writeU16(&data[0], TOCLIENT_PLAYERINFO);
3730         
3731         u32 start = 2;
3732         core::list<Player*>::Iterator i;
3733         for(i = players.begin();
3734                         i != players.end(); i++)
3735         {
3736                 Player *player = *i;
3737
3738                 /*infostream<<"Server sending player info for player with "
3739                                 "peer_id="<<player->peer_id<<std::endl;*/
3740                 
3741                 writeU16(&data[start], player->peer_id);
3742                 memset((char*)&data[start+2], 0, PLAYERNAME_SIZE);
3743                 snprintf((char*)&data[start+2], PLAYERNAME_SIZE, "%s", player->getName());
3744                 start += 2+PLAYERNAME_SIZE;
3745         }
3746
3747         //JMutexAutoLock conlock(m_con_mutex);
3748
3749         // Send as reliable
3750         m_con.SendToAll(0, data, true);
3751 }
3752
3753 void Server::SendInventory(u16 peer_id)
3754 {
3755         DSTACK(__FUNCTION_NAME);
3756         
3757         Player* player = m_env->getPlayer(peer_id);
3758         assert(player);
3759
3760         /*
3761                 Serialize it
3762         */
3763
3764         std::ostringstream os;
3765         //os.imbue(std::locale("C"));
3766
3767         player->inventory.serialize(os);
3768
3769         std::string s = os.str();
3770         
3771         SharedBuffer<u8> data(s.size()+2);
3772         writeU16(&data[0], TOCLIENT_INVENTORY);
3773         memcpy(&data[2], s.c_str(), s.size());
3774         
3775         // Send as reliable
3776         m_con.Send(peer_id, 0, data, true);
3777 }
3778
3779 std::string getWieldedItemString(const Player *player)
3780 {
3781         const InventoryItem *item = player->getWieldItem();
3782         if (item == NULL)
3783                 return std::string("");
3784         std::ostringstream os(std::ios_base::binary);
3785         item->serialize(os);
3786         return os.str();
3787 }
3788
3789 void Server::SendWieldedItem(const Player* player)
3790 {
3791         DSTACK(__FUNCTION_NAME);
3792
3793         assert(player);
3794
3795         std::ostringstream os(std::ios_base::binary);
3796
3797         writeU16(os, TOCLIENT_PLAYERITEM);
3798         writeU16(os, 1);
3799         writeU16(os, player->peer_id);
3800         os<<serializeString(getWieldedItemString(player));
3801
3802         // Make data buffer
3803         std::string s = os.str();
3804         SharedBuffer<u8> data((u8*)s.c_str(), s.size());
3805
3806         m_con.SendToAll(0, data, true);
3807 }
3808
3809 void Server::SendPlayerItems()
3810 {
3811         DSTACK(__FUNCTION_NAME);
3812
3813         std::ostringstream os(std::ios_base::binary);
3814         core::list<Player *> players = m_env->getPlayers(true);
3815
3816         writeU16(os, TOCLIENT_PLAYERITEM);
3817         writeU16(os, players.size());
3818         core::list<Player *>::Iterator i;
3819         for(i = players.begin(); i != players.end(); ++i)
3820         {
3821                 Player *p = *i;
3822                 writeU16(os, p->peer_id);
3823                 os<<serializeString(getWieldedItemString(p));
3824         }
3825
3826         // Make data buffer
3827         std::string s = os.str();
3828         SharedBuffer<u8> data((u8*)s.c_str(), s.size());
3829
3830         m_con.SendToAll(0, data, true);
3831 }
3832
3833 void Server::SendChatMessage(u16 peer_id, const std::wstring &message)
3834 {
3835         DSTACK(__FUNCTION_NAME);
3836         
3837         std::ostringstream os(std::ios_base::binary);
3838         u8 buf[12];
3839         
3840         // Write command
3841         writeU16(buf, TOCLIENT_CHAT_MESSAGE);
3842         os.write((char*)buf, 2);
3843         
3844         // Write length
3845         writeU16(buf, message.size());
3846         os.write((char*)buf, 2);
3847         
3848         // Write string
3849         for(u32 i=0; i<message.size(); i++)
3850         {
3851                 u16 w = message[i];
3852                 writeU16(buf, w);
3853                 os.write((char*)buf, 2);
3854         }
3855         
3856         // Make data buffer
3857         std::string s = os.str();
3858         SharedBuffer<u8> data((u8*)s.c_str(), s.size());
3859         // Send as reliable
3860         m_con.Send(peer_id, 0, data, true);
3861 }
3862
3863 void Server::BroadcastChatMessage(const std::wstring &message)
3864 {
3865         for(core::map<u16, RemoteClient*>::Iterator
3866                 i = m_clients.getIterator();
3867                 i.atEnd() == false; i++)
3868         {
3869                 // Get client and check that it is valid
3870                 RemoteClient *client = i.getNode()->getValue();
3871                 assert(client->peer_id == i.getNode()->getKey());
3872                 if(client->serialization_version == SER_FMT_VER_INVALID)
3873                         continue;
3874
3875                 SendChatMessage(client->peer_id, message);
3876         }
3877 }
3878
3879 void Server::SendPlayerHP(Player *player)
3880 {
3881         SendHP(m_con, player->peer_id, player->hp);
3882 }
3883
3884 void Server::SendMovePlayer(Player *player)
3885 {
3886         DSTACK(__FUNCTION_NAME);
3887         std::ostringstream os(std::ios_base::binary);
3888
3889         writeU16(os, TOCLIENT_MOVE_PLAYER);
3890         writeV3F1000(os, player->getPosition());
3891         writeF1000(os, player->getPitch());
3892         writeF1000(os, player->getYaw());
3893         
3894         {
3895                 v3f pos = player->getPosition();
3896                 f32 pitch = player->getPitch();
3897                 f32 yaw = player->getYaw();
3898                 infostream<<"Server sending TOCLIENT_MOVE_PLAYER"
3899                                 <<" pos=("<<pos.X<<","<<pos.Y<<","<<pos.Z<<")"
3900                                 <<" pitch="<<pitch
3901                                 <<" yaw="<<yaw
3902                                 <<std::endl;
3903         }
3904
3905         // Make data buffer
3906         std::string s = os.str();
3907         SharedBuffer<u8> data((u8*)s.c_str(), s.size());
3908         // Send as reliable
3909         m_con.Send(player->peer_id, 0, data, true);
3910 }
3911
3912 void Server::sendRemoveNode(v3s16 p, u16 ignore_id,
3913         core::list<u16> *far_players, float far_d_nodes)
3914 {
3915         float maxd = far_d_nodes*BS;
3916         v3f p_f = intToFloat(p, BS);
3917
3918         // Create packet
3919         u32 replysize = 8;
3920         SharedBuffer<u8> reply(replysize);
3921         writeU16(&reply[0], TOCLIENT_REMOVENODE);
3922         writeS16(&reply[2], p.X);
3923         writeS16(&reply[4], p.Y);
3924         writeS16(&reply[6], p.Z);
3925
3926         for(core::map<u16, RemoteClient*>::Iterator
3927                 i = m_clients.getIterator();
3928                 i.atEnd() == false; i++)
3929         {
3930                 // Get client and check that it is valid
3931                 RemoteClient *client = i.getNode()->getValue();
3932                 assert(client->peer_id == i.getNode()->getKey());
3933                 if(client->serialization_version == SER_FMT_VER_INVALID)
3934                         continue;
3935
3936                 // Don't send if it's the same one
3937                 if(client->peer_id == ignore_id)
3938                         continue;
3939                 
3940                 if(far_players)
3941                 {
3942                         // Get player
3943                         Player *player = m_env->getPlayer(client->peer_id);
3944                         if(player)
3945                         {
3946                                 // If player is far away, only set modified blocks not sent
3947                                 v3f player_pos = player->getPosition();
3948                                 if(player_pos.getDistanceFrom(p_f) > maxd)
3949                                 {
3950                                         far_players->push_back(client->peer_id);
3951                                         continue;
3952                                 }
3953                         }
3954                 }
3955
3956                 // Send as reliable
3957                 m_con.Send(client->peer_id, 0, reply, true);
3958         }
3959 }
3960
3961 void Server::sendAddNode(v3s16 p, MapNode n, u16 ignore_id,
3962                 core::list<u16> *far_players, float far_d_nodes)
3963 {
3964         float maxd = far_d_nodes*BS;
3965         v3f p_f = intToFloat(p, BS);
3966
3967         for(core::map<u16, RemoteClient*>::Iterator
3968                 i = m_clients.getIterator();
3969                 i.atEnd() == false; i++)
3970         {
3971                 // Get client and check that it is valid
3972                 RemoteClient *client = i.getNode()->getValue();
3973                 assert(client->peer_id == i.getNode()->getKey());
3974                 if(client->serialization_version == SER_FMT_VER_INVALID)
3975                         continue;
3976
3977                 // Don't send if it's the same one
3978                 if(client->peer_id == ignore_id)
3979                         continue;
3980
3981                 if(far_players)
3982                 {
3983                         // Get player
3984                         Player *player = m_env->getPlayer(client->peer_id);
3985                         if(player)
3986                         {
3987                                 // If player is far away, only set modified blocks not sent
3988                                 v3f player_pos = player->getPosition();
3989                                 if(player_pos.getDistanceFrom(p_f) > maxd)
3990                                 {
3991                                         far_players->push_back(client->peer_id);
3992                                         continue;
3993                                 }
3994                         }
3995                 }
3996
3997                 // Create packet
3998                 u32 replysize = 8 + MapNode::serializedLength(client->serialization_version);
3999                 SharedBuffer<u8> reply(replysize);
4000                 writeU16(&reply[0], TOCLIENT_ADDNODE);
4001                 writeS16(&reply[2], p.X);
4002                 writeS16(&reply[4], p.Y);
4003                 writeS16(&reply[6], p.Z);
4004                 n.serialize(&reply[8], client->serialization_version);
4005
4006                 // Send as reliable
4007                 m_con.Send(client->peer_id, 0, reply, true);
4008         }
4009 }
4010
4011 void Server::setBlockNotSent(v3s16 p)
4012 {
4013         for(core::map<u16, RemoteClient*>::Iterator
4014                 i = m_clients.getIterator();
4015                 i.atEnd()==false; i++)
4016         {
4017                 RemoteClient *client = i.getNode()->getValue();
4018                 client->SetBlockNotSent(p);
4019         }
4020 }
4021
4022 void Server::SendBlockNoLock(u16 peer_id, MapBlock *block, u8 ver)
4023 {
4024         DSTACK(__FUNCTION_NAME);
4025
4026         v3s16 p = block->getPos();
4027         
4028 #if 0
4029         // Analyze it a bit
4030         bool completely_air = true;
4031         for(s16 z0=0; z0<MAP_BLOCKSIZE; z0++)
4032         for(s16 x0=0; x0<MAP_BLOCKSIZE; x0++)
4033         for(s16 y0=0; y0<MAP_BLOCKSIZE; y0++)
4034         {
4035                 if(block->getNodeNoEx(v3s16(x0,y0,z0)).d != CONTENT_AIR)
4036                 {
4037                         completely_air = false;
4038                         x0 = y0 = z0 = MAP_BLOCKSIZE; // Break out
4039                 }
4040         }
4041
4042         // Print result
4043         infostream<<"Server: Sending block ("<<p.X<<","<<p.Y<<","<<p.Z<<"): ";
4044         if(completely_air)
4045                 infostream<<"[completely air] ";
4046         infostream<<std::endl;
4047 #endif
4048
4049         /*
4050                 Create a packet with the block in the right format
4051         */
4052         
4053         std::ostringstream os(std::ios_base::binary);
4054         block->serialize(os, ver);
4055         std::string s = os.str();
4056         SharedBuffer<u8> blockdata((u8*)s.c_str(), s.size());
4057
4058         u32 replysize = 8 + blockdata.getSize();
4059         SharedBuffer<u8> reply(replysize);
4060         writeU16(&reply[0], TOCLIENT_BLOCKDATA);
4061         writeS16(&reply[2], p.X);
4062         writeS16(&reply[4], p.Y);
4063         writeS16(&reply[6], p.Z);
4064         memcpy(&reply[8], *blockdata, blockdata.getSize());
4065
4066         /*infostream<<"Server: Sending block ("<<p.X<<","<<p.Y<<","<<p.Z<<")"
4067                         <<":  \tpacket size: "<<replysize<<std::endl;*/
4068         
4069         /*
4070                 Send packet
4071         */
4072         m_con.Send(peer_id, 1, reply, true);
4073 }
4074
4075 void Server::SendBlocks(float dtime)
4076 {
4077         DSTACK(__FUNCTION_NAME);
4078
4079         JMutexAutoLock envlock(m_env_mutex);
4080         JMutexAutoLock conlock(m_con_mutex);
4081
4082         //TimeTaker timer("Server::SendBlocks");
4083
4084         core::array<PrioritySortedBlockTransfer> queue;
4085
4086         s32 total_sending = 0;
4087         
4088         {
4089                 ScopeProfiler sp(g_profiler, "Server: selecting blocks for sending");
4090
4091                 for(core::map<u16, RemoteClient*>::Iterator
4092                         i = m_clients.getIterator();
4093                         i.atEnd() == false; i++)
4094                 {
4095                         RemoteClient *client = i.getNode()->getValue();
4096                         assert(client->peer_id == i.getNode()->getKey());
4097
4098                         total_sending += client->SendingCount();
4099                         
4100                         if(client->serialization_version == SER_FMT_VER_INVALID)
4101                                 continue;
4102                         
4103                         client->GetNextBlocks(this, dtime, queue);
4104                 }
4105         }
4106
4107         // Sort.
4108         // Lowest priority number comes first.
4109         // Lowest is most important.
4110         queue.sort();
4111
4112         for(u32 i=0; i<queue.size(); i++)
4113         {
4114                 //TODO: Calculate limit dynamically
4115                 if(total_sending >= g_settings->getS32
4116                                 ("max_simultaneous_block_sends_server_total"))
4117                         break;
4118                 
4119                 PrioritySortedBlockTransfer q = queue[i];
4120
4121                 MapBlock *block = NULL;
4122                 try
4123                 {
4124                         block = m_env->getMap().getBlockNoCreate(q.pos);
4125                 }
4126                 catch(InvalidPositionException &e)
4127                 {
4128                         continue;
4129                 }
4130
4131                 RemoteClient *client = getClient(q.peer_id);
4132
4133                 SendBlockNoLock(q.peer_id, block, client->serialization_version);
4134
4135                 client->SentBlock(q.pos);
4136
4137                 total_sending++;
4138         }
4139 }
4140
4141 struct SendableTexture
4142 {
4143         std::string name;
4144         std::string path;
4145         std::string data;
4146
4147         SendableTexture(const std::string &name_="", const std::string path_="",
4148                         const std::string &data_=""):
4149                 name(name_),
4150                 path(path_),
4151                 data(data_)
4152         {}
4153 };
4154
4155 void Server::SendTextures(u16 peer_id)
4156 {
4157         DSTACK(__FUNCTION_NAME);
4158
4159         infostream<<"Server::SendTextures(): Sending textures to client"<<std::endl;
4160         
4161         /* Read textures */
4162         
4163         // Put 5kB in one bunch (this is not accurate)
4164         u32 bytes_per_bunch = 5000;
4165         
4166         core::array< core::list<SendableTexture> > texture_bunches;
4167         texture_bunches.push_back(core::list<SendableTexture>());
4168         
4169         u32 texture_size_bunch_total = 0;
4170         core::list<ModSpec> mods = getMods(m_modspaths);
4171         for(core::list<ModSpec>::Iterator i = mods.begin();
4172                         i != mods.end(); i++){
4173                 ModSpec mod = *i;
4174                 std::string texturepath = mod.path + DIR_DELIM + "textures";
4175                 std::vector<fs::DirListNode> dirlist = fs::GetDirListing(texturepath);
4176                 for(u32 j=0; j<dirlist.size(); j++){
4177                         if(dirlist[j].dir) // Ignode dirs
4178                                 continue;
4179                         std::string tname = dirlist[j].name;
4180                         std::string tpath = texturepath + DIR_DELIM + tname;
4181                         // Read data
4182                         std::ifstream fis(tpath.c_str(), std::ios_base::binary);
4183                         if(fis.good() == false){
4184                                 errorstream<<"Server::SendTextures(): Could not open \""
4185                                                 <<tname<<"\" for reading"<<std::endl;
4186                                 continue;
4187                         }
4188                         std::ostringstream tmp_os(std::ios_base::binary);
4189                         bool bad = false;
4190                         for(;;){
4191                                 char buf[1024];
4192                                 fis.read(buf, 1024);
4193                                 std::streamsize len = fis.gcount();
4194                                 tmp_os.write(buf, len);
4195                                 texture_size_bunch_total += len;
4196                                 if(fis.eof())
4197                                         break;
4198                                 if(!fis.good()){
4199                                         bad = true;
4200                                         break;
4201                                 }
4202                         }
4203                         if(bad){
4204                                 errorstream<<"Server::SendTextures(): Failed to read \""
4205                                                 <<tname<<"\""<<std::endl;
4206                                 continue;
4207                         }
4208                         errorstream<<"Server::SendTextures(): Loaded \""
4209                                         <<tname<<"\""<<std::endl;
4210                         // Put in list
4211                         texture_bunches[texture_bunches.size()-1].push_back(
4212                                         SendableTexture(tname, tpath, tmp_os.str()));
4213                         
4214                         // Start next bunch if got enough data
4215                         if(texture_size_bunch_total >= bytes_per_bunch){
4216                                 texture_bunches.push_back(core::list<SendableTexture>());
4217                                 texture_size_bunch_total = 0;
4218                         }
4219                 }
4220         }
4221
4222         /* Create and send packets */
4223         
4224         u32 num_bunches = texture_bunches.size();
4225         for(u32 i=0; i<num_bunches; i++)
4226         {
4227                 /*
4228                         u16 command
4229                         u16 total number of texture bunches
4230                         u16 index of this bunch
4231                         u32 number of textures in this bunch
4232                         for each texture {
4233                                 u16 length of name
4234                                 string name
4235                                 u32 length of data
4236                                 data
4237                         }
4238                 */
4239                 std::ostringstream os(std::ios_base::binary);
4240
4241                 writeU16(os, TOCLIENT_TEXTURES);
4242                 writeU16(os, num_bunches);
4243                 writeU16(os, i);
4244                 writeU32(os, texture_bunches[i].size());
4245                 
4246                 for(core::list<SendableTexture>::Iterator
4247                                 j = texture_bunches[i].begin();
4248                                 j != texture_bunches[i].end(); j++){
4249                         os<<serializeString(j->name);
4250                         os<<serializeLongString(j->data);
4251                 }
4252                 
4253                 // Make data buffer
4254                 std::string s = os.str();
4255                 infostream<<"Server::SendTextures(): number of textures in bunch["
4256                                 <<i<<"]: "<<texture_bunches[i].size()
4257                                 <<", size: "<<s.size()<<std::endl;
4258                 SharedBuffer<u8> data((u8*)s.c_str(), s.size());
4259                 // Send as reliable
4260                 m_con.Send(peer_id, 0, data, true);
4261         }
4262 }
4263
4264 /*
4265         Something random
4266 */
4267
4268 void Server::HandlePlayerHP(Player *player, s16 damage)
4269 {
4270         if(player->hp > damage)
4271         {
4272                 player->hp -= damage;
4273                 SendPlayerHP(player);
4274         }
4275         else
4276         {
4277                 infostream<<"Server::HandlePlayerHP(): Player "
4278                                 <<player->getName()<<" dies"<<std::endl;
4279                 
4280                 player->hp = 0;
4281                 
4282                 //TODO: Throw items around
4283                 
4284                 // Handle players that are not connected
4285                 if(player->peer_id == PEER_ID_INEXISTENT){
4286                         RespawnPlayer(player);
4287                         return;
4288                 }
4289
4290                 SendPlayerHP(player);
4291                 
4292                 RemoteClient *client = getClient(player->peer_id);
4293                 if(client->net_proto_version >= 3)
4294                 {
4295                         SendDeathscreen(m_con, player->peer_id, false, v3f(0,0,0));
4296                 }
4297                 else
4298                 {
4299                         RespawnPlayer(player);
4300                 }
4301         }
4302 }
4303
4304 void Server::RespawnPlayer(Player *player)
4305 {
4306         v3f pos = findSpawnPos(m_env->getServerMap());
4307         player->setPosition(pos);
4308         player->hp = 20;
4309         SendMovePlayer(player);
4310         SendPlayerHP(player);
4311 }
4312
4313 void Server::UpdateCrafting(u16 peer_id)
4314 {
4315         DSTACK(__FUNCTION_NAME);
4316         
4317         Player* player = m_env->getPlayer(peer_id);
4318         assert(player);
4319
4320         /*
4321                 Calculate crafting stuff
4322         */
4323         if(g_settings->getBool("creative_mode") == false)
4324         {
4325                 InventoryList *clist = player->inventory.getList("craft");
4326                 InventoryList *rlist = player->inventory.getList("craftresult");
4327
4328                 if(rlist && rlist->getUsedSlots() == 0)
4329                         player->craftresult_is_preview = true;
4330
4331                 if(rlist && player->craftresult_is_preview)
4332                 {
4333                         rlist->clearItems();
4334                 }
4335                 if(clist && rlist && player->craftresult_is_preview)
4336                 {
4337                         InventoryItem *items[9];
4338                         for(u16 i=0; i<9; i++)
4339                         {
4340                                 items[i] = clist->getItem(i);
4341                         }
4342                         
4343                         // Get result of crafting grid
4344                         InventoryItem *result = craft_get_result(items, this);
4345                         if(result)
4346                                 rlist->addItem(result);
4347                 }
4348         
4349         } // if creative_mode == false
4350 }
4351
4352 RemoteClient* Server::getClient(u16 peer_id)
4353 {
4354         DSTACK(__FUNCTION_NAME);
4355         //JMutexAutoLock lock(m_con_mutex);
4356         core::map<u16, RemoteClient*>::Node *n;
4357         n = m_clients.find(peer_id);
4358         // A client should exist for all peers
4359         assert(n != NULL);
4360         return n->getValue();
4361 }
4362
4363 std::wstring Server::getStatusString()
4364 {
4365         std::wostringstream os(std::ios_base::binary);
4366         os<<L"# Server: ";
4367         // Version
4368         os<<L"version="<<narrow_to_wide(VERSION_STRING);
4369         // Uptime
4370         os<<L", uptime="<<m_uptime.get();
4371         // Information about clients
4372         os<<L", clients={";
4373         for(core::map<u16, RemoteClient*>::Iterator
4374                 i = m_clients.getIterator();
4375                 i.atEnd() == false; i++)
4376         {
4377                 // Get client and check that it is valid
4378                 RemoteClient *client = i.getNode()->getValue();
4379                 assert(client->peer_id == i.getNode()->getKey());
4380                 if(client->serialization_version == SER_FMT_VER_INVALID)
4381                         continue;
4382                 // Get player
4383                 Player *player = m_env->getPlayer(client->peer_id);
4384                 // Get name of player
4385                 std::wstring name = L"unknown";
4386                 if(player != NULL)
4387                         name = narrow_to_wide(player->getName());
4388                 // Add name to information string
4389                 os<<name<<L",";
4390         }
4391         os<<L"}";
4392         if(((ServerMap*)(&m_env->getMap()))->isSavingEnabled() == false)
4393                 os<<std::endl<<L"# Server: "<<" WARNING: Map saving is disabled.";
4394         if(g_settings->get("motd") != "")
4395                 os<<std::endl<<L"# Server: "<<narrow_to_wide(g_settings->get("motd"));
4396         return os.str();
4397 }
4398
4399 // Saves g_settings to configpath given at initialization
4400 void Server::saveConfig()
4401 {
4402         if(m_configpath != "")
4403                 g_settings->updateConfigFile(m_configpath.c_str());
4404 }
4405
4406 void Server::notifyPlayer(const char *name, const std::wstring msg)
4407 {
4408         Player *player = m_env->getPlayer(name);
4409         if(!player)
4410                 return;
4411         SendChatMessage(player->peer_id, std::wstring(L"Server: -!- ")+msg);
4412 }
4413
4414 void Server::notifyPlayers(const std::wstring msg)
4415 {
4416         BroadcastChatMessage(msg);
4417 }
4418
4419 // IGameDef interface
4420 // Under envlock
4421 IToolDefManager* Server::getToolDefManager()
4422 {
4423         return m_toolmgr;
4424 }
4425 INodeDefManager* Server::getNodeDefManager()
4426 {
4427         return m_nodemgr;
4428 }
4429 ITextureSource* Server::getTextureSource()
4430 {
4431         return NULL;
4432 }
4433
4434 IWritableToolDefManager* Server::getWritableToolDefManager()
4435 {
4436         return m_toolmgr;
4437 }
4438 IWritableNodeDefManager* Server::getWritableNodeDefManager()
4439 {
4440         return m_nodemgr;
4441 }
4442
4443 v3f findSpawnPos(ServerMap &map)
4444 {
4445         //return v3f(50,50,50)*BS;
4446
4447         v3s16 nodepos;
4448         
4449 #if 0
4450         nodepos = v2s16(0,0);
4451         groundheight = 20;
4452 #endif
4453
4454 #if 1
4455         // Try to find a good place a few times
4456         for(s32 i=0; i<1000; i++)
4457         {
4458                 s32 range = 1 + i;
4459                 // We're going to try to throw the player to this position
4460                 v2s16 nodepos2d = v2s16(-range + (myrand()%(range*2)),
4461                                 -range + (myrand()%(range*2)));
4462                 //v2s16 sectorpos = getNodeSectorPos(nodepos2d);
4463                 // Get ground height at point (fallbacks to heightmap function)
4464                 s16 groundheight = map.findGroundLevel(nodepos2d);
4465                 // Don't go underwater
4466                 if(groundheight < WATER_LEVEL)
4467                 {
4468                         //infostream<<"-> Underwater"<<std::endl;
4469                         continue;
4470                 }
4471                 // Don't go to high places
4472                 if(groundheight > WATER_LEVEL + 4)
4473                 {
4474                         //infostream<<"-> Underwater"<<std::endl;
4475                         continue;
4476                 }
4477                 
4478                 nodepos = v3s16(nodepos2d.X, groundheight-2, nodepos2d.Y);
4479                 bool is_good = false;
4480                 s32 air_count = 0;
4481                 for(s32 i=0; i<10; i++){
4482                         v3s16 blockpos = getNodeBlockPos(nodepos);
4483                         map.emergeBlock(blockpos, true);
4484                         MapNode n = map.getNodeNoEx(nodepos);
4485                         if(n.getContent() == CONTENT_AIR){
4486                                 air_count++;
4487                                 if(air_count >= 2){
4488                                         is_good = true;
4489                                         nodepos.Y -= 1;
4490                                         break;
4491                                 }
4492                         }
4493                         nodepos.Y++;
4494                 }
4495                 if(is_good){
4496                         // Found a good place
4497                         //infostream<<"Searched through "<<i<<" places."<<std::endl;
4498                         break;
4499                 }
4500         }
4501 #endif
4502         
4503         return intToFloat(nodepos, BS);
4504 }
4505
4506 Player *Server::emergePlayer(const char *name, const char *password, u16 peer_id)
4507 {
4508         /*
4509                 Try to get an existing player
4510         */
4511         Player *player = m_env->getPlayer(name);
4512         if(player != NULL)
4513         {
4514                 // If player is already connected, cancel
4515                 if(player->peer_id != 0)
4516                 {
4517                         infostream<<"emergePlayer(): Player already connected"<<std::endl;
4518                         return NULL;
4519                 }
4520
4521                 // Got one.
4522                 player->peer_id = peer_id;
4523                 
4524                 // Reset inventory to creative if in creative mode
4525                 if(g_settings->getBool("creative_mode"))
4526                 {
4527                         // Warning: double code below
4528                         // Backup actual inventory
4529                         player->inventory_backup = new Inventory();
4530                         *(player->inventory_backup) = player->inventory;
4531                         // Set creative inventory
4532                         craft_set_creative_inventory(player, this);
4533                 }
4534
4535                 return player;
4536         }
4537
4538         /*
4539                 If player with the wanted peer_id already exists, cancel.
4540         */
4541         if(m_env->getPlayer(peer_id) != NULL)
4542         {
4543                 infostream<<"emergePlayer(): Player with wrong name but same"
4544                                 " peer_id already exists"<<std::endl;
4545                 return NULL;
4546         }
4547         
4548         /*
4549                 Create a new player
4550         */
4551         {
4552                 // Add authentication stuff
4553                 m_authmanager.add(name);
4554                 m_authmanager.setPassword(name, password);
4555                 m_authmanager.setPrivs(name,
4556                                 stringToPrivs(g_settings->get("default_privs")));
4557
4558                 /*
4559                         Set player position
4560                 */
4561                 
4562                 infostream<<"Server: Finding spawn place for player \""
4563                                 <<name<<"\""<<std::endl;
4564
4565                 v3f pos = findSpawnPos(m_env->getServerMap());
4566
4567                 player = new ServerRemotePlayer(m_env, pos, peer_id, name);
4568
4569                 /*
4570                         Add player to environment
4571                 */
4572
4573                 m_env->addPlayer(player);
4574
4575                 /*
4576                         Add stuff to inventory
4577                 */
4578                 
4579                 if(g_settings->getBool("creative_mode"))
4580                 {
4581                         // Warning: double code above
4582                         // Backup actual inventory
4583                         player->inventory_backup = new Inventory();
4584                         *(player->inventory_backup) = player->inventory;
4585                         // Set creative inventory
4586                         craft_set_creative_inventory(player, this);
4587                 }
4588                 else if(g_settings->getBool("give_initial_stuff"))
4589                 {
4590                         craft_give_initial_stuff(player, this);
4591                 }
4592
4593                 return player;
4594                 
4595         } // create new player
4596 }
4597
4598 void Server::handlePeerChange(PeerChange &c)
4599 {
4600         JMutexAutoLock envlock(m_env_mutex);
4601         JMutexAutoLock conlock(m_con_mutex);
4602         
4603         if(c.type == PEER_ADDED)
4604         {
4605                 /*
4606                         Add
4607                 */
4608
4609                 // Error check
4610                 core::map<u16, RemoteClient*>::Node *n;
4611                 n = m_clients.find(c.peer_id);
4612                 // The client shouldn't already exist
4613                 assert(n == NULL);
4614
4615                 // Create client
4616                 RemoteClient *client = new RemoteClient();
4617                 client->peer_id = c.peer_id;
4618                 m_clients.insert(client->peer_id, client);
4619
4620         } // PEER_ADDED
4621         else if(c.type == PEER_REMOVED)
4622         {
4623                 /*
4624                         Delete
4625                 */
4626
4627                 // Error check
4628                 core::map<u16, RemoteClient*>::Node *n;
4629                 n = m_clients.find(c.peer_id);
4630                 // The client should exist
4631                 assert(n != NULL);
4632                 
4633                 /*
4634                         Mark objects to be not known by the client
4635                 */
4636                 RemoteClient *client = n->getValue();
4637                 // Handle objects
4638                 for(core::map<u16, bool>::Iterator
4639                                 i = client->m_known_objects.getIterator();
4640                                 i.atEnd()==false; i++)
4641                 {
4642                         // Get object
4643                         u16 id = i.getNode()->getKey();
4644                         ServerActiveObject* obj = m_env->getActiveObject(id);
4645                         
4646                         if(obj && obj->m_known_by_count > 0)
4647                                 obj->m_known_by_count--;
4648                 }
4649
4650                 // Collect information about leaving in chat
4651                 std::wstring message;
4652                 {
4653                         Player *player = m_env->getPlayer(c.peer_id);
4654                         if(player != NULL)
4655                         {
4656                                 std::wstring name = narrow_to_wide(player->getName());
4657                                 message += L"*** ";
4658                                 message += name;
4659                                 message += L" left game";
4660                                 if(c.timeout)
4661                                         message += L" (timed out)";
4662                         }
4663                 }
4664
4665                 /*// Delete player
4666                 {
4667                         m_env->removePlayer(c.peer_id);
4668                 }*/
4669
4670                 // Set player client disconnected
4671                 {
4672                         Player *player = m_env->getPlayer(c.peer_id);
4673                         if(player != NULL)
4674                                 player->peer_id = 0;
4675                         
4676                         /*
4677                                 Print out action
4678                         */
4679                         if(player != NULL)
4680                         {
4681                                 std::ostringstream os(std::ios_base::binary);
4682                                 for(core::map<u16, RemoteClient*>::Iterator
4683                                         i = m_clients.getIterator();
4684                                         i.atEnd() == false; i++)
4685                                 {
4686                                         RemoteClient *client = i.getNode()->getValue();
4687                                         assert(client->peer_id == i.getNode()->getKey());
4688                                         if(client->serialization_version == SER_FMT_VER_INVALID)
4689                                                 continue;
4690                                         // Get player
4691                                         Player *player = m_env->getPlayer(client->peer_id);
4692                                         if(!player)
4693                                                 continue;
4694                                         // Get name of player
4695                                         os<<player->getName()<<" ";
4696                                 }
4697
4698                                 actionstream<<player->getName()<<" "
4699                                                 <<(c.timeout?"times out.":"leaves game.")
4700                                                 <<" List of players: "
4701                                                 <<os.str()<<std::endl;
4702                         }
4703                 }
4704                 
4705                 // Delete client
4706                 delete m_clients[c.peer_id];
4707                 m_clients.remove(c.peer_id);
4708
4709                 // Send player info to all remaining clients
4710                 SendPlayerInfos();
4711                 
4712                 // Send leave chat message to all remaining clients
4713                 BroadcastChatMessage(message);
4714                 
4715         } // PEER_REMOVED
4716         else
4717         {
4718                 assert(0);
4719         }
4720 }
4721
4722 void Server::handlePeerChanges()
4723 {
4724         while(m_peer_change_queue.size() > 0)
4725         {
4726                 PeerChange c = m_peer_change_queue.pop_front();
4727
4728                 infostream<<"Server: Handling peer change: "
4729                                 <<"id="<<c.peer_id<<", timeout="<<c.timeout
4730                                 <<std::endl;
4731
4732                 handlePeerChange(c);
4733         }
4734 }
4735
4736 u64 Server::getPlayerPrivs(Player *player)
4737 {
4738         if(player==NULL)
4739                 return 0;
4740         std::string playername = player->getName();
4741         // Local player gets all privileges regardless of
4742         // what's set on their account.
4743         if(g_settings->get("name") == playername)
4744         {
4745                 return PRIV_ALL;
4746         }
4747         else
4748         {
4749                 return getPlayerAuthPrivs(playername);
4750         }
4751 }
4752
4753 void dedicated_server_loop(Server &server, bool &kill)
4754 {
4755         DSTACK(__FUNCTION_NAME);
4756         
4757         infostream<<DTIME<<std::endl;
4758         infostream<<"========================"<<std::endl;
4759         infostream<<"Running dedicated server"<<std::endl;
4760         infostream<<"========================"<<std::endl;
4761         infostream<<std::endl;
4762
4763         IntervalLimiter m_profiler_interval;
4764
4765         for(;;)
4766         {
4767                 // This is kind of a hack but can be done like this
4768                 // because server.step() is very light
4769                 {
4770                         ScopeProfiler sp(g_profiler, "dedicated server sleep");
4771                         sleep_ms(30);
4772                 }
4773                 server.step(0.030);
4774
4775                 if(server.getShutdownRequested() || kill)
4776                 {
4777                         infostream<<DTIME<<" dedicated_server_loop(): Quitting."<<std::endl;
4778                         break;
4779                 }
4780
4781                 /*
4782                         Profiler
4783                 */
4784                 float profiler_print_interval =
4785                                 g_settings->getFloat("profiler_print_interval");
4786                 if(profiler_print_interval != 0)
4787                 {
4788                         if(m_profiler_interval.step(0.030, profiler_print_interval))
4789                         {
4790                                 infostream<<"Profiler:"<<std::endl;
4791                                 g_profiler->print(infostream);
4792                                 g_profiler->clear();
4793                         }
4794                 }
4795                 
4796                 /*
4797                         Player info
4798                 */
4799                 static int counter = 0;
4800                 counter--;
4801                 if(counter <= 0)
4802                 {
4803                         counter = 10;
4804
4805                         core::list<PlayerInfo> list = server.getPlayerInfo();
4806                         core::list<PlayerInfo>::Iterator i;
4807                         static u32 sum_old = 0;
4808                         u32 sum = PIChecksum(list);
4809                         if(sum != sum_old)
4810                         {
4811                                 infostream<<DTIME<<"Player info:"<<std::endl;
4812                                 for(i=list.begin(); i!=list.end(); i++)
4813                                 {
4814                                         i->PrintLine(&infostream);
4815                                 }
4816                         }
4817                         sum_old = sum;
4818                 }
4819         }
4820 }
4821
4822