3 Copyright (C) 2010-2014 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 Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21 #include "clientiface.h"
22 #include "network/connection.h"
23 #include "network/serveropcodes.h"
24 #include "remoteplayer.h"
27 #include "serverenvironment.h"
30 #include "server/luaentity_sao.h"
31 #include "server/player_sao.h"
34 #include "face_position_cache.h"
36 const char *ClientInterface::statenames[] = {
51 std::string ClientInterface::state2Name(ClientState state)
53 return statenames[state];
56 RemoteClient::RemoteClient() :
57 m_max_simul_sends(g_settings->getU16("max_simultaneous_block_sends_per_client")),
58 m_min_time_from_building(
59 g_settings->getFloat("full_block_send_enable_min_time_from_building")),
60 m_max_send_distance(g_settings->getS16("max_block_send_distance")),
61 m_block_optimize_distance(g_settings->getS16("block_send_optimize_distance")),
62 m_max_gen_distance(g_settings->getS16("max_block_generate_distance")),
63 m_occ_cull(g_settings->getBool("server_side_occlusion_culling"))
67 void RemoteClient::ResendBlockIfOnWire(v3s16 p)
69 // if this block is on wire, mark it for sending again as soon as possible
70 if (m_blocks_sending.find(p) != m_blocks_sending.end()) {
75 LuaEntitySAO *getAttachedObject(PlayerSAO *sao, ServerEnvironment *env)
77 if (!sao->isAttached())
84 sao->getAttachment(&id, &bone, &dummy, &dummy, &force_visible);
85 ServerActiveObject *ao = env->getActiveObject(id);
87 ao->getAttachment(&id, &bone, &dummy, &dummy, &force_visible);
89 ao = env->getActiveObject(id);
91 return dynamic_cast<LuaEntitySAO *>(ao);
94 void RemoteClient::GetNextBlocks (
95 ServerEnvironment *env,
96 EmergeManager * emerge,
98 std::vector<PrioritySortedBlockTransfer> &dest)
101 m_nothing_to_send_pause_timer -= dtime;
103 if (m_nothing_to_send_pause_timer >= 0)
106 RemotePlayer *player = env->getPlayer(peer_id);
107 // This can happen sometimes; clients and players are not in perfect sync.
111 PlayerSAO *sao = player->getPlayerSAO();
115 // Won't send anything if already sending
116 if (m_blocks_sending.size() >= m_max_simul_sends) {
117 //infostream<<"Not sending any blocks, Queue full."<<std::endl;
121 v3f playerpos = sao->getBasePosition();
122 // if the player is attached, get the velocity from the attached object
123 LuaEntitySAO *lsao = getAttachedObject(sao, env);
124 const v3f &playerspeed = lsao? lsao->getVelocity() : player->getSpeed();
125 v3f playerspeeddir(0,0,0);
126 if (playerspeed.getLength() > 1.0f * BS)
127 playerspeeddir = playerspeed / playerspeed.getLength();
128 // Predict to next block
129 v3f playerpos_predicted = playerpos + playerspeeddir * (MAP_BLOCKSIZE * BS);
131 v3s16 center_nodepos = floatToInt(playerpos_predicted, BS);
133 v3s16 center = getNodeBlockPos(center_nodepos);
135 // Camera position and direction
136 v3f camera_pos = sao->getEyePosition();
137 v3f camera_dir = v3f(0,0,1);
138 camera_dir.rotateYZBy(sao->getLookPitch());
139 camera_dir.rotateXZBy(sao->getRotation().Y);
141 u16 max_simul_sends_usually = m_max_simul_sends;
144 Check the time from last addNode/removeNode.
146 Decrease send rate if player is building stuff.
148 m_time_from_building += dtime;
149 if (m_time_from_building < m_min_time_from_building) {
150 max_simul_sends_usually
151 = LIMITED_MAX_SIMULTANEOUS_BLOCK_SENDS;
155 Number of blocks sending + number of blocks selected for sending
157 u32 num_blocks_selected = m_blocks_sending.size();
160 next time d will be continued from the d from which the nearest
161 unsent block was found this time.
163 This is because not necessarily any of the blocks found this
164 time are actually sent.
166 s32 new_nearest_unsent_d = -1;
168 // Get view range and camera fov (radians) from the client
169 s16 wanted_range = sao->getWantedRange() + 1;
170 float camera_fov = sao->getFov();
173 Get the starting value of the block finder radius.
175 if (m_last_center != center) {
176 m_nearest_unsent_d = 0;
177 m_last_center = center;
179 // reset the unsent distance if the view angle has changed more that 10% of the fov
180 // (this matches isBlockInSight which allows for an extra 10%)
181 if (camera_dir.dotProduct(m_last_camera_dir) < std::cos(camera_fov * 0.1f)) {
182 m_nearest_unsent_d = 0;
183 m_last_camera_dir = camera_dir;
185 if (m_nearest_unsent_d > 0) {
186 // make sure any blocks modified since the last time we sent blocks are resent
187 for (const v3s16 &p : m_blocks_modified) {
188 m_nearest_unsent_d = std::min(m_nearest_unsent_d, center.getDistanceFrom(p));
191 m_blocks_modified.clear();
193 s16 d_start = m_nearest_unsent_d;
195 // Distrust client-sent FOV and get server-set player object property
196 // zoom FOV (degrees) as a check to avoid hacked clients using FOV to load
198 // (zoom is disabled by value 0)
199 float prop_zoom_fov = sao->getZoomFOV() < 0.001f ?
201 std::max(camera_fov, sao->getZoomFOV() * core::DEGTORAD);
203 const s16 full_d_max = std::min(adjustDist(m_max_send_distance, prop_zoom_fov),
205 const s16 d_opt = std::min(adjustDist(m_block_optimize_distance, prop_zoom_fov),
207 const s16 d_blocks_in_sight = full_d_max * BS * MAP_BLOCKSIZE;
209 s16 d_max_gen = std::min(adjustDist(m_max_gen_distance, prop_zoom_fov),
212 s16 d_max = full_d_max;
214 // Don't loop very much at a time
215 s16 max_d_increment_at_time = 2;
216 if (d_max > d_start + max_d_increment_at_time)
217 d_max = d_start + max_d_increment_at_time;
219 // cos(angle between velocity and camera) * |velocity|
220 // Limit to 0.0f in case player moves backwards.
221 f32 dot = rangelim(camera_dir.dotProduct(playerspeed), 0.0f, 300.0f);
223 // Reduce the field of view when a player moves and looks forward.
224 // limit max fov effect to 50%, 60% at 20n/s fly speed
225 camera_fov = camera_fov / (1 + dot / 300.0f);
227 s32 nearest_emerged_d = -1;
228 s32 nearest_emergefull_d = -1;
229 s32 nearest_sent_d = -1;
230 //bool queue_is_full = false;
232 const v3s16 cam_pos_nodes = floatToInt(camera_pos, BS);
235 for (d = d_start; d <= d_max; d++) {
237 Get the border/face dot coordinates of a "d-radiused"
240 std::vector<v3s16> list = FacePositionCache::getFacePositions(d);
242 std::vector<v3s16>::iterator li;
243 for (li = list.begin(); li != list.end(); ++li) {
244 v3s16 p = *li + center;
248 - Don't allow too many simultaneous transfers
249 - EXCEPT when the blocks are very close
251 Also, don't send blocks that are already flying.
254 // Start with the usual maximum
255 u16 max_simul_dynamic = max_simul_sends_usually;
257 // If block is very close, allow full maximum
258 if (d <= BLOCK_SEND_DISABLE_LIMITS_MAX_D)
259 max_simul_dynamic = m_max_simul_sends;
261 // Don't select too many blocks for sending
262 if (num_blocks_selected >= max_simul_dynamic) {
263 //queue_is_full = true;
264 goto queue_full_break;
267 // Don't send blocks that are currently being transferred
268 if (m_blocks_sending.find(p) != m_blocks_sending.end())
272 Do not go over max mapgen limit
274 if (blockpos_over_max_limit(p))
277 // If this is true, inexistent block will be made from scratch
278 bool generate = d <= d_max_gen;
281 Don't generate or send if not in sight
282 FIXME This only works if the client uses a small enough
283 FOV setting. The default of 72 degrees is fine.
284 Also retrieve a smaller view cone in the direction of the player's
286 (0.1 is about 4 degrees)
289 if (!(isBlockInSight(p, camera_pos, camera_dir, camera_fov,
290 d_blocks_in_sight, &dist) ||
291 (playerspeed.getLength() > 1.0f * BS &&
292 isBlockInSight(p, camera_pos, playerspeeddir, 0.1f,
293 d_blocks_in_sight)))) {
298 Check if map has this block
300 MapBlock *block = env->getMap().getBlockNoCreateNoEx(p);
302 bool block_not_found = false;
304 // Reset usage timer, this block will be of use in the future.
305 block->resetUsageTimer();
308 Don't send already sent blocks
310 if (m_blocks_sent.find(p) != m_blocks_sent.end())
313 // Check whether the block exists (with data)
314 if (!block->isGenerated())
315 block_not_found = true;
318 If block is not close, don't send it unless it is near
321 Block is near ground level if night-time mesh
322 differs from day-time mesh.
325 if (!block->getIsUnderground() && !block->getDayNightDiff())
329 if (m_occ_cull && !block_not_found &&
330 env->getMap().isBlockOccluded(block, cam_pos_nodes)) {
336 If block has been marked to not exist on disk (dummy) or is
337 not generated and generating new ones is not wanted, skip block.
339 if (!generate && block_not_found) {
345 Add inexistent block to emerge queue.
347 if (block == NULL || block_not_found) {
348 if (emerge->enqueueBlockEmerge(peer_id, p, generate)) {
349 if (nearest_emerged_d == -1)
350 nearest_emerged_d = d;
352 if (nearest_emergefull_d == -1)
353 nearest_emergefull_d = d;
354 goto queue_full_break;
361 if (nearest_sent_d == -1)
365 Add block to send queue
367 PrioritySortedBlockTransfer q((float)dist, p, peer_id);
371 num_blocks_selected += 1;
376 // If nothing was found for sending and nothing was queued for
377 // emerging, continue next time browsing from here
378 if (nearest_emerged_d != -1) {
379 new_nearest_unsent_d = nearest_emerged_d;
380 } else if (nearest_emergefull_d != -1) {
381 new_nearest_unsent_d = nearest_emergefull_d;
383 if (d > full_d_max) {
384 new_nearest_unsent_d = 0;
385 m_nothing_to_send_pause_timer = 2.0f;
387 if (nearest_sent_d != -1)
388 new_nearest_unsent_d = nearest_sent_d;
390 new_nearest_unsent_d = d;
394 if (new_nearest_unsent_d != -1)
395 m_nearest_unsent_d = new_nearest_unsent_d;
398 void RemoteClient::GotBlock(v3s16 p)
400 if (m_blocks_sending.find(p) != m_blocks_sending.end()) {
401 m_blocks_sending.erase(p);
402 // only add to sent blocks if it actually was sending
403 // (it might have been modified since)
404 m_blocks_sent.insert(p);
406 m_excess_gotblocks++;
410 void RemoteClient::SentBlock(v3s16 p)
412 if (m_blocks_sending.find(p) == m_blocks_sending.end())
413 m_blocks_sending[p] = 0.0f;
415 infostream<<"RemoteClient::SentBlock(): Sent block"
416 " already in m_blocks_sending"<<std::endl;
419 void RemoteClient::SetBlockNotSent(v3s16 p)
421 m_nothing_to_send_pause_timer = 0;
423 // remove the block from sending and sent sets,
424 // and mark as modified if found
425 if (m_blocks_sending.erase(p) + m_blocks_sent.erase(p) > 0)
426 m_blocks_modified.insert(p);
429 void RemoteClient::SetBlocksNotSent(std::map<v3s16, MapBlock*> &blocks)
431 m_nothing_to_send_pause_timer = 0;
433 for (auto &block : blocks) {
434 v3s16 p = block.first;
435 // remove the block from sending and sent sets,
436 // and mark as modified if found
437 if (m_blocks_sending.erase(p) + m_blocks_sent.erase(p) > 0)
438 m_blocks_modified.insert(p);
442 void RemoteClient::notifyEvent(ClientStateEvent event)
444 std::ostringstream myerror;
448 //intentionally do nothing
453 m_state = CS_HelloSent;
456 m_state = CS_Disconnecting;
461 /* GotInit2 SetDefinitionsSent SetMediaSent */
463 myerror << "Created: Invalid client state transition! " << event;
464 throw ClientStateError(myerror.str());
468 /* don't do anything if in denied state */
474 m_state = CS_AwaitingInit2;
478 m_state = CS_Disconnecting;
485 myerror << "HelloSent: Invalid client state transition! " << event;
486 throw ClientStateError(myerror.str());
489 case CS_AwaitingInit2:
493 confirmSerializationVersion();
494 m_state = CS_InitDone;
497 m_state = CS_Disconnecting;
503 /* Init SetDefinitionsSent SetMediaSent */
505 myerror << "InitSent: Invalid client state transition! " << event;
506 throw ClientStateError(myerror.str());
513 case CSE_SetDefinitionsSent:
514 m_state = CS_DefinitionsSent;
517 m_state = CS_Disconnecting;
523 /* Init GotInit2 SetMediaSent */
525 myerror << "InitDone: Invalid client state transition! " << event;
526 throw ClientStateError(myerror.str());
529 case CS_DefinitionsSent:
532 case CSE_SetClientReady:
536 m_state = CS_Disconnecting;
541 /* Init GotInit2 SetDefinitionsSent */
543 myerror << "DefinitionsSent: Invalid client state transition! " << event;
544 throw ClientStateError(myerror.str());
554 m_state = CS_Disconnecting;
556 case CSE_SudoSuccess:
557 m_state = CS_SudoMode;
560 /* Init GotInit2 SetDefinitionsSent SetMediaSent SetDenied */
562 myerror << "Active: Invalid client state transition! " << event;
563 throw ClientStateError(myerror.str());
574 m_state = CS_Disconnecting;
580 myerror << "Active: Invalid client state transition! " << event;
581 throw ClientStateError(myerror.str());
585 case CS_Disconnecting:
586 /* we are already disconnecting */
591 void RemoteClient::resetChosenMech()
594 srp_verifier_delete((SRPVerifier *) auth_data);
597 chosen_mech = AUTH_MECHANISM_NONE;
600 u64 RemoteClient::uptime() const
602 return porting::getTimeS() - m_connection_time;
605 ClientInterface::ClientInterface(const std::shared_ptr<con::Connection> & con)
609 m_print_info_timer(0.0f)
613 ClientInterface::~ClientInterface()
619 RecursiveMutexAutoLock clientslock(m_clients_mutex);
621 for (auto &client_it : m_clients) {
623 delete client_it.second;
628 std::vector<session_t> ClientInterface::getClientIDs(ClientState min_state)
630 std::vector<session_t> reply;
631 RecursiveMutexAutoLock clientslock(m_clients_mutex);
633 for (const auto &m_client : m_clients) {
634 if (m_client.second->getState() >= min_state)
635 reply.push_back(m_client.second->peer_id);
641 void ClientInterface::markBlockposAsNotSent(const v3s16 &pos)
643 RecursiveMutexAutoLock clientslock(m_clients_mutex);
644 for (const auto &client : m_clients) {
645 if (client.second->getState() >= CS_Active)
646 client.second->SetBlockNotSent(pos);
651 * Verify if user limit was reached.
652 * User limit count all clients from HelloSent state (MT protocol user) to Active state
653 * @return true if user limit was reached
655 bool ClientInterface::isUserLimitReached()
657 return getClientIDs(CS_HelloSent).size() >= g_settings->getU16("max_users");
660 void ClientInterface::step(float dtime)
662 m_print_info_timer += dtime;
663 if (m_print_info_timer >= 30.0f) {
664 m_print_info_timer = 0.0f;
669 void ClientInterface::UpdatePlayerList()
672 std::vector<session_t> clients = getClientIDs();
673 m_clients_names.clear();
675 if (!clients.empty())
676 infostream<<"Players:"<<std::endl;
678 for (session_t i : clients) {
679 RemotePlayer *player = m_env->getPlayer(i);
684 infostream << "* " << player->getName() << "\t";
687 RecursiveMutexAutoLock clientslock(m_clients_mutex);
688 RemoteClient* client = lockedGetClientNoEx(i);
690 client->PrintInfo(infostream);
693 m_clients_names.emplace_back(player->getName());
698 void ClientInterface::send(session_t peer_id, u8 channelnum,
699 NetworkPacket *pkt, bool reliable)
701 m_con->Send(peer_id, channelnum, pkt, reliable);
704 void ClientInterface::sendToAll(NetworkPacket *pkt)
706 RecursiveMutexAutoLock clientslock(m_clients_mutex);
707 for (auto &client_it : m_clients) {
708 RemoteClient *client = client_it.second;
710 if (client->net_proto_version != 0) {
711 m_con->Send(client->peer_id,
712 clientCommandFactoryTable[pkt->getCommand()].channel, pkt,
713 clientCommandFactoryTable[pkt->getCommand()].reliable);
718 RemoteClient* ClientInterface::getClientNoEx(session_t peer_id, ClientState state_min)
720 RecursiveMutexAutoLock clientslock(m_clients_mutex);
721 RemoteClientMap::const_iterator n = m_clients.find(peer_id);
722 // The client may not exist; clients are immediately removed if their
723 // access is denied, and this event occurs later then.
724 if (n == m_clients.end())
727 if (n->second->getState() >= state_min)
733 RemoteClient* ClientInterface::lockedGetClientNoEx(session_t peer_id, ClientState state_min)
735 RemoteClientMap::const_iterator n = m_clients.find(peer_id);
736 // The client may not exist; clients are immediately removed if their
737 // access is denied, and this event occurs later then.
738 if (n == m_clients.end())
741 if (n->second->getState() >= state_min)
747 ClientState ClientInterface::getClientState(session_t peer_id)
749 RecursiveMutexAutoLock clientslock(m_clients_mutex);
750 RemoteClientMap::const_iterator n = m_clients.find(peer_id);
751 // The client may not exist; clients are immediately removed if their
752 // access is denied, and this event occurs later then.
753 if (n == m_clients.end())
756 return n->second->getState();
759 void ClientInterface::setPlayerName(session_t peer_id, const std::string &name)
761 RecursiveMutexAutoLock clientslock(m_clients_mutex);
762 RemoteClientMap::iterator n = m_clients.find(peer_id);
763 // The client may not exist; clients are immediately removed if their
764 // access is denied, and this event occurs later then.
765 if (n != m_clients.end())
766 n->second->setName(name);
769 void ClientInterface::DeleteClient(session_t peer_id)
771 RecursiveMutexAutoLock conlock(m_clients_mutex);
774 RemoteClientMap::iterator n = m_clients.find(peer_id);
775 // The client may not exist; clients are immediately removed if their
776 // access is denied, and this event occurs later then.
777 if (n == m_clients.end())
781 Mark objects to be not known by the client
783 //TODO this should be done by client destructor!!!
784 RemoteClient *client = n->second;
786 for (u16 id : client->m_known_objects) {
788 ServerActiveObject* obj = m_env->getActiveObject(id);
790 if(obj && obj->m_known_by_count > 0)
791 obj->m_known_by_count--;
795 delete m_clients[peer_id];
796 m_clients.erase(peer_id);
799 void ClientInterface::CreateClient(session_t peer_id)
801 RecursiveMutexAutoLock conlock(m_clients_mutex);
804 RemoteClientMap::iterator n = m_clients.find(peer_id);
805 // The client shouldn't already exist
806 if (n != m_clients.end()) return;
809 RemoteClient *client = new RemoteClient();
810 client->peer_id = peer_id;
811 m_clients[client->peer_id] = client;
814 void ClientInterface::event(session_t peer_id, ClientStateEvent event)
817 RecursiveMutexAutoLock clientlock(m_clients_mutex);
820 RemoteClientMap::iterator n = m_clients.find(peer_id);
822 // No client to deliver event
823 if (n == m_clients.end())
825 n->second->notifyEvent(event);
828 if ((event == CSE_SetClientReady) ||
829 (event == CSE_Disconnect) ||
830 (event == CSE_SetDenied))
836 u16 ClientInterface::getProtocolVersion(session_t peer_id)
838 RecursiveMutexAutoLock conlock(m_clients_mutex);
841 RemoteClientMap::iterator n = m_clients.find(peer_id);
843 // No client to get version
844 if (n == m_clients.end())
847 return n->second->net_proto_version;
850 void ClientInterface::setClientVersion(session_t peer_id, u8 major, u8 minor, u8 patch,
851 const std::string &full)
853 RecursiveMutexAutoLock conlock(m_clients_mutex);
856 RemoteClientMap::iterator n = m_clients.find(peer_id);
858 // No client to set versions
859 if (n == m_clients.end())
862 n->second->setVersionInfo(major, minor, patch, full);