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