aboutsummaryrefslogtreecommitdiff
path: root/advtrains/textures/advtrains_dtrack_detector_placer.png
blob: e6c6ad691d3188a593921af20dec1ebd594599eb (plain)
ofshex dumpascii
0000 89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 00 00 00 38 00 00 00 38 08 06 00 00 00 a8 86 3b .PNG........IHDR...8...8.......;
0020 1e 00 00 00 06 62 4b 47 44 00 ff 00 ff 00 ff a0 bd a7 93 00 00 00 09 70 48 59 73 00 00 0b 13 00 .....bKGD..............pHYs.....
0040 00 0b 13 01 00 9a 9c 18 00 00 00 07 74 49 4d 45 07 e0 0b 0a 15 18 04 5d 66 5d 8c 00 00 00 19 74 ............tIME.......]f].....t
0060 45 58 74 43 6f 6d 6d 65 6e 74 00 43 72 65 61 74 65 64 20 77 69 74 68 20 47 49 4d 50 57 81 0e 17 EXtComment.Created.with.GIMPW...
0080 00 00 04 4d 49 44 41 54 68 de ed da 6d 4c 53 57 18 07 f0 ff 69 0b 25 85 3a a1 d0 d9 44 2d 42 c3 ...MIDATh...mLSW....i.%.:...D-B.
00a0 0c ae 8d e2 4b 22 b4 4d 97 b9 2d 41 1d 61 51 3e 10 c8 96 18 65 f8 b2 98 a9 cb 0c 99 21 7e d0 65 ....K".M..-A.aQ>....e.......!~.e
00c0 f1 0b 8a 6e c6 10 4d 16 bf b8 cc 89 59 5c 58 95 d4 01 63 cb 32 9b 6c 11 b2 25 9b d2 25 eb 68 bb ...n..M.....Y\X...c.2.l..%..%.h.
00e0 a2 05 84 76 d3 b3 0f e4 76 97 db 7b 6f df 8b 98 73 be b6 b9 3c bf 3c ff f3 9c 7b 00 62 30 18 f0 ...v....v..{o...s...<.<...{.b0..
0100 2c 2f 05 9e f1 c5 80 0c c8 80 0c c8 80 0c c8 80 0c c8 80 0c c8 80 0c c8 80 0c c8 80 0c c8 80 0c ,/..............................
0120 c8 80 0c c8 80 59 5c 9b 36 6e a0 b9 06 aa 72 f1 43 de 39 b0 8f da 6c 56 00 c0 83 89 07 74 77 5b .....Y\.6n....r.C.9...lV.....tw[
0140 3b 59 94 c0 2b 1d e5 14 00 06 7e 7e 08 00 20 c6 66 70 b0 a9 c9 29 7c ed 74 e2 d1 a3 99 c5 19 d1 ;Y..+.....~~....fp...)|.t.......
0160 c6 cd 85 74 cc ff 04 20 04 c4 d8 0c 7b cb 39 d8 6c 56 4c 4d 4e e1 ea d5 2f 10 f8 3b 80 f5 35 35 ...t........{.9.lVLMN.../..;..55
0180 98 9c 0c 2d 4e e0 b2 62 05 fe 50 6f 07 b1 9c 10 85 f9 7c 7e 68 97 2c 41 7b fb db 68 6d 69 ce d9 ...-N..b..Po......|~h.,A{..hmi..
01a0 5e 24 a9 fc f9 8c 8b 22 17 47 61 14 5f ab df 86 cb 9f 5e 02 01 c1 b8 cf 07 93 c9 84 92 92 62 84 ^$.....".Ga._.....^...........b.
01c0 c3 11 7c ff d9 41 9c b9 3e 41 9e 5a 60 e3 e6 42 5a 6b d6 c1 a8 57 e2 54 9f 0e 87 0f bd 0b a2 20 ..|..A..>A.Z`..BZk...W.T........
01e0 51 98 70 0d 0d b8 10 0e 47 90 ff 4b 27 40 29 f8 7b 34 17 50 55 aa 51 2c b7 58 71 c4 02 49 18 00 Q.p.....G..K'@).{4.PU.Q,.Xq..I..
0200 8c 00 e8 bf b4 07 de e0 63 00 40 9d a5 14 46 bd 12 36 f3 73 dc 57 68 b6 a1 b2 1d 4c 24 8a 52 30 ........c.@...F..6.s.Wh....L$.R0
0220 6e 6d 31 18 08 00 b4 d7 6b a9 10 9a 8b 8e 4a 02 f9 51 1c 7c 58 9f 34 8c 5b bd 6d d5 f3 0a cf 35 nm1.....k.....J..Q.|X.4.[.m....5
0240 54 b6 83 fc 03 9a 3b c7 6a 6a d6 41 dd fa 16 00 60 87 0c 2c 78 b6 36 5a 38 57 fc 42 40 89 c1 60 T.....;.jj.A....`..,x.6Z8W.B@..`
0260 88 1b 45 0e c6 4d c5 15 87 8e 44 1f 50 2d f1 e0 ee c6 ca 98 c2 93 81 7a 02 c0 98 37 7d 28 d9 fb ..E..M....D.P-.........z...7}(..
0280 86 89 aa 94 04 3b 1d 65 73 85 98 4f 44 a7 a2 10 c6 1f f7 c1 2d af ce 03 f6 b6 55 a3 e1 fc ff bd .....;.es..OD.......-.....U.....
02a0 fc 7c 57 15 00 c0 1b 7c 9c 16 34 91 8e 5e ec b9 40 35 85 1a b8 5c df e0 e3 4f ce 93 98 0e 72 0f .|W....|..4..^..@5...\...O....r.
02c0 cf 53 29 a0 5a be 15 79 79 79 30 9b d7 88 c2 5a 5a df 24 dc f7 13 2d 3c 5b d0 8b 3d 17 68 91 b6 .S).Z..yyy0....ZZ.$...-<[..=.h..
02e0 68 ee b3 81 41 94 ea 74 38 d6 79 9c 48 ee c1 a3 ef bf 47 07 07 87 d0 f0 fa f6 b8 07 f4 69 af 97 h...A..t8.y.H.....G..........i..
0300 8e ee aa 42 ba 50 4f 60 ee f3 31 6f 7c a8 c7 4f b1 b2 14 98 ae e8 80 10 16 8e 44 e0 76 bb 71 e3 ...B.PO`..1o|..O..........D.v.q.
0320 ab 3e 22 3b 64 9a 9a 76 50 87 dd 8e 32 7d 59 cc 01 2d 56 38 bf 98 4c 76 f4 4f af 77 de eb dc de .>";d..vP...2}Y..-V8..Lv.O.w....
0340 c6 4a 34 ec ee 12 85 a9 d5 6a 8c 8f fb 60 b7 5b 11 f0 fb b1 ef c0 41 92 d0 14 e5 47 37 ba 47 b3 .J4......j...`.[......A....G7.G.
0360 0c b5 ee 1f 8e a9 a3 ef c6 97 b2 30 87 c3 0e 02 82 1f ef dc c1 c9 0f 3f 22 49 bf aa 65 0a ca 4d ...........0...........?"I..e..M
0380 46 31 e8 07 3d bf a6 05 5b a7 bc 22 3a 8c 92 7a 17 cd 46 47 85 51 e4 c3 fa fb 5d 28 28 50 a3 78 F1..=...[..":..z..FG.Q....]((P.x
03a0 e9 52 49 d8 a8 ab 5b 74 18 29 14 04 5d d7 82 24 a5 db 44 26 a1 7f ed 1f 8e be 30 88 75 6c e8 db .RI...[t.)..]..$..D&......0.ul..
03c0 61 d4 d5 d5 4a 46 51 38 8c ca 9f 57 e1 de f8 bf 88 fc f3 04 37 bf fb 3d b5 eb 52 3c a8 58 14 c5 a...JFQ8...W........7..=..R<.X..
03e0 a0 1e 3f 45 7e e7 30 b4 12 51 74 bb dd 58 b5 aa 22 26 8a 72 c7 cb 44 68 16 66 53 31 56 94 2a f1 ..?E~.0..Qt..X.."&.r..Dh.fS1V.*.
0400 d3 6f a1 f4 80 e9 76 34 de 54 74 38 ec 70 3a 6f 42 a7 d3 89 46 11 00 86 ee 86 d0 75 2d 18 7d fe .o....v4.Tt8.p:oB...F......u-.}.
0420 4e 9b 96 46 66 43 e8 fd 81 90 94 2f bc e9 42 c5 0e e8 78 53 51 38 75 85 51 74 8d e6 93 8c dd e8 N..FfC...../..B...xSQ8u.Qt......
0440 93 85 7a fc 73 50 dd a6 8e a4 a6 a2 dc f1 32 72 7f 7a 5e 14 2f df 9e cd 1d 50 0a 7a cb f7 32 34 ..z.sP........2r.z^./....P.z..24
0460 1a 4d d2 53 31 91 28 66 f4 77 32 a9 42 0b 2b 1a b0 76 ad 05 33 33 b3 b2 07 34 7f 18 25 1a c5 05 .M.S1.(f.w2.B.+..v..33...4..%...
0480 05 02 40 b9 71 25 ad ac 34 61 f5 ea 17 12 8a 22 07 1d b9 3f 0d 7d 49 01 36 54 15 c9 46 71 c1 81 ..@.q%..4a....."...?.}I.6T..Fq..
04a0 dc 32 9b 5f a4 db b6 d6 63 d4 d5 2d 3a 8c 84 51 04 80 57 d6 44 a8 f3 6e 7e 4a 77 42 b2 90 ff 75 .2._....c..-:..Q..W.D..n~JwB...u
04c0 cf df a3 4d 2f e9 d3 8a e2 53 09 cc 64 14 a5 d6 7f b8 8a cd 99 03 14 f8 4b 00 00 00 00 49 45 4e ...M/....S..d...........K....IEN
04e0 44 ae 42 60 82 D.B`.
n296' href='#n296'>296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909
/*
Minetest
Copyright (C) 2010-2014 celeron55, Perttu Ahola <celeron55@gmail.com>

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/

#include <sstream>
#include "clientiface.h"
#include "network/connection.h"
#include "network/serveropcodes.h"
#include "remoteplayer.h"
#include "settings.h"
#include "mapblock.h"
#include "serverenvironment.h"
#include "map.h"
#include "emerge.h"
#include "content_sao.h"              // TODO this is used for cleanup of only
#include "log.h"
#include "util/srp.h"
#include "face_position_cache.h"

const char *ClientInterface::statenames[] = {
	"Invalid",
	"Disconnecting",
	"Denied",
	"Created",
	"AwaitingInit2",
	"HelloSent",
	"InitDone",
	"DefinitionsSent",
	"Active",
	"SudoMode",
};



std::string ClientInterface::state2Name(ClientState state)
{
	return statenames[state];
}

RemoteClient::RemoteClient() :
	m_max_simul_sends(g_settings->getU16("max_simultaneous_block_sends_per_client")),
	m_min_time_from_building(
		g_settings->getFloat("full_block_send_enable_min_time_from_building")),
	m_max_send_distance(g_settings->getS16("max_block_send_distance")),
	m_block_optimize_distance(g_settings->getS16("block_send_optimize_distance")),
	m_max_gen_distance(g_settings->getS16("max_block_generate_distance")),
	m_occ_cull(g_settings->getBool("server_side_occlusion_culling"))
{
}

void RemoteClient::ResendBlockIfOnWire(v3s16 p)
{
	// if this block is on wire, mark it for sending again as soon as possible
	if (m_blocks_sending.find(p) != m_blocks_sending.end()) {
		SetBlockNotSent(p);
	}
}

LuaEntitySAO *getAttachedObject(PlayerSAO *sao, ServerEnvironment *env)
{
	if (!sao->isAttached())
		return nullptr;

	int id;
	std::string bone;
	v3f dummy;
	sao->getAttachment(&id, &bone, &dummy, &dummy);
	ServerActiveObject *ao = env->getActiveObject(id);
	while (id && ao) {
		ao->getAttachment(&id, &bone, &dummy, &dummy);
		if (id)
			ao = env->getActiveObject(id);
	}
	return dynamic_cast<LuaEntitySAO *>(ao);
}

void RemoteClient::GetNextBlocks (
		ServerEnvironment *env,
		EmergeManager * emerge,
		float dtime,
		std::vector<PrioritySortedBlockTransfer> &dest)
{
	// Increment timers
	m_nothing_to_send_pause_timer -= dtime;
	m_nearest_unsent_reset_timer += dtime;

	if (m_nothing_to_send_pause_timer >= 0)
		return;

	RemotePlayer *player = env->getPlayer(peer_id);
	// This can happen sometimes; clients and players are not in perfect sync.
	if (!player)
		return;

	PlayerSAO *sao = player->getPlayerSAO();
	if (!sao)
		return;

	// Won't send anything if already sending
	if (m_blocks_sending.size() >= m_max_simul_sends) {
		//infostream<<"Not sending any blocks, Queue full."<<std::endl;
		return;
	}

	v3f playerpos = sao->getBasePosition();
	// if the player is attached, get the velocity from the attached object
	LuaEntitySAO *lsao = getAttachedObject(sao, env);
	const v3f &playerspeed = lsao? lsao->getVelocity() : player->getSpeed();
	v3f playerspeeddir(0,0,0);
	if (playerspeed.getLength() > 1.0f * BS)
		playerspeeddir = playerspeed / playerspeed.getLength();
	// Predict to next block
	v3f playerpos_predicted = playerpos + playerspeeddir * (MAP_BLOCKSIZE * BS);

	v3s16 center_nodepos = floatToInt(playerpos_predicted, BS);

	v3s16 center = getNodeBlockPos(center_nodepos);

	// Camera position and direction
	v3f camera_pos = sao->getEyePosition();
	v3f camera_dir = v3f(0,0,1);
	camera_dir.rotateYZBy(sao->getLookPitch());
	camera_dir.rotateXZBy(sao->getRotation().Y);

	/*infostream<<"camera_dir=("<<camera_dir.X<<","<<camera_dir.Y<<","
			<<camera_dir.Z<<")"<<std::endl;*/

	/*
		Get the starting value of the block finder radius.
	*/

	if (m_last_center != center) {
		m_nearest_unsent_d = 0;
		m_last_center = center;
	}

	/*infostream<<"m_nearest_unsent_reset_timer="
			<<m_nearest_unsent_reset_timer<<std::endl;*/

	// Reset periodically to workaround for some bugs or stuff
	if (m_nearest_unsent_reset_timer > 20.0f) {
		m_nearest_unsent_reset_timer = 0.0f;
		m_nearest_unsent_d = 0;
		//infostream<<"Resetting m_nearest_unsent_d for "
		//		<<server->getPlayerName(peer_id)<<std::endl;
	}

	//s16 last_nearest_unsent_d = m_nearest_unsent_d;
	s16 d_start = m_nearest_unsent_d;

	//infostream<<"d_start="<<d_start<<std::endl;

	u16 max_simul_sends_usually = m_max_simul_sends;

	/*
		Check the time from last addNode/removeNode.

		Decrease send rate if player is building stuff.
	*/
	m_time_from_building += dtime;
	if (m_time_from_building < m_min_time_from_building) {
		max_simul_sends_usually
			= LIMITED_MAX_SIMULTANEOUS_BLOCK_SENDS;
	}

	/*
		Number of blocks sending + number of blocks selected for sending
	*/
	u32 num_blocks_selected = m_blocks_sending.size();

	/*
		next time d will be continued from the d from which the nearest
		unsent block was found this time.

		This is because not necessarily any of the blocks found this
		time are actually sent.
	*/
	s32 new_nearest_unsent_d = -1;

	// Get view range and camera fov (radians) from the client
	s16 wanted_range = sao->getWantedRange() + 1;
	float camera_fov = sao->getFov();

	// Distrust client-sent FOV and get server-set player object property
	// zoom FOV (degrees) as a check to avoid hacked clients using FOV to load
	// distant world.
	// (zoom is disabled by value 0)
	float prop_zoom_fov = sao->getZoomFOV() < 0.001f ?
		0.0f :
		std::max(camera_fov, sao->getZoomFOV() * core::DEGTORAD);

	const s16 full_d_max = std::min(adjustDist(m_max_send_distance, prop_zoom_fov),
		wanted_range);
	const s16 d_opt = std::min(adjustDist(m_block_optimize_distance, prop_zoom_fov),
		wanted_range);
	const s16 d_blocks_in_sight = full_d_max * BS * MAP_BLOCKSIZE;

	s16 d_max = full_d_max;
	s16 d_max_gen = std::min(adjustDist(m_max_gen_distance, prop_zoom_fov),
		wanted_range);

	// Don't loop very much at a time, adjust with distance,
	// do more work per RTT with greater distances.
	s16 max_d_increment_at_time = full_d_max / 9 + 1;
	if (d_max > d_start + max_d_increment_at_time)
		d_max = d_start + max_d_increment_at_time;

	// cos(angle between velocity and camera) * |velocity|
	// Limit to 0.0f in case player moves backwards.
	f32 dot = rangelim(camera_dir.dotProduct(playerspeed), 0.0f, 300.0f);

	// Reduce the field of view when a player moves and looks forward.
	// limit max fov effect to 50%, 60% at 20n/s fly speed
	camera_fov = camera_fov / (1 + dot / 300.0f);

	s32 nearest_emerged_d = -1;
	s32 nearest_emergefull_d = -1;
	s32 nearest_sent_d = -1;
	//bool queue_is_full = false;

	const v3s16 cam_pos_nodes = floatToInt(camera_pos, BS);

	s16 d;
	for (d = d_start; d <= d_max; d++) {
		/*
			Get the border/face dot coordinates of a "d-radiused"
			box
		*/
		std::vector<v3s16> list = FacePositionCache::getFacePositions(d);

		std::vector<v3s16>::iterator li;
		for (li = list.begin(); li != list.end(); ++li) {
			v3s16 p = *li + center;

			/*
				Send throttling
				- Don't allow too many simultaneous transfers
				- EXCEPT when the blocks are very close

				Also, don't send blocks that are already flying.
			*/

			// Start with the usual maximum
			u16 max_simul_dynamic = max_simul_sends_usually;

			// If block is very close, allow full maximum
			if (d <= BLOCK_SEND_DISABLE_LIMITS_MAX_D)
				max_simul_dynamic = m_max_simul_sends;

			// Don't select too many blocks for sending
			if (num_blocks_selected >= max_simul_dynamic) {
				//queue_is_full = true;
				goto queue_full_break;
			}

			// Don't send blocks that are currently being transferred
			if (m_blocks_sending.find(p) != m_blocks_sending.end())
				continue;

			/*
				Do not go over max mapgen limit
			*/
			if (blockpos_over_max_limit(p))
				continue;

			// If this is true, inexistent block will be made from scratch
			bool generate = d <= d_max_gen;

			/*
				Don't generate or send if not in sight
				FIXME This only works if the client uses a small enough
				FOV setting. The default of 72 degrees is fine.
				Also retrieve a smaller view cone in the direction of the player's
				movement.
				(0.1 is about 4 degrees)
			*/
			f32 dist;
			if (!(isBlockInSight(p, camera_pos, camera_dir, camera_fov,
						d_blocks_in_sight, &dist) ||
					(playerspeed.getLength() > 1.0f * BS &&
					isBlockInSight(p, camera_pos, playerspeeddir, 0.1f,
						d_blocks_in_sight)))) {
				continue;
			}

			/*
				Don't send already sent blocks
			*/
			if (m_blocks_sent.find(p) != m_blocks_sent.end())
				continue;

			/*
				Check if map has this block
			*/
			MapBlock *block = env->getMap().getBlockNoCreateNoEx(p);

			bool surely_not_found_on_disk = false;
			bool block_is_invalid = false;
			if (block) {
				// Reset usage timer, this block will be of use in the future.
				block->resetUsageTimer();

				// Block is dummy if data doesn't exist.
				// It means it has been not found from disk and not generated
				if (block->isDummy()) {
					surely_not_found_on_disk = true;
				}

				if (!block->isGenerated())
					block_is_invalid = true;

				/*
					If block is not close, don't send it unless it is near
					ground level.

					Block is near ground level if night-time mesh
					differs from day-time mesh.
				*/
				if (d >= d_opt) {
					if (!block->getIsUnderground() && !block->getDayNightDiff())
						continue;
				}

				if (m_occ_cull && !block_is_invalid &&
						env->getMap().isBlockOccluded(block, cam_pos_nodes)) {
					continue;
				}
			}

			/*
				If block has been marked to not exist on disk (dummy)
				and generating new ones is not wanted, skip block.
			*/
			if (!generate && surely_not_found_on_disk) {
				// get next one.
				continue;
			}

			/*
				Add inexistent block to emerge queue.
			*/
			if (block == NULL || surely_not_found_on_disk || block_is_invalid) {
				if (emerge->enqueueBlockEmerge(peer_id, p, generate)) {
					if (nearest_emerged_d == -1)
						nearest_emerged_d = d;
				} else {
					if (nearest_emergefull_d == -1)
						nearest_emergefull_d = d;
					goto queue_full_break;
				}

				// get next one.
				continue;
			}

			if (nearest_sent_d == -1)
				nearest_sent_d = d;

			/*
				Add block to send queue
			*/
			PrioritySortedBlockTransfer q((float)dist, p, peer_id);

			dest.push_back(q);

			num_blocks_selected += 1;
		}
	}
queue_full_break:

	// If nothing was found for sending and nothing was queued for
	// emerging, continue next time browsing from here
	if (nearest_emerged_d != -1) {
		new_nearest_unsent_d = nearest_emerged_d;
	} else if (nearest_emergefull_d != -1) {
		new_nearest_unsent_d = nearest_emergefull_d;
	} else {
		if (d > full_d_max) {
			new_nearest_unsent_d = 0;
			m_nothing_to_send_pause_timer = 2.0f;
		} else {
			if (nearest_sent_d != -1)
				new_nearest_unsent_d = nearest_sent_d;
			else
				new_nearest_unsent_d = d;
		}
	}

	if (new_nearest_unsent_d != -1)
		m_nearest_unsent_d = new_nearest_unsent_d;
}

void RemoteClient::GotBlock(v3s16 p)
{
	if (m_blocks_modified.find(p) == m_blocks_modified.end()) {
		if (m_blocks_sending.find(p) != m_blocks_sending.end())
			m_blocks_sending.erase(p);
		else
			m_excess_gotblocks++;

		m_blocks_sent.insert(p);
	}
}

void RemoteClient::SentBlock(v3s16 p)
{
	if (m_blocks_modified.find(p) != m_blocks_modified.end())
		m_blocks_modified.erase(p);

	if (m_blocks_sending.find(p) == m_blocks_sending.end())
		m_blocks_sending[p] = 0.0f;
	else
		infostream<<"RemoteClient::SentBlock(): Sent block"
				" already in m_blocks_sending"<<std::endl;
}

void RemoteClient::SetBlockNotSent(v3s16 p)
{
	m_nearest_unsent_d = 0;
	m_nothing_to_send_pause_timer = 0;

	if (m_blocks_sending.find(p) != m_blocks_sending.end())
		m_blocks_sending.erase(p);
	if (m_blocks_sent.find(p) != m_blocks_sent.end())
		m_blocks_sent.erase(p);
	m_blocks_modified.insert(p);
}

void RemoteClient::SetBlocksNotSent(std::map<v3s16, MapBlock*> &blocks)
{
	m_nearest_unsent_d = 0;
	m_nothing_to_send_pause_timer = 0;

	for (auto &block : blocks) {
		v3s16 p = block.first;
		m_blocks_modified.insert(p);

		if (m_blocks_sending.find(p) != m_blocks_sending.end())
			m_blocks_sending.erase(p);
		if (m_blocks_sent.find(p) != m_blocks_sent.end())
			m_blocks_sent.erase(p);
	}
}

void RemoteClient::notifyEvent(ClientStateEvent event)
{
	std::ostringstream myerror;
	switch (m_state)
	{
	case CS_Invalid:
		//intentionally do nothing
		break;
	case CS_Created:
		switch (event) {
		case CSE_Hello:
			m_state = CS_HelloSent;
			break;
		case CSE_InitLegacy:
			m_state = CS_AwaitingInit2;
			break;
		case CSE_Disconnect:
			m_state = CS_Disconnecting;
			break;
		case CSE_SetDenied:
			m_state = CS_Denied;
			break;
		/* GotInit2 SetDefinitionsSent SetMediaSent */
		default:
			myerror << "Created: Invalid client state transition! " << event;
			throw ClientStateError(myerror.str());
		}
		break;
	case CS_Denied:
		/* don't do anything if in denied state */
		break;
	case CS_HelloSent:
		switch(event)
		{
		case CSE_AuthAccept:
			m_state = CS_AwaitingInit2;
			if (chosen_mech == AUTH_MECHANISM_SRP ||
					chosen_mech == AUTH_MECHANISM_LEGACY_PASSWORD)
				srp_verifier_delete((SRPVerifier *) auth_data);
			chosen_mech = AUTH_MECHANISM_NONE;
			break;
		case CSE_Disconnect:
			m_state = CS_Disconnecting;
			break;
		case CSE_SetDenied:
			m_state = CS_Denied;
			if (chosen_mech == AUTH_MECHANISM_SRP ||
					chosen_mech == AUTH_MECHANISM_LEGACY_PASSWORD)
				srp_verifier_delete((SRPVerifier *) auth_data);
			chosen_mech = AUTH_MECHANISM_NONE;
			break;
		default:
			myerror << "HelloSent: Invalid client state transition! " << event;
			throw ClientStateError(myerror.str());
		}
		break;
	case CS_AwaitingInit2:
		switch(event)
		{
		case CSE_GotInit2:
			confirmSerializationVersion();
			m_state = CS_InitDone;
			break;
		case CSE_Disconnect:
			m_state = CS_Disconnecting;
			break;
		case CSE_SetDenied:
			m_state = CS_Denied;
			break;

		/* Init SetDefinitionsSent SetMediaSent */
		default:
			myerror << "InitSent: Invalid client state transition! " << event;
			throw ClientStateError(myerror.str());
		}
		break;

	case CS_InitDone:
		switch(event)
		{
		case CSE_SetDefinitionsSent:
			m_state = CS_DefinitionsSent;
			break;
		case CSE_Disconnect:
			m_state = CS_Disconnecting;
			break;
		case CSE_SetDenied:
			m_state = CS_Denied;
			break;

		/* Init GotInit2 SetMediaSent */
		default:
			myerror << "InitDone: Invalid client state transition! " << event;
			throw ClientStateError(myerror.str());
		}
		break;
	case CS_DefinitionsSent:
		switch(event)
		{
		case CSE_SetClientReady:
			m_state = CS_Active;
			break;
		case CSE_Disconnect:
			m_state = CS_Disconnecting;
			break;
		case CSE_SetDenied:
			m_state = CS_Denied;
			break;
		/* Init GotInit2 SetDefinitionsSent */
		default:
			myerror << "DefinitionsSent: Invalid client state transition! " << event;
			throw ClientStateError(myerror.str());
		}
		break;
	case CS_Active:
		switch(event)
		{
		case CSE_SetDenied:
			m_state = CS_Denied;
			break;
		case CSE_Disconnect:
			m_state = CS_Disconnecting;
			break;
		case CSE_SudoSuccess:
			m_state = CS_SudoMode;
			if (chosen_mech == AUTH_MECHANISM_SRP)
				srp_verifier_delete((SRPVerifier *) auth_data);
			chosen_mech = AUTH_MECHANISM_NONE;
			break;
		/* Init GotInit2 SetDefinitionsSent SetMediaSent SetDenied */
		default:
			myerror << "Active: Invalid client state transition! " << event;
			throw ClientStateError(myerror.str());
			break;
		}
		break;
	case CS_SudoMode:
		switch(event)
		{
		case CSE_SetDenied:
			m_state = CS_Denied;
			break;
		case CSE_Disconnect:
			m_state = CS_Disconnecting;
			break;
		case CSE_SudoLeave:
			m_state = CS_Active;
			break;
		default:
			myerror << "Active: Invalid client state transition! " << event;
			throw ClientStateError(myerror.str());
			break;
		}
		break;
	case CS_Disconnecting:
		/* we are already disconnecting */
		break;
	}
}

u64 RemoteClient::uptime() const
{
	return porting::getTimeS() - m_connection_time;
}

ClientInterface::ClientInterface(const std::shared_ptr<con::Connection> & con)
:
	m_con(con),
	m_env(NULL),
	m_print_info_timer(0.0f)
{

}
ClientInterface::~ClientInterface()
{
	/*
		Delete clients
	*/
	{
		RecursiveMutexAutoLock clientslock(m_clients_mutex);

		for (auto &client_it : m_clients) {
			// Delete client
			delete client_it.second;
		}
	}
}

std::vector<session_t> ClientInterface::getClientIDs(ClientState min_state)
{
	std::vector<session_t> reply;
	RecursiveMutexAutoLock clientslock(m_clients_mutex);

	for (const auto &m_client : m_clients) {
		if (m_client.second->getState() >= min_state)
			reply.push_back(m_client.second->peer_id);
	}

	return reply;
}

void ClientInterface::markBlockposAsNotSent(const v3s16 &pos)
{
	RecursiveMutexAutoLock clientslock(m_clients_mutex);
	for (const auto &client : m_clients) {
		if (client.second->getState() >= CS_Active)
			client.second->SetBlockNotSent(pos);
	}
}

/**
 * Verify if user limit was reached.
 * User limit count all clients from HelloSent state (MT protocol user) to Active state
 * @return true if user limit was reached
 */
bool ClientInterface::isUserLimitReached()
{
	return getClientIDs(CS_HelloSent).size() >= g_settings->getU16("max_users");
}

void ClientInterface::step(float dtime)
{
	m_print_info_timer += dtime;
	if (m_print_info_timer >= 30.0f) {
		m_print_info_timer = 0.0f;
		UpdatePlayerList();
	}
}

void ClientInterface::UpdatePlayerList()
{
	if (m_env) {
		std::vector<session_t> clients = getClientIDs();
		m_clients_names.clear();


		if (!clients.empty())
			infostream<<"Players:"<<std::endl;

		for (session_t i : clients) {
			RemotePlayer *player = m_env->getPlayer(i);

			if (player == NULL)
				continue;

			infostream << "* " << player->getName() << "\t";

			{
				RecursiveMutexAutoLock clientslock(m_clients_mutex);
				RemoteClient* client = lockedGetClientNoEx(i);
				if (client)
					client->PrintInfo(infostream);
			}

			m_clients_names.emplace_back(player->getName());
		}
	}
}

void ClientInterface::send(session_t peer_id, u8 channelnum,
		NetworkPacket *pkt, bool reliable)
{
	m_con->Send(peer_id, channelnum, pkt, reliable);
}

void ClientInterface::sendToAll(NetworkPacket *pkt)
{
	RecursiveMutexAutoLock clientslock(m_clients_mutex);
	for (auto &client_it : m_clients) {
		RemoteClient *client = client_it.second;

		if (client->net_proto_version != 0) {
			m_con->Send(client->peer_id,
					clientCommandFactoryTable[pkt->getCommand()].channel, pkt,
					clientCommandFactoryTable[pkt->getCommand()].reliable);
		}
	}
}

void ClientInterface::sendToAllCompat(NetworkPacket *pkt, NetworkPacket *legacypkt,
		u16 min_proto_ver)
{
	RecursiveMutexAutoLock clientslock(m_clients_mutex);
	for (auto &client_it : m_clients) {
		RemoteClient *client = client_it.second;
		NetworkPacket *pkt_to_send = nullptr;

		if (client->net_proto_version >= min_proto_ver) {
			pkt_to_send = pkt;
		} else if (client->net_proto_version != 0) {
			pkt_to_send = legacypkt;
		} else {
			warningstream << "Client with unhandled version to handle: '"
				<< client->net_proto_version << "'";
			continue;
		}

		m_con->Send(client->peer_id,
			clientCommandFactoryTable[pkt_to_send->getCommand()].channel,
			pkt_to_send,
			clientCommandFactoryTable[pkt_to_send->getCommand()].reliable);
	}
}

RemoteClient* ClientInterface::getClientNoEx(session_t peer_id, ClientState state_min)
{
	RecursiveMutexAutoLock clientslock(m_clients_mutex);
	RemoteClientMap::const_iterator n = m_clients.find(peer_id);
	// The client may not exist; clients are immediately removed if their
	// access is denied, and this event occurs later then.
	if (n == m_clients.end())
		return NULL;

	if (n->second->getState() >= state_min)
		return n->second;

	return NULL;
}

RemoteClient* ClientInterface::lockedGetClientNoEx(session_t peer_id, ClientState state_min)
{
	RemoteClientMap::const_iterator n = m_clients.find(peer_id);
	// The client may not exist; clients are immediately removed if their
	// access is denied, and this event occurs later then.
	if (n == m_clients.end())
		return NULL;

	if (n->second->getState() >= state_min)
		return n->second;

	return NULL;
}

ClientState ClientInterface::getClientState(session_t peer_id)
{
	RecursiveMutexAutoLock clientslock(m_clients_mutex);
	RemoteClientMap::const_iterator n = m_clients.find(peer_id);
	// The client may not exist; clients are immediately removed if their
	// access is denied, and this event occurs later then.
	if (n == m_clients.end())
		return CS_Invalid;

	return n->second->getState();
}

void ClientInterface::setPlayerName(session_t peer_id, const std::string &name)
{
	RecursiveMutexAutoLock clientslock(m_clients_mutex);
	RemoteClientMap::iterator n = m_clients.find(peer_id);
	// The client may not exist; clients are immediately removed if their
	// access is denied, and this event occurs later then.
	if (n != m_clients.end())
		n->second->setName(name);
}