3 Copyright (C) 2010 celeron55, Perttu Ahola <celeron55@gmail.com>
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.
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.
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.
21 (c) 2010 Perttu Ahola <celeron55@gmail.com>
27 #include "clientserver.h"
29 #include "jmutexautolock.h"
31 #include "constants.h"
34 void * ServerThread::Thread()
38 DSTACK(__FUNCTION_NAME);
43 m_server->AsyncRunStep();
45 //dout_server<<"Running m_server->Receive()"<<std::endl;
48 catch(con::NoIncomingDataException &e)
51 #if CATCH_UNHANDLED_EXCEPTIONS
53 This is what has to be done in threads to get suitable debug info
55 catch(std::exception &e)
57 dstream<<std::endl<<DTIME<<"An unhandled exception occurred: "
58 <<e.what()<<std::endl;
68 void * EmergeThread::Thread()
72 DSTACK(__FUNCTION_NAME);
75 #if CATCH_UNHANDLED_EXCEPTIONS
81 Get block info from queue, emerge them and send them
84 After queue is empty, exit.
88 QueuedBlockEmerge *qptr = m_server->m_emerge_queue.pop();
92 SharedPtr<QueuedBlockEmerge> q(qptr);
96 //derr_server<<"EmergeThread::Thread(): running"<<std::endl;
99 Try to emerge it from somewhere.
101 If it is only wanted as optional, only loading from disk
106 Check if any peer wants it as non-optional. In that case it
109 Also decrement the emerge queue count in clients.
112 bool optional = true;
115 core::map<u16, u8>::Iterator i;
116 for(i=q->peer_ids.getIterator(); i.atEnd()==false; i++)
118 //u16 peer_id = i.getNode()->getKey();
121 u8 flags = i.getNode()->getValue();
122 if((flags & TOSERVER_GETBLOCK_FLAG_OPTIONAL) == false)
128 /*dstream<<"EmergeThread: p="
129 <<"("<<p.X<<","<<p.Y<<","<<p.Z<<") "
130 <<"optional="<<optional<<std::endl;*/
132 ServerMap &map = ((ServerMap&)m_server->m_env.getMap());
134 core::map<v3s16, MapBlock*> changed_blocks;
135 core::map<v3s16, MapBlock*> lighting_invalidated_blocks;
137 MapBlock *block = NULL;
138 bool got_block = true;
139 core::map<v3s16, MapBlock*> modified_blocks;
143 JMutexAutoLock envlock(m_server->m_env_mutex);
145 //TimeTaker timer("block emerge envlock", g_device);
148 bool only_from_disk = false;
151 only_from_disk = true;
153 block = map.emergeBlock(
157 lighting_invalidated_blocks);
159 // If it is a dummy, block was not found on disk
162 //dstream<<"EmergeThread: Got a dummy block"<<std::endl;
166 catch(InvalidPositionException &e)
169 // This happens when position is over limit.
175 if(debug && changed_blocks.size() > 0)
177 dout_server<<DTIME<<"Got changed_blocks: ";
178 for(core::map<v3s16, MapBlock*>::Iterator i = changed_blocks.getIterator();
179 i.atEnd() == false; i++)
181 MapBlock *block = i.getNode()->getValue();
182 v3s16 p = block->getPos();
183 dout_server<<"("<<p.X<<","<<p.Y<<","<<p.Z<<") ";
185 dout_server<<std::endl;
189 Collect a list of blocks that have been modified in
190 addition to the fetched one.
193 // Add all the "changed blocks"
194 for(core::map<v3s16, MapBlock*>::Iterator i = changed_blocks.getIterator();
195 i.atEnd() == false; i++)
197 MapBlock *block = i.getNode()->getValue();
198 modified_blocks.insert(block->getPos(), block);
201 /*dstream<<"lighting "<<lighting_invalidated_blocks.size()
202 <<" blocks"<<std::endl;
203 TimeTaker timer("** updateLighting", g_device);*/
205 // Update lighting without locking the environment mutex,
206 // add modified blocks to changed blocks
207 map.updateLighting(lighting_invalidated_blocks, modified_blocks);
209 // If we got no block, there should be no invalidated blocks
212 assert(lighting_invalidated_blocks.size() == 0);
218 Set sent status of modified blocks on clients
221 // NOTE: Server's clients are also behind the connection mutex
222 JMutexAutoLock lock(m_server->m_con_mutex);
225 Add the originally fetched block to the modified list
229 modified_blocks.insert(p, block);
233 Set the modified blocks unsent for all the clients
236 for(core::map<u16, RemoteClient*>::Iterator
237 i = m_server->m_clients.getIterator();
238 i.atEnd() == false; i++)
240 RemoteClient *client = i.getNode()->getValue();
242 if(modified_blocks.size() > 0)
244 // Remove block from sent history
245 client->SetBlocksNotSent(modified_blocks);
248 /*if(q->peer_ids.find(client->peer_id) != NULL)
250 // Decrement emerge queue count of client
251 client->BlockEmerged();
256 #if CATCH_UNHANDLED_EXCEPTIONS
259 This is what has to be done in threads to get suitable debug info
261 catch(std::exception &e)
263 dstream<<std::endl<<DTIME<<"An unhandled exception occurred: "
264 <<e.what()<<std::endl;
272 void RemoteClient::GetNextBlocks(Server *server, float dtime,
273 core::array<PrioritySortedBlockTransfer> &dest)
275 DSTACK(__FUNCTION_NAME);
277 // Won't send anything if already sending
279 JMutexAutoLock lock(m_blocks_sending_mutex);
281 if(m_blocks_sending.size() >= g_settings.getU16
282 ("max_simultaneous_block_sends_per_client"))
284 //dstream<<"Not sending any blocks, Queue full."<<std::endl;
289 Player *player = server->m_env.getPlayer(peer_id);
291 v3f playerpos = player->getPosition();
292 v3f playerspeed = player->getSpeed();
294 v3s16 center_nodepos = floatToInt(playerpos);
296 v3s16 center = getNodeBlockPos(center_nodepos);
299 Get the starting value of the block finder radius.
301 s16 last_nearest_unsent_d;
304 JMutexAutoLock lock(m_blocks_sent_mutex);
306 if(m_last_center != center)
308 m_nearest_unsent_d = 0;
309 m_last_center = center;
312 static float reset_counter = 0;
313 reset_counter += dtime;
314 if(reset_counter > 5.0)
317 m_nearest_unsent_d = 0;
320 last_nearest_unsent_d = m_nearest_unsent_d;
322 d_start = m_nearest_unsent_d;
325 u16 maximum_simultaneous_block_sends_setting = g_settings.getU16
326 ("max_simultaneous_block_sends_per_client");
327 u16 maximum_simultaneous_block_sends =
328 maximum_simultaneous_block_sends_setting;
331 Check the time from last addNode/removeNode.
333 Decrease send rate if player is building stuff.
336 SharedPtr<JMutexAutoLock> lock(m_time_from_building.getLock());
337 m_time_from_building.m_value += dtime;
338 if(m_time_from_building.m_value
339 < FULL_BLOCK_SEND_ENABLE_MIN_TIME_FROM_BUILDING)
341 maximum_simultaneous_block_sends
342 = LIMITED_MAX_SIMULTANEOUS_BLOCK_SENDS;
346 // Serialization version used
347 //u8 ser_version = serialization_version;
349 //bool has_incomplete_blocks = false;
352 TODO: Get this from somewhere
357 //TODO: Get this from somewhere (probably a bigger value)
360 //dstream<<"Starting from "<<d_start<<std::endl;
362 for(s16 d = d_start; d <= d_max; d++)
364 //dstream<<"RemoteClient::SendBlocks(): d="<<d<<std::endl;
366 //if(has_incomplete_blocks == false)
368 JMutexAutoLock lock(m_blocks_sent_mutex);
370 If m_nearest_unsent_d was changed by the EmergeThread
371 (it can change it to 0 through SetBlockNotSent),
373 Else update m_nearest_unsent_d
375 if(m_nearest_unsent_d != last_nearest_unsent_d)
377 d = m_nearest_unsent_d;
381 m_nearest_unsent_d = d;
383 last_nearest_unsent_d = m_nearest_unsent_d;
387 Get the border/face dot coordinates of a "d-radiused"
390 core::list<v3s16> list;
391 getFacePositions(list, d);
393 core::list<v3s16>::Iterator li;
394 for(li=list.begin(); li!=list.end(); li++)
396 v3s16 p = *li + center;
400 - Don't allow too many simultaneous transfers
401 - EXCEPT when the blocks are very close
403 Also, don't send blocks that are already flying.
406 u16 maximum_simultaneous_block_sends_now =
407 maximum_simultaneous_block_sends;
409 if(d <= BLOCK_SEND_DISABLE_LIMITS_MAX_D)
410 maximum_simultaneous_block_sends_now =
411 maximum_simultaneous_block_sends_setting;
414 JMutexAutoLock lock(m_blocks_sending_mutex);
416 // Limit is dynamically lowered when building
417 if(m_blocks_sending.size()
418 >= maximum_simultaneous_block_sends_now)
420 /*dstream<<"Not sending more blocks. Queue full. "
421 <<m_blocks_sending.size()
426 if(m_blocks_sending.find(p) != NULL)
433 if(p.X < -MAP_GENERATION_LIMIT / MAP_BLOCKSIZE
434 || p.X > MAP_GENERATION_LIMIT / MAP_BLOCKSIZE
435 || p.Y < -MAP_GENERATION_LIMIT / MAP_BLOCKSIZE
436 || p.Y > MAP_GENERATION_LIMIT / MAP_BLOCKSIZE
437 || p.Z < -MAP_GENERATION_LIMIT / MAP_BLOCKSIZE
438 || p.Z > MAP_GENERATION_LIMIT / MAP_BLOCKSIZE)
441 bool generate = d <= d_max_gen;
443 // Limit the generating area vertically to half
444 if(abs(p.Y - center.Y) > d_max_gen / 2)
448 Don't send already sent blocks
451 JMutexAutoLock lock(m_blocks_sent_mutex);
453 if(m_blocks_sent.find(p) != NULL)
458 Check if map has this block
460 MapBlock *block = NULL;
463 block = server->m_env.getMap().getBlockNoCreate(p);
465 catch(InvalidPositionException &e)
469 bool surely_not_found_on_disk = false;
472 /*if(block->isIncomplete())
474 has_incomplete_blocks = true;
480 surely_not_found_on_disk = true;
485 If block has been marked to not exist on disk (dummy)
486 and generating new ones is not wanted, skip block.
488 if(generate == false && surely_not_found_on_disk == true)
495 Add inexistent block to emerge queue.
497 if(block == NULL || surely_not_found_on_disk)
499 /*SharedPtr<JMutexAutoLock> lock
500 (m_num_blocks_in_emerge_queue.getLock());*/
502 //TODO: Get value from somewhere
503 // Allow only one block in emerge queue
504 if(server->m_emerge_queue.peerItemCount(peer_id) < 1)
506 // Add it to the emerge queue and trigger the thread
509 if(generate == false)
510 flags |= TOSERVER_GETBLOCK_FLAG_OPTIONAL;
512 server->m_emerge_queue.addBlock(peer_id, p, flags);
513 server->m_emergethread.trigger();
524 PrioritySortedBlockTransfer q((float)d, p, peer_id);
530 // Don't add anything here. The loop breaks by returning.
533 void RemoteClient::SendObjectData(
536 core::map<v3s16, bool> &stepped_blocks
539 DSTACK(__FUNCTION_NAME);
541 // Can't send anything without knowing version
542 if(serialization_version == SER_FMT_VER_INVALID)
544 dstream<<"RemoteClient::SendObjectData(): Not sending, no version."
550 Send a TOCLIENT_OBJECTDATA packet.
554 u16 number of player positions
565 std::ostringstream os(std::ios_base::binary);
569 writeU16(buf, TOCLIENT_OBJECTDATA);
570 os.write((char*)buf, 2);
573 Get and write player data
576 core::list<Player*> players = server->m_env.getPlayers();
578 // Write player count
579 u16 playercount = players.size();
580 writeU16(buf, playercount);
581 os.write((char*)buf, 2);
583 core::list<Player*>::Iterator i;
584 for(i = players.begin();
585 i != players.end(); i++)
589 v3f pf = player->getPosition();
590 v3f sf = player->getSpeed();
592 v3s32 position_i(pf.X*100, pf.Y*100, pf.Z*100);
593 v3s32 speed_i (sf.X*100, sf.Y*100, sf.Z*100);
594 s32 pitch_i (player->getPitch() * 100);
595 s32 yaw_i (player->getYaw() * 100);
597 writeU16(buf, player->peer_id);
598 os.write((char*)buf, 2);
599 writeV3S32(buf, position_i);
600 os.write((char*)buf, 12);
601 writeV3S32(buf, speed_i);
602 os.write((char*)buf, 12);
603 writeS32(buf, pitch_i);
604 os.write((char*)buf, 4);
605 writeS32(buf, yaw_i);
606 os.write((char*)buf, 4);
610 Get and write object data
616 For making players to be able to build to their nearby
617 environment (building is not possible on blocks that are not
620 - Add blocks to emerge queue if they are not found
622 SUGGESTION: These could be ignored from the backside of the player
624 TODO: Keep track of total size of packet and stop when it is too big
627 Player *player = server->m_env.getPlayer(peer_id);
629 v3f playerpos = player->getPosition();
630 v3f playerspeed = player->getSpeed();
632 v3s16 center_nodepos = floatToInt(playerpos);
633 v3s16 center = getNodeBlockPos(center_nodepos);
635 //s16 d_max = ACTIVE_OBJECT_D_BLOCKS;
636 s16 d_max = g_settings.getS16("active_object_range");
638 // Number of blocks whose objects were written to bos
641 //core::map<v3s16, MapBlock*> blocks;
642 std::ostringstream bos(std::ios_base::binary);
644 for(s16 d = 0; d <= d_max; d++)
646 core::list<v3s16> list;
647 getFacePositions(list, d);
649 core::list<v3s16>::Iterator li;
650 for(li=list.begin(); li!=list.end(); li++)
652 v3s16 p = *li + center;
655 Ignore blocks that haven't been sent to the client
658 JMutexAutoLock sentlock(m_blocks_sent_mutex);
659 if(m_blocks_sent.find(p) == NULL)
663 // Try stepping block and add it to a send queue
668 MapBlock *block = server->m_env.getMap().getBlockNoCreate(p);
670 // Skip block if there are no objects
671 if(block->getObjectCount() == 0)
674 // Step block if not in stepped_blocks and add to stepped_blocks
675 if(stepped_blocks.find(p) == NULL)
677 block->stepObjects(dtime, true);
678 stepped_blocks.insert(p, true);
679 block->setChangedFlag();
688 bos.write((char*)buf, 6);
691 block->serializeObjects(bos, serialization_version);
696 Stop collecting objects if data is already too big
698 // Sum of player and object data sizes
699 s32 sum = (s32)os.tellp() + 2 + (s32)bos.tellp();
700 // break out if data too big
701 if(sum > MAX_OBJECTDATA_SIZE)
703 goto skip_subsequent;
707 catch(InvalidPositionException &e)
710 // Add it to the emerge queue and trigger the thread.
711 // Fetch the block only if it is on disk.
713 // Grab and increment counter
714 /*SharedPtr<JMutexAutoLock> lock
715 (m_num_blocks_in_emerge_queue.getLock());
716 m_num_blocks_in_emerge_queue.m_value++;*/
718 // Add to queue as an anonymous fetch from disk
719 u8 flags = TOSERVER_GETBLOCK_FLAG_OPTIONAL;
720 server->m_emerge_queue.addBlock(0, p, flags);
721 server->m_emergethread.trigger();
729 writeU16(buf, blockcount);
730 os.write((char*)buf, 2);
732 // Write block objects
739 //dstream<<"Server: Sending object data to "<<peer_id<<std::endl;
742 std::string s = os.str();
743 SharedBuffer<u8> data((u8*)s.c_str(), s.size());
744 // Send as unreliable
745 server->m_con.Send(peer_id, 0, data, false);
748 void RemoteClient::GotBlock(v3s16 p)
750 JMutexAutoLock lock(m_blocks_sending_mutex);
751 JMutexAutoLock lock2(m_blocks_sent_mutex);
752 if(m_blocks_sending.find(p) != NULL)
753 m_blocks_sending.remove(p);
755 dstream<<"RemoteClient::GotBlock(): Didn't find in"
756 " m_blocks_sending"<<std::endl;
757 m_blocks_sent.insert(p, true);
760 void RemoteClient::SentBlock(v3s16 p)
762 JMutexAutoLock lock(m_blocks_sending_mutex);
763 if(m_blocks_sending.size() > 15)
765 dstream<<"RemoteClient::SentBlock(): "
766 <<"m_blocks_sending.size()="
767 <<m_blocks_sending.size()<<std::endl;
769 if(m_blocks_sending.find(p) == NULL)
770 m_blocks_sending.insert(p, 0.0);
772 dstream<<"RemoteClient::SentBlock(): Sent block"
773 " already in m_blocks_sending"<<std::endl;
776 void RemoteClient::SetBlockNotSent(v3s16 p)
778 JMutexAutoLock sendinglock(m_blocks_sending_mutex);
779 JMutexAutoLock sentlock(m_blocks_sent_mutex);
781 m_nearest_unsent_d = 0;
783 if(m_blocks_sending.find(p) != NULL)
784 m_blocks_sending.remove(p);
785 if(m_blocks_sent.find(p) != NULL)
786 m_blocks_sent.remove(p);
789 void RemoteClient::SetBlocksNotSent(core::map<v3s16, MapBlock*> &blocks)
791 JMutexAutoLock sendinglock(m_blocks_sending_mutex);
792 JMutexAutoLock sentlock(m_blocks_sent_mutex);
794 m_nearest_unsent_d = 0;
796 for(core::map<v3s16, MapBlock*>::Iterator
797 i = blocks.getIterator();
798 i.atEnd()==false; i++)
800 v3s16 p = i.getNode()->getKey();
802 if(m_blocks_sending.find(p) != NULL)
803 m_blocks_sending.remove(p);
804 if(m_blocks_sent.find(p) != NULL)
805 m_blocks_sent.remove(p);
809 /*void RemoteClient::BlockEmerged()
811 SharedPtr<JMutexAutoLock> lock(m_num_blocks_in_emerge_queue.getLock());
812 assert(m_num_blocks_in_emerge_queue.m_value > 0);
813 m_num_blocks_in_emerge_queue.m_value--;
816 /*void RemoteClient::RunSendingTimeouts(float dtime, float timeout)
818 JMutexAutoLock sendinglock(m_blocks_sending_mutex);
820 core::list<v3s16> remove_queue;
821 for(core::map<v3s16, float>::Iterator
822 i = m_blocks_sending.getIterator();
823 i.atEnd()==false; i++)
825 v3s16 p = i.getNode()->getKey();
826 float t = i.getNode()->getValue();
828 i.getNode()->setValue(t);
832 remove_queue.push_back(p);
835 for(core::list<v3s16>::Iterator
836 i = remove_queue.begin();
837 i != remove_queue.end(); i++)
839 m_blocks_sending.remove(*i);
847 PlayerInfo::PlayerInfo()
852 void PlayerInfo::PrintLine(std::ostream *s)
854 (*s)<<id<<": \""<<name<<"\" ("
855 <<position.X<<","<<position.Y
856 <<","<<position.Z<<") ";
858 (*s)<<" avg_rtt="<<avg_rtt;
862 u32 PIChecksum(core::list<PlayerInfo> &l)
864 core::list<PlayerInfo>::Iterator i;
867 for(i=l.begin(); i!=l.end(); i++)
869 checksum += a * (i->id+1);
870 checksum ^= 0x435aafcd;
881 std::string mapsavedir,
885 m_env(new ServerMap(mapsavedir, hm_params, map_params), dout_server),
886 m_con(PROTOCOL_ID, 512, CONNECTION_TIMEOUT, this),
892 m_step_dtime_mutex.Init();
901 JMutexAutoLock clientslock(m_con_mutex);
903 for(core::map<u16, RemoteClient*>::Iterator
904 i = m_clients.getIterator();
905 i.atEnd() == false; i++)
907 u16 peer_id = i.getNode()->getKey();
911 JMutexAutoLock envlock(m_env_mutex);
912 m_env.removePlayer(peer_id);
916 delete i.getNode()->getValue();
920 void Server::start(unsigned short port)
922 DSTACK(__FUNCTION_NAME);
923 // Stop thread if already running
926 // Initialize connection
927 m_con.setTimeoutMs(30);
931 m_thread.setRun(true);
934 dout_server<<"Server started on port "<<port<<std::endl;
939 DSTACK(__FUNCTION_NAME);
940 // Stop threads (set run=false first so both start stopping)
941 m_thread.setRun(false);
942 m_emergethread.setRun(false);
944 m_emergethread.stop();
946 dout_server<<"Server threads stopped"<<std::endl;
949 void Server::step(float dtime)
951 DSTACK(__FUNCTION_NAME);
956 JMutexAutoLock lock(m_step_dtime_mutex);
957 m_step_dtime += dtime;
961 void Server::AsyncRunStep()
963 DSTACK(__FUNCTION_NAME);
967 JMutexAutoLock lock1(m_step_dtime_mutex);
968 dtime = m_step_dtime;
974 //dstream<<"Server steps "<<dtime<<std::endl;
976 //dstream<<"Server::AsyncRunStep(): dtime="<<dtime<<std::endl;
978 // Has to be locked for peerAdded/Removed
979 JMutexAutoLock lock1(m_env_mutex);
980 // Process connection's timeouts
981 JMutexAutoLock lock2(m_con_mutex);
982 m_con.RunTimeouts(dtime);
986 // This also runs Map's timers
987 JMutexAutoLock lock(m_env_mutex);
999 static float counter = 0.0;
1006 core::map<v3s16, MapBlock*> modified_blocks;
1010 JMutexAutoLock lock(m_env_mutex);
1012 MapVoxelManipulator v(&m_env.getMap());
1015 v.flowWater(m_flow_active_nodes, 0, false, 20);
1016 //v.flowWater(p_under, 0, true, 100);
1018 catch(ProcessingLimitException &e)
1020 dstream<<"Processing limit reached"<<std::endl;
1023 v.flowWater(m_flow_active_nodes, 0, false, 20);
1025 v.blitBack(modified_blocks);
1027 ServerMap &map = ((ServerMap&)m_env.getMap());
1030 core::map<v3s16, MapBlock*> lighting_modified_blocks;
1031 map.updateLighting(modified_blocks, lighting_modified_blocks);
1033 // Add blocks modified by lighting to modified_blocks
1034 for(core::map<v3s16, MapBlock*>::Iterator
1035 i = lighting_modified_blocks.getIterator();
1036 i.atEnd() == false; i++)
1038 MapBlock *block = i.getNode()->getValue();
1039 modified_blocks.insert(block->getPos(), block);
1044 Set the modified blocks unsent for all the clients
1047 JMutexAutoLock lock2(m_con_mutex);
1049 for(core::map<u16, RemoteClient*>::Iterator
1050 i = m_clients.getIterator();
1051 i.atEnd() == false; i++)
1053 RemoteClient *client = i.getNode()->getValue();
1055 if(modified_blocks.size() > 0)
1057 // Remove block from sent history
1058 client->SetBlocksNotSent(modified_blocks);
1065 // Periodically print some info
1067 static float counter = 0.0;
1073 JMutexAutoLock lock2(m_con_mutex);
1075 for(core::map<u16, RemoteClient*>::Iterator
1076 i = m_clients.getIterator();
1077 i.atEnd() == false; i++)
1079 //u16 peer_id = i.getNode()->getKey();
1080 RemoteClient *client = i.getNode()->getValue();
1081 client->PrintInfo(std::cout);
1086 // Run time- and client- related stuff
1087 // NOTE: If you intend to add something here, check that it
1088 // doesn't fit in RemoteClient::GetNextBlocks for example.
1090 // Clients are behind connection lock
1091 JMutexAutoLock lock(m_con_mutex);
1093 for(core::map<u16, RemoteClient*>::Iterator
1094 i = m_clients.getIterator();
1095 i.atEnd() == false; i++)
1097 RemoteClient *client = i.getNode()->getValue();
1098 //con::Peer *peer = m_con.GetPeer(client->peer_id);
1099 //client->RunSendingTimeouts(dtime, peer->resend_timeout);
1103 // Send blocks to clients
1106 // Send object positions
1108 static float counter = 0.0;
1110 if(counter >= g_settings.getFloat("objectdata_interval"))
1112 JMutexAutoLock lock1(m_env_mutex);
1113 JMutexAutoLock lock2(m_con_mutex);
1114 SendObjectData(counter);
1120 // Trigger emergethread (it gets somehow gets to a
1121 // non-triggered but bysy state sometimes)
1123 static float counter = 0.0;
1129 m_emergethread.trigger();
1135 static float counter = 0.0;
1137 if(counter >= SERVER_MAP_SAVE_INTERVAL)
1141 JMutexAutoLock lock(m_env_mutex);
1142 // Save only changed parts
1143 m_env.getMap().save(true);
1148 void Server::Receive()
1150 DSTACK(__FUNCTION_NAME);
1151 u32 data_maxsize = 10000;
1152 Buffer<u8> data(data_maxsize);
1157 JMutexAutoLock lock(m_con_mutex);
1158 datasize = m_con.Receive(peer_id, *data, data_maxsize);
1160 ProcessData(*data, datasize, peer_id);
1162 catch(con::InvalidIncomingDataException &e)
1164 derr_server<<"Server::Receive(): "
1165 "InvalidIncomingDataException: what()="
1166 <<e.what()<<std::endl;
1168 catch(con::PeerNotFoundException &e)
1170 //NOTE: This is not needed anymore
1172 // The peer has been disconnected.
1173 // Find the associated player and remove it.
1175 /*JMutexAutoLock envlock(m_env_mutex);
1177 dout_server<<"ServerThread: peer_id="<<peer_id
1178 <<" has apparently closed connection. "
1179 <<"Removing player."<<std::endl;
1181 m_env.removePlayer(peer_id);*/
1185 void Server::ProcessData(u8 *data, u32 datasize, u16 peer_id)
1187 DSTACK(__FUNCTION_NAME);
1188 // Environment is locked first.
1189 JMutexAutoLock envlock(m_env_mutex);
1190 JMutexAutoLock conlock(m_con_mutex);
1194 peer = m_con.GetPeer(peer_id);
1196 catch(con::PeerNotFoundException &e)
1198 derr_server<<DTIME<<"Server::ProcessData(): Cancelling: peer "
1199 <<peer_id<<" not found"<<std::endl;
1203 //u8 peer_ser_ver = peer->serialization_version;
1204 u8 peer_ser_ver = getClient(peer->id)->serialization_version;
1212 ToServerCommand command = (ToServerCommand)readU16(&data[0]);
1214 if(command == TOSERVER_INIT)
1216 // [0] u16 TOSERVER_INIT
1217 // [2] u8 SER_FMT_VER_HIGHEST
1218 // [3] u8[20] player_name
1223 derr_server<<DTIME<<"Server: Got TOSERVER_INIT from "
1224 <<peer->id<<std::endl;
1226 // First byte after command is maximum supported
1227 // serialization version
1228 u8 client_max = data[2];
1229 u8 our_max = SER_FMT_VER_HIGHEST;
1230 // Use the highest version supported by both
1231 u8 deployed = core::min_(client_max, our_max);
1232 // If it's lower than the lowest supported, give up.
1233 if(deployed < SER_FMT_VER_LOWEST)
1234 deployed = SER_FMT_VER_INVALID;
1236 //peer->serialization_version = deployed;
1237 getClient(peer->id)->pending_serialization_version = deployed;
1239 if(deployed == SER_FMT_VER_INVALID)
1241 derr_server<<DTIME<<"Server: Cannot negotiate "
1242 "serialization version with peer "
1243 <<peer_id<<std::endl;
1251 Player *player = m_env.getPlayer(peer_id);
1253 // Check if player doesn't exist
1255 throw con::InvalidIncomingDataException
1256 ("Server::ProcessData(): INIT: Player doesn't exist");
1258 // update name if it was supplied
1259 if(datasize >= 20+3)
1262 player->updateName((const char*)&data[3]);
1265 // Now answer with a TOCLIENT_INIT
1267 SharedBuffer<u8> reply(2+1+6);
1268 writeU16(&reply[0], TOCLIENT_INIT);
1269 writeU8(&reply[2], deployed);
1270 writeV3S16(&reply[3], floatToInt(player->getPosition()+v3f(0,BS/2,0)));
1272 m_con.Send(peer_id, 0, reply, true);
1276 if(command == TOSERVER_INIT2)
1278 derr_server<<DTIME<<"Server: Got TOSERVER_INIT2 from "
1279 <<peer->id<<std::endl;
1282 getClient(peer->id)->serialization_version
1283 = getClient(peer->id)->pending_serialization_version;
1286 Send some initialization data
1289 // Send player info to all players
1292 // Send inventory to player
1293 SendInventory(peer->id);
1298 if(peer_ser_ver == SER_FMT_VER_INVALID)
1300 derr_server<<DTIME<<"Server::ProcessData(): Cancelling: Peer"
1301 " serialization format invalid or not initialized."
1302 " Skipping incoming command="<<command<<std::endl;
1306 Player *player = m_env.getPlayer(peer_id);
1309 derr_server<<"Server::ProcessData(): Cancelling: "
1310 "No player for peer_id="<<peer_id
1314 if(command == TOSERVER_PLAYERPOS)
1316 if(datasize < 2+12+12+4+4)
1320 v3s32 ps = readV3S32(&data[start+2]);
1321 v3s32 ss = readV3S32(&data[start+2+12]);
1322 f32 pitch = (f32)readS32(&data[2+12+12]) / 100.0;
1323 f32 yaw = (f32)readS32(&data[2+12+12+4]) / 100.0;
1324 v3f position((f32)ps.X/100., (f32)ps.Y/100., (f32)ps.Z/100.);
1325 v3f speed((f32)ss.X/100., (f32)ss.Y/100., (f32)ss.Z/100.);
1326 pitch = wrapDegrees(pitch);
1327 yaw = wrapDegrees(yaw);
1328 player->setPosition(position);
1329 player->setSpeed(speed);
1330 player->setPitch(pitch);
1331 player->setYaw(yaw);
1333 /*dout_server<<"Server::ProcessData(): Moved player "<<peer_id<<" to "
1334 <<"("<<position.X<<","<<position.Y<<","<<position.Z<<")"
1335 <<" pitch="<<pitch<<" yaw="<<yaw<<std::endl;*/
1337 else if(command == TOSERVER_GOTBLOCKS)
1350 u16 count = data[2];
1351 for(u16 i=0; i<count; i++)
1353 if((s16)datasize < 2+1+(i+1)*6)
1354 throw con::InvalidIncomingDataException
1355 ("GOTBLOCKS length is too short");
1356 v3s16 p = readV3S16(&data[2+1+i*6]);
1357 /*dstream<<"Server: GOTBLOCKS ("
1358 <<p.X<<","<<p.Y<<","<<p.Z<<")"<<std::endl;*/
1359 RemoteClient *client = getClient(peer_id);
1360 client->GotBlock(p);
1363 else if(command == TOSERVER_DELETEDBLOCKS)
1376 u16 count = data[2];
1377 for(u16 i=0; i<count; i++)
1379 if((s16)datasize < 2+1+(i+1)*6)
1380 throw con::InvalidIncomingDataException
1381 ("DELETEDBLOCKS length is too short");
1382 v3s16 p = readV3S16(&data[2+1+i*6]);
1383 /*dstream<<"Server: DELETEDBLOCKS ("
1384 <<p.X<<","<<p.Y<<","<<p.Z<<")"<<std::endl;*/
1385 RemoteClient *client = getClient(peer_id);
1386 client->SetBlockNotSent(p);
1389 else if(command == TOSERVER_CLICK_OBJECT)
1396 [2] u8 button (0=left, 1=right)
1401 u8 button = readU8(&data[2]);
1403 p.X = readS16(&data[3]);
1404 p.Y = readS16(&data[5]);
1405 p.Z = readS16(&data[7]);
1406 s16 id = readS16(&data[9]);
1407 //u16 item_i = readU16(&data[11]);
1409 MapBlock *block = NULL;
1412 block = m_env.getMap().getBlockNoCreate(p);
1414 catch(InvalidPositionException &e)
1416 derr_server<<"PICK_OBJECT block not found"<<std::endl;
1420 MapBlockObject *obj = block->getObject(id);
1424 derr_server<<"PICK_OBJECT object not found"<<std::endl;
1428 //TODO: Check that object is reasonably close
1433 if(g_settings.getBool("creative_mode") == false)
1436 // Skip if inventory has no free space
1437 if(player->inventory.getUsedSlots() == player->inventory.getSize())
1439 dout_server<<"Player inventory has no free space"<<std::endl;
1443 // Add to inventory and send inventory
1444 InventoryItem *item = new MapBlockObjectItem
1445 (obj->getInventoryString());
1446 player->inventory.addItem(item);
1447 SendInventory(player->peer_id);
1450 // Remove from block
1451 block->removeObject(id);
1454 else if(command == TOSERVER_CLICK_GROUND)
1461 [2] u8 button (0=left, 1=right)
1462 [3] v3s16 nodepos_undersurface
1463 [9] v3s16 nodepos_abovesurface
1466 u8 button = readU8(&data[2]);
1468 p_under.X = readS16(&data[3]);
1469 p_under.Y = readS16(&data[5]);
1470 p_under.Z = readS16(&data[7]);
1472 p_over.X = readS16(&data[9]);
1473 p_over.Y = readS16(&data[11]);
1474 p_over.Z = readS16(&data[13]);
1475 u16 item_i = readU16(&data[15]);
1477 //TODO: Check that target is reasonably close
1480 Left button digs ground
1485 core::map<v3s16, MapBlock*> modified_blocks;
1491 // Get material at position
1492 material = m_env.getMap().getNode(p_under).d;
1493 // If it's not diggable, do nothing
1494 if(material_diggable(material) == false)
1499 catch(InvalidPositionException &e)
1501 derr_server<<"Server: Ignoring REMOVENODE: Node not found"
1506 // Reset build time counter
1507 getClient(peer->id)->m_time_from_building.set(0.0);
1511 SharedBuffer<u8> reply(replysize);
1512 writeU16(&reply[0], TOCLIENT_REMOVENODE);
1513 writeS16(&reply[2], p_under.X);
1514 writeS16(&reply[4], p_under.Y);
1515 writeS16(&reply[6], p_under.Z);
1517 m_con.SendToAll(0, reply, true);
1519 if(g_settings.getBool("creative_mode") == false)
1521 // Add to inventory and send inventory
1522 InventoryItem *item = new MaterialItem(material, 1);
1523 player->inventory.addItem(item);
1524 SendInventory(player->peer_id);
1529 (this takes some time so it is done after the quick stuff)
1531 m_env.getMap().removeNodeAndUpdate(p_under, modified_blocks);
1537 // Update water pressure around modification
1538 // This also adds it to m_flow_active_nodes if appropriate
1540 MapVoxelManipulator v(&m_env.getMap());
1542 VoxelArea area(p_under-v3s16(1,1,1), p_under+v3s16(1,1,1));
1546 v.updateAreaWaterPressure(area, m_flow_active_nodes);
1548 catch(ProcessingLimitException &e)
1550 dstream<<"Processing limit reached"<<std::endl;
1553 v.blitBack(modified_blocks);
1555 // Add the node to m_flow_active_nodes.
1556 //m_flow_active_nodes[p_under] = 1;
1560 Right button places blocks and stuff
1562 else if(button == 1)
1566 InventoryItem *item = player->inventory.getItem(item_i);
1568 // If there is no item, it is not possible to add it anywhere
1573 Handle material items
1575 if(std::string("MaterialItem") == item->getName())
1577 MaterialItem *mitem = (MaterialItem*)item;
1580 n.d = mitem->getMaterial();
1583 // Don't add a node if this is not a free space
1584 MapNode n2 = m_env.getMap().getNode(p_over);
1585 if(material_buildable_to(n2.d) == false)
1588 catch(InvalidPositionException &e)
1590 derr_server<<"Server: Ignoring ADDNODE: Node not found"
1595 // Reset build time counter
1596 getClient(peer->id)->m_time_from_building.set(0.0);
1598 if(g_settings.getBool("creative_mode") == false)
1600 // Remove from inventory and send inventory
1601 if(mitem->getCount() == 1)
1602 player->inventory.deleteItem(item_i);
1606 SendInventory(peer_id);
1610 u32 replysize = 8 + MapNode::serializedLength(peer_ser_ver);
1611 SharedBuffer<u8> reply(replysize);
1612 writeU16(&reply[0], TOCLIENT_ADDNODE);
1613 writeS16(&reply[2], p_over.X);
1614 writeS16(&reply[4], p_over.Y);
1615 writeS16(&reply[6], p_over.Z);
1616 n.serialize(&reply[8], peer_ser_ver);
1618 m_con.SendToAll(0, reply, true);
1623 This takes some time so it is done after the quick stuff
1625 core::map<v3s16, MapBlock*> modified_blocks;
1626 m_env.getMap().addNodeAndUpdate(p_over, n, modified_blocks);
1629 Handle block object items
1631 else if(std::string("MBOItem") == item->getName())
1633 MapBlockObjectItem *oitem = (MapBlockObjectItem*)item;
1635 /*dout_server<<"Trying to place a MapBlockObjectItem: "
1636 "inventorystring=\""
1637 <<oitem->getInventoryString()
1638 <<"\""<<std::endl;*/
1640 v3s16 blockpos = getNodeBlockPos(p_over);
1642 MapBlock *block = NULL;
1645 block = m_env.getMap().getBlockNoCreate(blockpos);
1647 catch(InvalidPositionException &e)
1649 derr_server<<"Error while placing object: "
1650 "block not found"<<std::endl;
1654 v3s16 block_pos_i_on_map = block->getPosRelative();
1655 v3f block_pos_f_on_map = intToFloat(block_pos_i_on_map);
1657 v3f pos = intToFloat(p_over);
1658 pos -= block_pos_f_on_map;
1660 /*dout_server<<"pos="
1661 <<"("<<pos.X<<","<<pos.Y<<","<<pos.Z<<")"
1665 MapBlockObject *obj = oitem->createObject
1666 (pos, player->getYaw(), player->getPitch());
1669 derr_server<<"WARNING: oitem created NULL object"
1672 block->addObject(obj);
1674 //dout_server<<"Placed object"<<std::endl;
1676 if(g_settings.getBool("creative_mode") == false)
1678 // Remove from inventory and send inventory
1679 player->inventory.deleteItem(item_i);
1681 SendInventory(peer_id);
1687 Catch invalid buttons
1691 derr_server<<"WARNING: Server: Invalid button "
1692 <<button<<std::endl;
1695 else if(command == TOSERVER_RELEASE)
1706 else if(command == TOSERVER_SIGNTEXT)
1715 std::string datastring((char*)&data[2], datasize-2);
1716 std::istringstream is(datastring, std::ios_base::binary);
1719 is.read((char*)buf, 6);
1720 v3s16 blockpos = readV3S16(buf);
1721 is.read((char*)buf, 2);
1722 s16 id = readS16(buf);
1723 is.read((char*)buf, 2);
1724 u16 textlen = readU16(buf);
1726 for(u16 i=0; i<textlen; i++)
1728 is.read((char*)buf, 1);
1729 text += (char)buf[0];
1732 MapBlock *block = NULL;
1735 block = m_env.getMap().getBlockNoCreate(blockpos);
1737 catch(InvalidPositionException &e)
1739 derr_server<<"Error while setting sign text: "
1740 "block not found"<<std::endl;
1744 MapBlockObject *obj = block->getObject(id);
1747 derr_server<<"Error while setting sign text: "
1748 "object not found"<<std::endl;
1752 if(obj->getTypeId() != MAPBLOCKOBJECT_TYPE_SIGN)
1754 derr_server<<"Error while setting sign text: "
1755 "object is not a sign"<<std::endl;
1759 ((SignObject*)obj)->setText(text);
1761 obj->getBlock()->setChangedFlag();
1765 derr_server<<"WARNING: Server::ProcessData(): Ignoring "
1766 "unknown command "<<command<<std::endl;
1770 catch(SendFailedException &e)
1772 derr_server<<"Server::ProcessData(): SendFailedException: "
1778 /*void Server::Send(u16 peer_id, u16 channelnum,
1779 SharedBuffer<u8> data, bool reliable)
1781 JMutexAutoLock lock(m_con_mutex);
1782 m_con.Send(peer_id, channelnum, data, reliable);
1785 void Server::SendBlockNoLock(u16 peer_id, MapBlock *block, u8 ver)
1787 DSTACK(__FUNCTION_NAME);
1789 Create a packet with the block in the right format
1792 std::ostringstream os(std::ios_base::binary);
1793 block->serialize(os, ver);
1794 std::string s = os.str();
1795 SharedBuffer<u8> blockdata((u8*)s.c_str(), s.size());
1797 u32 replysize = 8 + blockdata.getSize();
1798 SharedBuffer<u8> reply(replysize);
1799 v3s16 p = block->getPos();
1800 writeU16(&reply[0], TOCLIENT_BLOCKDATA);
1801 writeS16(&reply[2], p.X);
1802 writeS16(&reply[4], p.Y);
1803 writeS16(&reply[6], p.Z);
1804 memcpy(&reply[8], *blockdata, blockdata.getSize());
1809 m_con.Send(peer_id, 1, reply, true);
1812 /*void Server::SendBlock(u16 peer_id, MapBlock *block, u8 ver)
1814 JMutexAutoLock conlock(m_con_mutex);
1816 SendBlockNoLock(peer_id, block, ver);
1820 void Server::SendSectorMeta(u16 peer_id, core::list<v2s16> ps, u8 ver)
1822 DSTACK(__FUNCTION_NAME);
1823 dstream<<"Server sending sector meta of "
1824 <<ps.getSize()<<" sectors"<<std::endl;
1826 core::list<v2s16>::Iterator i = ps.begin();
1827 core::list<v2s16> sendlist;
1830 if(sendlist.size() == 255 || i == ps.end())
1832 if(sendlist.size() == 0)
1837 [3...] v2s16 pos + sector metadata
1839 std::ostringstream os(std::ios_base::binary);
1842 writeU16(buf, TOCLIENT_SECTORMETA);
1843 os.write((char*)buf, 2);
1845 writeU8(buf, sendlist.size());
1846 os.write((char*)buf, 1);
1848 for(core::list<v2s16>::Iterator
1849 j = sendlist.begin();
1850 j != sendlist.end(); j++)
1853 writeV2S16(buf, *j);
1854 os.write((char*)buf, 4);
1857 Write ClientMapSector metadata
1861 [0] u8 serialization version
1868 In which corners are in these positions
1877 os.write((char*)buf, 1);
1880 // TODO: Get real values
1882 ((ServerMap&)m_env.getMap()).getSectorCorners(*j, corners);
1884 writeS16(buf, corners[0]);
1885 os.write((char*)buf, 2);
1886 writeS16(buf, corners[1]);
1887 os.write((char*)buf, 2);
1888 writeS16(buf, corners[2]);
1889 os.write((char*)buf, 2);
1890 writeS16(buf, corners[3]);
1891 os.write((char*)buf, 2);
1894 SharedBuffer<u8> data((u8*)os.str().c_str(), os.str().size());
1896 /*dstream<<"Server::SendSectorMeta(): sending packet"
1897 " with "<<sendlist.size()<<" sectors"<<std::endl;*/
1899 m_con.Send(peer_id, 1, data, true);
1907 sendlist.push_back(*i);
1913 core::list<PlayerInfo> Server::getPlayerInfo()
1915 DSTACK(__FUNCTION_NAME);
1916 JMutexAutoLock envlock(m_env_mutex);
1917 JMutexAutoLock conlock(m_con_mutex);
1919 core::list<PlayerInfo> list;
1921 core::list<Player*> players = m_env.getPlayers();
1923 core::list<Player*>::Iterator i;
1924 for(i = players.begin();
1925 i != players.end(); i++)
1929 Player *player = *i;
1931 con::Peer *peer = m_con.GetPeer(player->peer_id);
1933 info.address = peer->address;
1934 info.avg_rtt = peer->avg_rtt;
1936 catch(con::PeerNotFoundException &e)
1938 // Outdated peer info
1940 info.address = Address(0,0,0,0,0);
1944 snprintf(info.name, PLAYERNAME_SIZE, "%s", player->getName());
1945 info.position = player->getPosition();
1947 list.push_back(info);
1953 void Server::peerAdded(con::Peer *peer)
1955 DSTACK(__FUNCTION_NAME);
1956 dout_server<<"Server::peerAdded(): peer->id="
1957 <<peer->id<<std::endl;
1959 // Connection is already locked when this is called.
1960 //JMutexAutoLock lock(m_con_mutex);
1963 core::map<u16, RemoteClient*>::Node *n;
1964 n = m_clients.find(peer->id);
1965 // The client shouldn't already exist
1969 RemoteClient *client = new RemoteClient();
1970 client->peer_id = peer->id;
1971 m_clients.insert(client->peer_id, client);
1975 // Already locked when called
1976 //JMutexAutoLock envlock(m_env_mutex);
1978 Player *player = m_env.getPlayer(peer->id);
1980 // The player shouldn't already exist
1981 assert(player == NULL);
1983 player = new RemotePlayer();
1984 player->peer_id = peer->id;
1990 // Get zero sector (it could have been unloaded to disk)
1991 m_env.getMap().emergeSector(v2s16(0,0));
1992 // Get ground height at origin
1993 f32 groundheight = m_env.getMap().getGroundHeight(v2s16(0,0), true);
1994 // The zero sector should have been generated
1995 assert(groundheight > GROUNDHEIGHT_VALID_MINVALUE);
1996 // Don't go underwater
1997 if(groundheight < WATER_LEVEL)
1998 groundheight = WATER_LEVEL;
2000 player->setPosition(intToFloat(v3s16(
2007 Add player to environment
2010 m_env.addPlayer(player);
2013 Add stuff to inventory
2016 if(g_settings.getBool("creative_mode"))
2018 // Give all materials
2019 assert(USEFUL_MATERIAL_COUNT <= PLAYER_INVENTORY_SIZE);
2020 for(u16 i=0; i<USEFUL_MATERIAL_COUNT; i++)
2022 InventoryItem *item = new MaterialItem(i, 1);
2023 player->inventory.addItem(item);
2027 InventoryItem *item = new MapBlockObjectItem("Sign Example text");
2028 bool r = player->inventory.addItem(item);
2033 InventoryItem *item = new MapBlockObjectItem("Rat");
2034 bool r = player->inventory.addItem(item);
2042 InventoryItem *item = new MaterialItem(3, 999);
2043 bool r = player->inventory.addItem(item);
2047 for(u16 i=0; i<4; i++)
2049 InventoryItem *item = new MapBlockObjectItem("Sign Example text");
2050 bool r = player->inventory.addItem(item);
2054 for(u16 i=0; i<4; i++)
2056 InventoryItem *item = new MapBlockObjectItem("Rat");
2057 bool r = player->inventory.addItem(item);
2064 void Server::deletingPeer(con::Peer *peer, bool timeout)
2066 DSTACK(__FUNCTION_NAME);
2067 dout_server<<"Server::deletingPeer(): peer->id="
2068 <<peer->id<<", timeout="<<timeout<<std::endl;
2070 // Connection is already locked when this is called.
2071 //JMutexAutoLock lock(m_con_mutex);
2074 core::map<u16, RemoteClient*>::Node *n;
2075 n = m_clients.find(peer->id);
2076 // The client should exist
2081 // Already locked when called
2082 //JMutexAutoLock envlock(m_env_mutex);
2083 m_env.removePlayer(peer->id);
2087 delete m_clients[peer->id];
2088 m_clients.remove(peer->id);
2090 // Send player info to all clients
2094 void Server::SendObjectData(float dtime)
2096 DSTACK(__FUNCTION_NAME);
2098 core::map<v3s16, bool> stepped_blocks;
2100 for(core::map<u16, RemoteClient*>::Iterator
2101 i = m_clients.getIterator();
2102 i.atEnd() == false; i++)
2104 u16 peer_id = i.getNode()->getKey();
2105 RemoteClient *client = i.getNode()->getValue();
2106 assert(client->peer_id == peer_id);
2108 if(client->serialization_version == SER_FMT_VER_INVALID)
2111 client->SendObjectData(this, dtime, stepped_blocks);
2115 void Server::SendPlayerInfos()
2117 DSTACK(__FUNCTION_NAME);
2119 //JMutexAutoLock envlock(m_env_mutex);
2121 core::list<Player*> players = m_env.getPlayers();
2123 u32 player_count = players.getSize();
2124 u32 datasize = 2+(2+PLAYERNAME_SIZE)*player_count;
2126 SharedBuffer<u8> data(datasize);
2127 writeU16(&data[0], TOCLIENT_PLAYERINFO);
2130 core::list<Player*>::Iterator i;
2131 for(i = players.begin();
2132 i != players.end(); i++)
2134 Player *player = *i;
2136 /*dstream<<"Server sending player info for player with "
2137 "peer_id="<<player->peer_id<<std::endl;*/
2139 writeU16(&data[start], player->peer_id);
2140 snprintf((char*)&data[start+2], PLAYERNAME_SIZE, "%s", player->getName());
2141 start += 2+PLAYERNAME_SIZE;
2144 //JMutexAutoLock conlock(m_con_mutex);
2147 m_con.SendToAll(0, data, true);
2150 void Server::SendInventory(u16 peer_id)
2152 DSTACK(__FUNCTION_NAME);
2154 //JMutexAutoLock envlock(m_env_mutex);
2156 Player* player = m_env.getPlayer(peer_id);
2158 std::ostringstream os;
2159 //os.imbue(std::locale("C"));
2161 player->inventory.serialize(os);
2163 std::string s = os.str();
2165 SharedBuffer<u8> data(s.size()+2);
2166 writeU16(&data[0], TOCLIENT_INVENTORY);
2167 memcpy(&data[2], s.c_str(), s.size());
2169 //JMutexAutoLock conlock(m_con_mutex);
2172 m_con.Send(peer_id, 0, data, true);
2175 void Server::SendBlocks(float dtime)
2177 DSTACK(__FUNCTION_NAME);
2179 JMutexAutoLock envlock(m_env_mutex);
2181 core::array<PrioritySortedBlockTransfer> queue;
2183 s32 total_sending = 0;
2185 for(core::map<u16, RemoteClient*>::Iterator
2186 i = m_clients.getIterator();
2187 i.atEnd() == false; i++)
2189 RemoteClient *client = i.getNode()->getValue();
2190 assert(client->peer_id == i.getNode()->getKey());
2192 total_sending += client->SendingCount();
2194 if(client->serialization_version == SER_FMT_VER_INVALID)
2197 client->GetNextBlocks(this, dtime, queue);
2201 // Lowest priority number comes first.
2202 // Lowest is most important.
2205 JMutexAutoLock conlock(m_con_mutex);
2207 for(u32 i=0; i<queue.size(); i++)
2209 //TODO: Calculate limit dynamically
2210 if(total_sending >= g_settings.getS32
2211 ("max_simultaneous_block_sends_server_total"))
2214 PrioritySortedBlockTransfer q = queue[i];
2216 MapBlock *block = NULL;
2219 block = m_env.getMap().getBlockNoCreate(q.pos);
2221 catch(InvalidPositionException &e)
2226 RemoteClient *client = getClient(q.peer_id);
2228 SendBlockNoLock(q.peer_id, block, client->serialization_version);
2230 client->SentBlock(q.pos);
2237 RemoteClient* Server::getClient(u16 peer_id)
2239 DSTACK(__FUNCTION_NAME);
2240 //JMutexAutoLock lock(m_con_mutex);
2241 core::map<u16, RemoteClient*>::Node *n;
2242 n = m_clients.find(peer_id);
2243 // A client should exist for all peers
2245 return n->getValue();