aboutsummaryrefslogtreecommitdiff
path: root/mp/src/game/server/vote_controller.cpp
blob: 7dab54bbafba9ae8bbcafb0920d0209e3a38f550 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
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
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose: Base VoteController.  Handles holding and voting on issues.
//
// $NoKeywords: $
//=============================================================================//
#include "cbase.h"
#include "vote_controller.h"
#include "shareddefs.h"
#include "eiface.h"
#include "team.h"
#include "gameinterface.h"
#include "fmtstr.h"

#ifdef TF_DLL
#include "tf/tf_gamerules.h"
#endif

// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"

#define MAX_VOTER_HISTORY 64

// Datatable
IMPLEMENT_SERVERCLASS_ST( CVoteController, DT_VoteController )
	SendPropInt( SENDINFO( m_iActiveIssueIndex ) ),
	SendPropInt( SENDINFO( m_iOnlyTeamToVote ) ),
	SendPropArray3( SENDINFO_ARRAY3( m_nVoteOptionCount ), SendPropInt( SENDINFO_ARRAY( m_nVoteOptionCount ), 8, SPROP_UNSIGNED ) ),
	SendPropInt( SENDINFO( m_nPotentialVotes ) ),
	SendPropBool( SENDINFO( m_bIsYesNoVote ) )
END_SEND_TABLE()

BEGIN_DATADESC( CVoteController )
	DEFINE_THINKFUNC( VoteControllerThink ),
END_DATADESC()

LINK_ENTITY_TO_CLASS( vote_controller, CVoteController );

CVoteController *g_voteController = NULL;

ConVar sv_vote_timer_duration("sv_vote_timer_duration", "15", FCVAR_DEVELOPMENTONLY, "How long to allow voting on an issue");
ConVar sv_vote_command_delay("sv_vote_command_delay", "2", FCVAR_DEVELOPMENTONLY, "How long after a vote passes until the action happens", false, 0, true, 4.5);
ConVar sv_allow_votes("sv_allow_votes", "1", FCVAR_NONE, "Allow voting?");
ConVar sv_vote_failure_timer( "sv_vote_failure_timer", "300", FCVAR_NONE, "A vote that fails cannot be re-submitted for this long" );
#ifdef TF_DLL
ConVar sv_vote_failure_timer_mvm( "sv_vote_failure_timer_mvm", "120", FCVAR_NONE, "A vote that fails in MvM cannot be re-submitted for this long" );
#endif // TF_DLL
ConVar sv_vote_creation_timer("sv_vote_creation_timer", "120", FCVAR_DEVELOPMENTONLY, "How often someone can individually call a vote.");
ConVar sv_vote_quorum_ratio( "sv_vote_quorum_ratio", "0.6", FCVAR_HIDDEN, "The minimum ratio of players needed to vote on an issue to resolve it.", true, 0.1, true, 1.0 );
ConVar sv_vote_allow_spectators( "sv_vote_allow_spectators", "0", FCVAR_NONE, "Allow spectators to vote?" );
ConVar sv_vote_ui_hide_disabled_issues( "sv_vote_ui_hide_disabled_issues", "1", FCVAR_NONE, "Suppress listing of disabled issues in the vote setup screen." );

static const int k_nKickWatchListMaxDuration = 300;

//-----------------------------------------------------------------------------
// Purpose: Game system to detect maps without cameras in them, and move on
//-----------------------------------------------------------------------------
class CVoteControllerSystem : public CAutoGameSystemPerFrame
{
public:
	CVoteControllerSystem( char const *name ) : CAutoGameSystemPerFrame( name )
	{
		SetDefLessFunc( m_mapKickWatchList );
		m_flNextKickCheckTime = 0.f;
	}

	virtual void LevelInitPreEntity()
	{
	}

	virtual void FrameUpdatePostEntityThink( void )
	{
		// Executing the vote controller command needs to happen in the PostEntityThink as it can restart levels and
		//	blast entities, etc. If you're doing this during a regular think, this can cause entities thinking after
		//	you in Physics_RunThinkFunctions() to get grumpy and crash.
		if ( g_voteController )
		{
			// Vote passed - execute the command
			if ( g_voteController->m_executeCommandTimer.HasStarted() && g_voteController->m_executeCommandTimer.IsElapsed() )
			{
				g_voteController->m_executeCommandTimer.Invalidate();
				g_voteController->m_potentialIssues[g_voteController->m_iActiveIssueIndex]->ExecuteCommand();
			}
			
			// Kick watch
			if ( m_flNextKickCheckTime < gpGlobals->curtime )
			{
				FOR_EACH_MAP( m_mapKickWatchList, i )
				{
					if ( gpGlobals->curtime > m_mapKickWatchList[i] )
					{
						m_mapKickWatchList.RemoveAt( i );
						break;	// Constantly called code - resume on next pass
					}

					CBasePlayer *pTarget = NULL;
					CSteamID steamIDPlayer;
					for ( int j = 1; j <= gpGlobals->maxClients; j++ )
					{
						CBasePlayer *pPlayer = UTIL_PlayerByIndex( j );
						if ( !pPlayer )
							continue;

						if ( pPlayer->GetSteamID( &steamIDPlayer ) == false )
							continue;

						if ( steamIDPlayer == m_mapKickWatchList.Key( i ) )
						{
							pTarget = pPlayer;
							break;
						}
					}

					if ( pTarget )
					{
						// Welcome back
						engine->ServerCommand( CFmtStr( "kickid %d %s;", pTarget->GetUserID(), "Kicked by server." ) );
					}
				}

				m_flNextKickCheckTime = gpGlobals->curtime + 0.2f;
			}
		}
	}

	void AddPlayerToKickWatchList( CSteamID steamID, float flDuration )
	{
		flDuration = clamp( flDuration, 1.f, (float)k_nKickWatchListMaxDuration );
		if ( m_mapKickWatchList.Find( steamID ) == m_mapKickWatchList.InvalidIndex() )
		{
			m_mapKickWatchList.Insert( steamID, ( gpGlobals->curtime + flDuration ) );
		}
	}

private:

	CUtlMap< CSteamID, float > m_mapKickWatchList;
	float m_flNextKickCheckTime;
};

CVoteControllerSystem VoteControllerSystem( "CVoteControllerSystem" );

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CommandListIssues( void )
{
	CBasePlayer *commandIssuer = UTIL_GetCommandClient();

	if ( g_voteController && commandIssuer )
	{
		g_voteController->ListIssues(commandIssuer);
	}
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
ConCommand ListIssues("listissues", CommandListIssues, "List all the issues that can be voted on.", 0);

//-----------------------------------------------------------------------------
// Purpose: This should eventually ask the player what team they are voting on
// to take into account different idle / spectator rules.
//-----------------------------------------------------------------------------

int GetVoterTeam( CBaseEntity *pEntity )
{
	if ( !pEntity )
		return TEAM_UNASSIGNED;

	int iTeam = pEntity->GetTeamNumber();

	return iTeam;
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CON_COMMAND( callvote, "Start a vote on an issue." )
{
	if ( !g_voteController )
	{
		DevMsg( "Vote Controller Not Found!\n" );
			return;
	}

	CBasePlayer *pVoteCaller = UTIL_GetCommandClient();
	if( !pVoteCaller )
		return;

	if ( !sv_vote_allow_spectators.GetBool() )
	{
		if ( pVoteCaller->GetTeamNumber() == TEAM_SPECTATOR )
		{
			g_voteController->SendVoteCreationFailedMessage( VOTE_FAILED_SPECTATOR, pVoteCaller );
			return;
		}
	}

	// Prevent spamming commands
#ifndef _DEBUG
	int nCooldown = 0;
	if ( !g_voteController->CanEntityCallVote( pVoteCaller, nCooldown ) )
	{
		g_voteController->SendVoteCreationFailedMessage( VOTE_FAILED_RATE_EXCEEDED, pVoteCaller, nCooldown );
		return;
	}
#endif

	// Parameters
	char szEmptyDetails[MAX_VOTE_DETAILS_LENGTH];
	szEmptyDetails[0] = '\0';
	const char *arg2 = args[1];
	const char *arg3 = args.ArgC() >= 3 ? args[2] : szEmptyDetails;

	// If we don't have any arguments, invoke VoteSetup UI
	if( args.ArgC() < 2 )
	{
		g_voteController->SetupVote( pVoteCaller->entindex() );
		return;
	}

	g_voteController->CreateVote( pVoteCaller->entindex(), arg2, arg3 );
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CVoteController::~CVoteController()
{
	g_voteController = NULL;

	for( int issueIndex = 0; issueIndex < m_potentialIssues.Count(); ++issueIndex )
	{
		delete m_potentialIssues[issueIndex];
	}
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CVoteController::ResetData( void )
{
	m_iActiveIssueIndex = INVALID_ISSUE;

	for ( int index = 0; index < m_nVoteOptionCount.Count(); index++ )
	{
		m_nVoteOptionCount.Set( index, 0 );
	}

	m_nPotentialVotes = 0;
	m_acceptingVotesTimer.Invalidate();
	m_executeCommandTimer.Invalidate();
	m_iEntityHoldingVote = -1;
	m_iOnlyTeamToVote = TEAM_INVALID;
	m_bIsYesNoVote = true;

	for( int voteIndex = 0; voteIndex < ARRAYSIZE( m_nVotesCast ); ++voteIndex )
	{
		m_nVotesCast[voteIndex] = VOTE_UNCAST;
	}
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CVoteController::Spawn( void )
{
	ResetData();

	BaseClass::Spawn();

	SetThink( &CVoteController::VoteControllerThink );
	SetNextThink( gpGlobals->curtime );

	SetDefLessFunc( m_VoteCallers );

	g_voteController = this;
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
int CVoteController::UpdateTransmitState( void )
{
	// ALWAYS transmit to all clients.
	return SetTransmitState( FL_EDICT_ALWAYS );
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool CVoteController::CanTeamCastVote( int iTeam ) const
{
	if ( m_iOnlyTeamToVote == TEAM_INVALID )
		return true;

	return iTeam == m_iOnlyTeamToVote;
}

//-----------------------------------------------------------------------------
// Purpose: Handles menu-driven setup of Voting
//-----------------------------------------------------------------------------
bool CVoteController::SetupVote( int iEntIndex )
{
	CBasePlayer *pVoteCaller = UTIL_PlayerByIndex( iEntIndex );
	if( !pVoteCaller )
		return false;

	int nIssueCount = 0;

	// Passing an nIssueCount of 0 triggers a "Voting disabled on server" message in the setup UI
	if ( sv_allow_votes.GetBool() )
	{
		for( int iIndex = 0; iIndex < m_potentialIssues.Count(); ++iIndex )
		{
			// Hide disabled issues?
			CBaseIssue *pCurrentIssue = m_potentialIssues[iIndex];
			if ( pCurrentIssue )
			{
				if ( !pCurrentIssue->IsEnabled() && sv_vote_ui_hide_disabled_issues.GetBool() )
					continue;

				nIssueCount++;
			}
		}
	}

	CSingleUserRecipientFilter filter( pVoteCaller );
	filter.MakeReliable();
	UserMessageBegin( filter, "VoteSetup" );
	WRITE_BYTE( nIssueCount );

	for( int iIndex = 0; iIndex < m_potentialIssues.Count(); ++iIndex )
	{
		CBaseIssue *pCurrentIssue = m_potentialIssues[iIndex];
		if ( pCurrentIssue )
		{
			if ( pCurrentIssue->IsEnabled() )
			{
				WRITE_STRING( pCurrentIssue->GetTypeString() );
			}
			else
			{
				// Don't send/display disabled issues when set
				if ( sv_vote_ui_hide_disabled_issues.GetBool() )
					continue;

				char szDisabledIssueStr[MAX_COMMAND_LENGTH + 12];
				V_strcpy( szDisabledIssueStr, pCurrentIssue->GetTypeString() );
				V_strcat( szDisabledIssueStr, " (Disabled on Server)", sizeof(szDisabledIssueStr) );

				WRITE_STRING( szDisabledIssueStr );
			}
		}
	}

	MessageEnd();

	return true;
}

//-----------------------------------------------------------------------------
// Purpose: Handles console-driven setup of Voting
//-----------------------------------------------------------------------------
bool CVoteController::CreateVote( int iEntIndex, const char *pszTypeString, const char *pszDetailString )
{
	// Terrible Hack:  Dedicated servers pass 99 as the EntIndex
	bool bDedicatedServer = ( iEntIndex == DEDICATED_SERVER ) ? true : false;

	if( !sv_allow_votes.GetBool() )
		return false;

	// Already running a vote?
	if( IsVoteActive() )
		return false;

	CBasePlayer *pVoteCaller = UTIL_PlayerByIndex( iEntIndex );
	if( !pVoteCaller && !bDedicatedServer )
		return false;

	// Find the issue the user is asking for
	for( int issueIndex = 0; issueIndex < m_potentialIssues.Count(); ++issueIndex )
	{
		CBaseIssue *pCurrentIssue = m_potentialIssues[issueIndex];
		if ( !pCurrentIssue )
			return false;
		
		if( FStrEq( pszTypeString, pCurrentIssue->GetTypeString() ) )
		{
			vote_create_failed_t nErrorCode = VOTE_FAILED_GENERIC;
			int nTime = 0;
			if( pCurrentIssue->CanCallVote( iEntIndex, pszDetailString, nErrorCode, nTime ) )
			{
				// Establish a bunch of data on this particular issue
				pCurrentIssue->SetIssueDetails( pszDetailString );
				m_bIsYesNoVote = pCurrentIssue->IsYesNoVote();
				m_iActiveIssueIndex = issueIndex;
				m_iEntityHoldingVote = iEntIndex;
				if ( !bDedicatedServer )
				{
					if( pCurrentIssue->IsAllyRestrictedVote() )
					{
						m_iOnlyTeamToVote = GetVoterTeam( pVoteCaller );
					}
					else
					{
						m_iOnlyTeamToVote = TEAM_INVALID;
					}
				}
				
				// Now get our choices
				m_VoteOptions.RemoveAll();
				pCurrentIssue->GetVoteOptions( m_VoteOptions );
				int nNumVoteOptions = m_VoteOptions.Count();
				if ( nNumVoteOptions >= 2 )
				{
					IGameEvent *event = gameeventmanager->CreateEvent( "vote_options" );
					if ( event )
					{
						event->SetInt( "count", nNumVoteOptions );
						for ( int iIndex = 0; iIndex < nNumVoteOptions; iIndex++ )
						{
							char szNumber[2];
							Q_snprintf( szNumber, sizeof( szNumber ), "%i", iIndex + 1 );

							char szOptionName[8] = "option";
							Q_strncat( szOptionName, szNumber, sizeof( szOptionName ), COPY_ALL_CHARACTERS );

							event->SetString( szOptionName, m_VoteOptions[iIndex] );
						}
						gameeventmanager->FireEvent( event );
					}
				}
				else
				{
					Assert( nNumVoteOptions >= 2 );
				}

				// Have the issue start working on it
				pCurrentIssue->OnVoteStarted();

				// Now the vote handling and UI
				m_nPotentialVotes = pCurrentIssue->CountPotentialVoters();
				m_acceptingVotesTimer.Start( sv_vote_timer_duration.GetFloat() );

				// Force the vote holder to agree with a Yes/No vote
				if ( m_bIsYesNoVote && !bDedicatedServer )
				{
					TryCastVote( iEntIndex, "Option1" );
				}

				// Get the data out to the client
				CBroadcastRecipientFilter filter;
				filter.MakeReliable();
				UserMessageBegin( filter, "VoteStart" );
					WRITE_BYTE( m_iOnlyTeamToVote );			// move into the filter
					WRITE_BYTE( m_iEntityHoldingVote );
					WRITE_STRING( pCurrentIssue->GetDisplayString() );
					WRITE_STRING( pCurrentIssue->GetDetailsString() );
					WRITE_BOOL( m_bIsYesNoVote );
				MessageEnd();

				if ( !bDedicatedServer )
				{
					TrackVoteCaller( pVoteCaller );
				}

				return true;
			}
			else
			{
				if ( !bDedicatedServer )
				{
					SendVoteCreationFailedMessage( nErrorCode, pVoteCaller, nTime );
				}
			}
		}
	}

	return false;
}

//-----------------------------------------------------------------------------
// Purpose: The vote failed to start - let the caller know why
//-----------------------------------------------------------------------------
void CVoteController::SendVoteCreationFailedMessage( vote_create_failed_t nReason, CBasePlayer *pVoteCaller, int nTime /*= -1*/ )
{
	Assert( pVoteCaller );
	if ( !pVoteCaller )
		return;

	CSingleUserRecipientFilter user( pVoteCaller );
	user.MakeReliable();

	UserMessageBegin( user, "CallVoteFailed" );
	WRITE_BYTE( nReason );
	WRITE_SHORT( nTime );
	MessageEnd();
}

//-----------------------------------------------------------------------------
// Purpose: The vote was called, but failed to pass - let everyone know why
//-----------------------------------------------------------------------------
void CVoteController::SendVoteFailedToPassMessage( vote_create_failed_t nReason )
{
	Assert( m_potentialIssues[m_iActiveIssueIndex] );

	// See if we have a player target.
	CBasePlayer *pVoteTarget = m_potentialIssues[m_iActiveIssueIndex]->m_hPlayerTarget;
	bool bFakeClient = ( pVoteTarget && ( pVoteTarget->IsFakeClient() || pVoteTarget->IsHLTV() || pVoteTarget->IsReplay() ) );

	UTIL_LogPrintf( "Vote failed \"%s %s\" with code %i (proxy: %i) \n", m_potentialIssues[m_iActiveIssueIndex]->GetTypeString(), m_potentialIssues[m_iActiveIssueIndex]->GetDetailsString(), (int)nReason, bFakeClient );

	CBroadcastRecipientFilter filter;
	filter.MakeReliable();

	UserMessageBegin( filter, "VoteFailed" );
	WRITE_BYTE( m_iOnlyTeamToVote );
	WRITE_BYTE( nReason );
	MessageEnd();
}

//-----------------------------------------------------------------------------
// Purpose:  Player generated a vote command.  i.e. /vote option1
//-----------------------------------------------------------------------------
CVoteController::TryCastVoteResult CVoteController::TryCastVote( int iEntIndex, const char *pszVoteString )
{
	if( !sv_allow_votes.GetBool() )
		return CAST_FAIL_SERVER_DISABLE;

	if( iEntIndex >= ARRAYSIZE( m_nVotesCast ) )
		return CAST_FAIL_SYSTEM_ERROR;

	if( !IsVoteActive() )
		return CAST_FAIL_NO_ACTIVE_ISSUE;

	if( m_executeCommandTimer.HasStarted() )
		return CAST_FAIL_VOTE_CLOSED;

	if( m_potentialIssues[m_iActiveIssueIndex] && m_potentialIssues[m_iActiveIssueIndex]->IsAllyRestrictedVote() )
	{
		CBaseEntity *pVoteHolder = UTIL_EntityByIndex( m_iEntityHoldingVote );
		CBaseEntity *pVoter = UTIL_EntityByIndex( iEntIndex );

		if( ( pVoteHolder == NULL ) || ( pVoter == NULL ) || ( GetVoterTeam( pVoteHolder ) != GetVoterTeam( pVoter ) ) )
		{
			return CAST_FAIL_TEAM_RESTRICTED;
		}
	}

	// Look for a previous vote
	int nOldVote = m_nVotesCast[iEntIndex];
#ifndef DEBUG
	if( nOldVote != VOTE_UNCAST )
	{
		return CAST_FAIL_NO_CHANGES;
	}
#endif // !DEBUG

	// Which option are they voting for?
	int nCurrentVote = VOTE_UNCAST;
	if ( Q_strnicmp( pszVoteString, "Option", 6 ) != 0 )
		return CAST_FAIL_SYSTEM_ERROR;

	nCurrentVote = (CastVote)( atoi( pszVoteString + 6 ) - 1 );

	if ( nCurrentVote < VOTE_OPTION1 || nCurrentVote > VOTE_OPTION5 )
		return CAST_FAIL_SYSTEM_ERROR;
	
	// They're changing their vote
#ifdef DEBUG
	if ( nOldVote != VOTE_UNCAST )
	{
		if( nOldVote == nCurrentVote )
		{
			return CAST_FAIL_DUPLICATE;
		}
		VoteChoice_Decrement( nOldVote );
	}
#endif // DEBUG

	// With a Yes/No vote, slam anything past "No" to No
	if ( m_potentialIssues[m_iActiveIssueIndex]->IsYesNoVote() )
	{
		if ( nCurrentVote > VOTE_OPTION2 )
			nCurrentVote = VOTE_OPTION2;
	}

	// Register and track this vote
	VoteChoice_Increment( nCurrentVote );
	m_nVotesCast[iEntIndex] = nCurrentVote;

	// Tell the client-side UI
	IGameEvent *event = gameeventmanager->CreateEvent( "vote_cast" );
	if ( event )
	{
		event->SetInt( "vote_option", nCurrentVote );
		event->SetInt( "team", m_iOnlyTeamToVote );
		event->SetInt( "entityid", iEntIndex );
		gameeventmanager->FireEvent( event );
	}

	CheckForEarlyVoteClose();

	return CAST_OK;
}

//-----------------------------------------------------------------------------
// Purpose:  Increments the vote count for a particular vote option 
//			 i.e. nVoteChoice = 0 might mean a Yes vote
//-----------------------------------------------------------------------------
void CVoteController::VoteChoice_Increment( int nVoteChoice )
{
	if ( nVoteChoice < VOTE_OPTION1 || nVoteChoice > VOTE_OPTION5 )
		return;

	int nValue = m_nVoteOptionCount.Get( nVoteChoice );
	m_nVoteOptionCount.Set( nVoteChoice, ++nValue );
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CVoteController::VoteChoice_Decrement( int nVoteChoice )
{
	if ( nVoteChoice < VOTE_OPTION1 || nVoteChoice > VOTE_OPTION5 )
		return;

	int nValue = m_nVoteOptionCount.Get( nVoteChoice );
	m_nVoteOptionCount.Set( nVoteChoice, --nValue );
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CVoteController::VoteControllerThink( void )
{
	if ( !m_potentialIssues.IsValidIndex( m_iActiveIssueIndex ) )
	{
		SetNextThink( gpGlobals->curtime + 0.5f );

		return;
	}

	// Vote time is up - process the result
	if( m_acceptingVotesTimer.HasStarted() && m_acceptingVotesTimer.IsElapsed() )
	{
		m_acceptingVotesTimer.Invalidate();
		
		int nVoteTally = 0;
		for ( int index = 0; index < MAX_VOTE_OPTIONS; index++ )
		{
			nVoteTally += m_nVoteOptionCount.Get( index );
		}

		bool bVotePassed = true;

		// for record-keeping
		if ( m_potentialIssues[m_iActiveIssueIndex]->IsYesNoVote() )
		{
			m_potentialIssues[m_iActiveIssueIndex]->SetYesNoVoteCount( m_nVoteOptionCount[VOTE_OPTION1],  m_nVoteOptionCount[VOTE_OPTION2], m_nPotentialVotes );
		}

		// Have we exceeded the required ratio of Voted-vs-Abstained?
		if ( nVoteTally >= m_nPotentialVotes * sv_vote_quorum_ratio.GetFloat() )
		{
			int nWinningVoteOption = GetWinningVoteOption();
			Assert( nWinningVoteOption >= 0 && nWinningVoteOption < m_VoteOptions.Count() );

			if ( nWinningVoteOption >= 0 && nWinningVoteOption < MAX_VOTE_OPTIONS )
			{
				// YES/NO VOTES
				if ( m_potentialIssues[m_iActiveIssueIndex]->IsYesNoVote() )
				{
					// Option1 is Yes
					if ( nWinningVoteOption != VOTE_OPTION1 )
					{
						SendVoteFailedToPassMessage( VOTE_FAILED_YES_MUST_EXCEED_NO );
						bVotePassed = false;
					}					
				}
				// GENERAL VOTES:
				// We set the details string after the vote, since that's when
				// we finally have a parameter to pass along and execute
				else if ( nWinningVoteOption < m_VoteOptions.Count() )
				{
					m_potentialIssues[m_iActiveIssueIndex]->SetIssueDetails( m_VoteOptions[nWinningVoteOption] );
				}
			}
		}
		else
		{
			SendVoteFailedToPassMessage( VOTE_FAILED_QUORUM_FAILURE );
			bVotePassed = false;
		}

 		if ( bVotePassed )
		{
			m_executeCommandTimer.Start( sv_vote_command_delay.GetFloat() );
			m_resetVoteTimer.Start( 5.0 );

			// Target is not always a player (changelevel, etc)
			CBasePlayer *pVoteTarget = m_potentialIssues[m_iActiveIssueIndex]->m_hPlayerTarget;
			bool bFakeClient = ( pVoteTarget && ( pVoteTarget->IsFakeClient() || pVoteTarget->IsHLTV() || pVoteTarget->IsReplay() ) );

			UTIL_LogPrintf( "Vote succeeded \"%s %s\" (proxy: %i) \n", m_potentialIssues[m_iActiveIssueIndex]->GetTypeString(), m_potentialIssues[m_iActiveIssueIndex]->GetDetailsString(), bFakeClient );

			CBroadcastRecipientFilter filter;
			filter.MakeReliable();

			UserMessageBegin( filter, "VotePass" );
				WRITE_BYTE( m_iOnlyTeamToVote );
				WRITE_STRING( m_potentialIssues[m_iActiveIssueIndex]->GetVotePassedString() );
				WRITE_STRING( m_potentialIssues[m_iActiveIssueIndex]->GetDetailsString() );
			MessageEnd();
		}
		else
		{
			m_potentialIssues[m_iActiveIssueIndex]->OnVoteFailed( m_iEntityHoldingVote );
			m_resetVoteTimer.Start( 5.0 );
		}
	}

	// Vote passed check moved down to FrameUpdatePostEntityThink at bottom of this file...

	if ( m_resetVoteTimer.HasStarted() && m_resetVoteTimer.IsElapsed() )
	{
		ResetData();
		m_resetVoteTimer.Invalidate();
	}

	// Size maintenance on m_VoteCallers
	if ( m_VoteCallers.Count() >= MAX_VOTER_HISTORY )
	{
		// Remove older entries
		for ( int iIdx = m_VoteCallers.FirstInorder(); iIdx != m_VoteCallers.InvalidIndex(); iIdx = m_VoteCallers.NextInorder( iIdx ) )
		{
			if ( m_VoteCallers[ iIdx ] - gpGlobals->curtime <= 0 )
			{
				m_VoteCallers.Remove( iIdx );
			}
		}
	}

	SetNextThink( gpGlobals->curtime + 0.5f );
}

//-----------------------------------------------------------------------------
// Purpose: End the vote early if everyone's voted
//-----------------------------------------------------------------------------
void CVoteController::CheckForEarlyVoteClose( void )
{
	int nVoteTally = 0;
	for ( int index = 0; index < MAX_VOTE_OPTIONS; index++ )
	{
		nVoteTally += m_nVoteOptionCount.Get( index );
	}

	if( nVoteTally >= m_nPotentialVotes )
	{
		m_acceptingVotesTimer.Start( 0 );	// Run the timer out right now
	}
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool CVoteController::IsValidVoter( CBasePlayer *pWhom )
{
	if ( pWhom == NULL )
		return false;

	if ( !pWhom->IsConnected() )
		return false;

	if ( !sv_vote_allow_spectators.GetBool() )
	{
		if ( pWhom->GetTeamNumber() == TEAM_SPECTATOR )
			return false;
	}

#ifndef DEBUG  // Don't want to do this check for debug builds (so we can test with bots)
	if ( pWhom->IsBot() )
		return false;

	if ( pWhom->IsFakeClient() )
		return false;
#endif // DEBUG

	if ( pWhom->IsHLTV() )
		return false;

	if ( pWhom->IsReplay() )
		return false;

#ifdef TF_DLL
	if ( TFGameRules() && TFGameRules()->IsMannVsMachineMode() )
	{
		if ( pWhom->GetTeamNumber() != TF_TEAM_PVE_DEFENDERS )
			return false;
	}
#endif // TF_DLL

	return true;
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CVoteController::RegisterIssue( CBaseIssue *pszNewIssue )
{
	m_potentialIssues.AddToTail( pszNewIssue );
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CVoteController::ListIssues( CBasePlayer *pForWhom )
{
	if( !sv_allow_votes.GetBool() )
		return;

	ClientPrint( pForWhom, HUD_PRINTCONSOLE, "---Vote commands---\n" );

	for( int issueIndex = 0; issueIndex < m_potentialIssues.Count(); ++issueIndex )
	{
		CBaseIssue *pCurrentIssue = m_potentialIssues[issueIndex];
		pCurrentIssue->ListIssueDetails( pForWhom );
	}
	ClientPrint( pForWhom, HUD_PRINTCONSOLE, "--- End Vote commands---\n" );
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
int CVoteController::GetWinningVoteOption( void )
{
	if ( m_potentialIssues[m_iActiveIssueIndex]->IsYesNoVote() )
	{
		return ( m_nVoteOptionCount[VOTE_OPTION1] > m_nVoteOptionCount[VOTE_OPTION2] ) ? VOTE_OPTION1 : VOTE_OPTION2;
	}
	else
	{
		CUtlVector <int> pVoteCounts;

		// Which option had the most votes?
		// driller:  Need to handle ties
		int nHighest = m_nVoteOptionCount[0];
		for ( int iIndex = 0; iIndex < m_nVoteOptionCount.Count(); iIndex ++ )
		{
			nHighest = ( ( nHighest < m_nVoteOptionCount[iIndex] ) ? m_nVoteOptionCount[iIndex] : nHighest );
			pVoteCounts.AddToTail( m_nVoteOptionCount[iIndex] );
		}
		
		m_nHighestCountIndex = -1;
		for ( int iIndex = 0; iIndex < m_nVoteOptionCount.Count(); iIndex++ )
		{
			if ( m_nVoteOptionCount[iIndex] == nHighest )
			{
				m_nHighestCountIndex = iIndex;
				// henryg: break on first match, not last. this avoids a crash
				// if we are all tied at zero and we pick something beyond the
				// last vote option. this code really ought to ignore attempts
				// to tally votes for options beyond the last valid one!
				break;
			}
		}

		return m_nHighestCountIndex;
	}

	return -1;
}

//-----------------------------------------------------------------------------
// Purpose: Store steamIDs for every player that calls a vote
//-----------------------------------------------------------------------------
void CVoteController::TrackVoteCaller( CBasePlayer *pPlayer )
{
	if ( !pPlayer )
		return;

	CSteamID steamID;
	pPlayer->GetSteamID( &steamID );

	int iIdx = m_VoteCallers.Find( steamID.ConvertToUint64() );
	if ( iIdx != m_VoteCallers.InvalidIndex() )
	{
		// Already being tracked - update timer
		m_VoteCallers[ iIdx ] = gpGlobals->curtime + sv_vote_creation_timer.GetInt();
		return;
	}

	m_VoteCallers.Insert( steamID.ConvertToUint64(), gpGlobals->curtime + sv_vote_creation_timer.GetInt() );
};

//-----------------------------------------------------------------------------
// Purpose: Check the history of steamIDs that called votes and test against a timer
//-----------------------------------------------------------------------------
bool CVoteController::CanEntityCallVote( CBasePlayer *pPlayer, int &nCooldown )
{
	if ( !pPlayer )
		return false;
	
	CSteamID steamID;
	pPlayer->GetSteamID( &steamID );

	// Has this SteamID tried to call a vote recently?
	int iIdx = m_VoteCallers.Find( steamID.ConvertToUint64() );
	if ( iIdx != m_VoteCallers.InvalidIndex() )
	{
		// Timer elapsed?
		nCooldown = (int)( m_VoteCallers[ iIdx ] - gpGlobals->curtime );
		if ( nCooldown > 0 )
			return false;

		// Expired
		m_VoteCallers.Remove( iIdx );
	}

	return true;
};

//-----------------------------------------------------------------------------
// Purpose: 
//-----------------------------------------------------------------------------
void CVoteController::AddPlayerToKickWatchList( CSteamID steamID, float flDuration )
{
	VoteControllerSystem.AddPlayerToKickWatchList( steamID, flDuration );
}

//-----------------------------------------------------------------------------
// Purpose: BaseIssue
//-----------------------------------------------------------------------------
CBaseIssue::CBaseIssue( const char *pszTypeString )
{
	Q_strcpy( m_szTypeString, pszTypeString );

	m_iNumYesVotes = 0;
	m_iNumNoVotes = 0;
	m_iNumPotentialVotes = 0;
	m_flNextCallTime = -1.f;

	ASSERT( g_voteController );
	g_voteController->RegisterIssue( this );
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CBaseIssue::~CBaseIssue()
{
	for ( int index = 0; index < m_FailedVotes.Count(); index++ )
	{
		FailedVote *pFailedVote = m_FailedVotes[index];
		delete pFailedVote;
	}
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
const char *CBaseIssue::GetTypeString( void )
{
	return m_szTypeString;
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
const char *CBaseIssue::GetDetailsString( void )
{
	return m_szDetailsString;
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CBaseIssue::SetIssueDetails( const char *pszDetails )
{
	Q_strcpy( m_szDetailsString, pszDetails );
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool CBaseIssue::IsAllyRestrictedVote( void )
{
	return false;
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
const char *CBaseIssue::GetVotePassedString( void )
{
	return "Unknown vote passed.";
}

//-----------------------------------------------------------------------------
// Purpose:  Store failures to prevent vote spam
//-----------------------------------------------------------------------------
void CBaseIssue::OnVoteFailed( int iEntityHoldingVote )
{
	// Don't track failed dedicated server votes
	if ( BRecordVoteFailureEventForEntity( iEntityHoldingVote ) )
	{
		// Check for an existing match
		for ( int index = 0; index < m_FailedVotes.Count(); index++ )
		{
			FailedVote *pFailedVote = m_FailedVotes[index];
			if ( Q_strcmp( pFailedVote->szFailedVoteParameter, GetDetailsString() ) == 0 )
			{
				int nTime = sv_vote_failure_timer.GetInt();

#ifdef TF_DLL
				if ( TFGameRules() && TFGameRules()->IsMannVsMachineMode() )
				{
					nTime = sv_vote_failure_timer_mvm.GetInt();
				}
#endif // TF_DLL

				pFailedVote->flLockoutTime = gpGlobals->curtime + nTime;

				return;
			}
		}

		// Need to create a new one
		FailedVote *pNewFailedVote = new FailedVote;
		int iIndex = m_FailedVotes.AddToTail( pNewFailedVote );
		Q_strcpy( m_FailedVotes[iIndex]->szFailedVoteParameter, GetDetailsString() );
		m_FailedVotes[iIndex]->flLockoutTime = gpGlobals->curtime + sv_vote_failure_timer.GetFloat();
	}
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool CBaseIssue::CanTeamCallVote( int iTeam ) const
{
	return true;
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool CBaseIssue::CanCallVote( int iEntIndex, const char *pszDetails, vote_create_failed_t &nFailCode, int &nTime )
{
	// Automated server vote - don't bother testing against it
	if ( !BRecordVoteFailureEventForEntity( iEntIndex ) )
		return true;

	// Bogus player
	if ( iEntIndex == -1 )
		return false;

	// Note: Issue timers reset on level change because the class is created/destroyed during transitions.
	// It'd be nice to refactor the basic framework of the system to get rid of side-effects like this.
	if ( m_flNextCallTime != -1.f && gpGlobals->curtime < m_flNextCallTime )
	{
		nFailCode = VOTE_FAILED_ON_COOLDOWN;
		nTime = m_flNextCallTime - gpGlobals->curtime;
		return false;
	}

#ifdef TF_DLL
	if ( TFGameRules() && TFGameRules()->IsInWaitingForPlayers() && !TFGameRules()->IsInTournamentMode() )
	{
		nFailCode = VOTE_FAILED_WAITINGFORPLAYERS;
		return false;
	}
#endif // TF_DLL

	CBaseEntity *pVoteCaller = UTIL_EntityByIndex( iEntIndex );
	if ( pVoteCaller && !CanTeamCallVote( GetVoterTeam( pVoteCaller ) ) )
	{
		nFailCode = VOTE_FAILED_TEAM_CANT_CALL;
		return false;
	}

	// Did this fail recently?
	for ( int iIndex = 0; iIndex < m_FailedVotes.Count(); iIndex++ )
	{
		FailedVote *pCurrentFailure = m_FailedVotes[iIndex];
		int nTimeRemaining = pCurrentFailure->flLockoutTime - gpGlobals->curtime;
		bool bFailed = false;

		// If this issue requires a parameter, see if we're voting for the same one again (i.e. changelevel ctf_2fort)
		if ( Q_strlen( pCurrentFailure->szFailedVoteParameter ) > 0 )
		{
			if( nTimeRemaining > 1 && FStrEq( pCurrentFailure->szFailedVoteParameter, pszDetails ) )
			{
				bFailed = true;
			}
		}
		// Otherwise we have a parameter-less vote, so just check the lockout timer (i.e. restartgame)
		else
		{
			if( nTimeRemaining > 1 )
			{
				bFailed = true;

			}
		}

		if ( bFailed )
		{
			nFailCode = VOTE_FAILED_ON_COOLDOWN;
			nTime = nTimeRemaining;
			return false;
		}
	}

	return true;
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
int CBaseIssue::CountPotentialVoters( void )
{
	int nTotalPlayers = 0;

	for( int playerIndex = 1; playerIndex <= MAX_PLAYERS; ++playerIndex )
	{
		CBasePlayer *pPlayer = UTIL_PlayerByIndex( playerIndex );
		if( g_voteController->IsValidVoter( pPlayer ) )
		{
			if ( g_voteController->CanTeamCastVote( GetVoterTeam( pPlayer ) ) )
			{
				nTotalPlayers++;
			}
		}
	}

	return nTotalPlayers;
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
int CBaseIssue::GetNumberVoteOptions( void )
{
	return 2;  // The default issue is Yes/No (so 2), but it can be anywhere between 1 and MAX_VOTE_COUNT
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool CBaseIssue::IsYesNoVote( void )
{
	return true;  // Default
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CBaseIssue::SetYesNoVoteCount( int iNumYesVotes, int iNumNoVotes, int iNumPotentialVotes )
{
	m_iNumYesVotes = iNumYesVotes;
	m_iNumNoVotes = iNumNoVotes;
	m_iNumPotentialVotes = iNumPotentialVotes;
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CBaseIssue::ListStandardNoArgCommand( CBasePlayer *forWhom, const char *issueString )
{
	ClientPrint( forWhom, HUD_PRINTCONSOLE, "callvote %s1\n", issueString );
}

//-----------------------------------------------------------------------------
// Purpose: 
//-----------------------------------------------------------------------------
bool CBaseIssue::GetVoteOptions( CUtlVector <const char*> &vecNames )
{
	// The default vote issue is a Yes/No vote
	vecNames.AddToHead( "Yes" );
	vecNames.AddToTail( "No" );

	return true;
}