VoltMod
C++23 framework for CS2 server plugins
Loading...
Searching...
No Matches
Vote.cpp
Go to the documentation of this file.
2
10#include <cstrike15_usermessages.pb.h>
11#include <engine2/igameeventsystem.h>
12#include <networksystem/inetworkmessages.h>
13#include <string_view>
14#include <utility>
15
16namespace VoltMod
17{
18
19static constexpr std::string_view ControllerClass = "vote_controller";
20
21// A client takes F1/F2 only while an issue is active. The engine must never run this one, so
22// `vote` and `callvote` are blocked during a vote.
23static constexpr int YesNoIssueIndex = 2;
24static constexpr int NoIssue = -1;
25static constexpr int AllTeams = -1;
26
27// The vote_cast event's option numbers.
28static constexpr int YesOption = 0;
29static constexpr int NoOption = 1;
30
31// Names carry the message prefix: a bare "VoteFailed" also matches CCSUsrMsg_CallVoteFailed.
32static constexpr std::string_view VoteStartMessage = "CCSUsrMsg_VoteStart";
33static constexpr std::string_view VotePassMessage = "CCSUsrMsg_VotePass";
34static constexpr std::string_view VoteFailedMessage = "CCSUsrMsg_VoteFailed";
35
36Vote::Vote(Interfaces& interfaces, EntitySystem& entities, PlayerManager& players, GameEvents& events,
37 Scheduler& scheduler)
38 : _interfaces(interfaces), _entities(entities), _players(players), _events(events), _scheduler(scheduler)
39{
40 _leaving = players.Disconnected += [this](Player& player) { DropVoter(player.Slot()); };
41}
42
43CRecipientFilter Vote::Recipients() const
44{
45 CRecipientFilter filter;
46 filter.MakeReliable();
47 for (const Player* player : _players.All())
48 {
49 if (!player->IsBot())
50 {
51 filter.AddRecipient(player->Slot());
52 }
53 }
54 return filter;
55}
56
57Schema::CVoteController Vote::Controller()
58{
59 return Schema::CVoteController{_entities.Find(ControllerClass).Raw()};
60}
61
63{
64 if (_running || !request.Passed)
65 {
66 return false;
67 }
68
69 Ballot ballot{.Request = std::move(request)};
70 for (const Player* player : _players.All())
71 {
72 if (!player->IsBot() && IsValidSlot(player->Slot()))
73 {
74 ballot.Waiting[player->Slot()] = true;
75 ++ballot.Tally.Eligible;
76 }
77 }
78 if (ballot.Tally.Eligible == 0)
79 {
80 return false;
81 }
82
83 if (Schema::CVoteController controller = Controller())
84 {
85 controller.SetPotentialVotes(ballot.Tally.Eligible);
86 controller.SetIsYesNoVote(true);
87 // The VoteStart recipients decide who may vote.
88 controller.SetOnlyTeamToVote(AllTeams);
89 controller.SetActiveIssueIndex(YesNoIssueIndex);
90 }
91
92 Ballot& running = _running.emplace(std::move(ballot));
93 PublishCounts(running.Tally);
94 SendStart(running);
95 running.Timeout = _scheduler.Delay(running.Request.DurationMs, [this] { Finish(VoteEndReason::TimeUp); });
96 return true;
97}
98
99bool Vote::TryCastBallot(int slot, std::string_view option)
100{
101 if (!_running)
102 {
103 return false;
104 }
105
106 Ballot& ballot = *_running;
107 if (!IsValidSlot(slot) || !ballot.Waiting[slot])
108 {
109 return true;
110 }
111
112 if (option == "option1")
113 {
114 ++ballot.Tally.Yes;
115 PublishBallot(slot, YesOption);
116 }
117 else if (option == "option2")
118 {
119 ++ballot.Tally.No;
120 PublishBallot(slot, NoOption);
121 }
122 else
123 {
124 return true;
125 }
126
127 ballot.Waiting[slot] = false;
128 PublishCounts(ballot.Tally);
129 CloseIfAllVoted();
130 return true;
131}
132
133void Vote::DropVoter(int slot)
134{
135 if (!_running || !IsValidSlot(slot) || !_running->Waiting[slot])
136 {
137 return;
138 }
139
140 // A player who leaves without voting would otherwise hold the vote open until it times out.
141 _running->Waiting[slot] = false;
142 --_running->Tally.Eligible;
143 PublishCounts(_running->Tally);
144 CloseIfAllVoted();
145}
146
147void Vote::CloseIfAllVoted()
148{
149 if (_running->Tally.Cast() < _running->Tally.Eligible)
150 {
151 return;
152 }
153
154 // Deferred a tick: the engine may still be inside the command dispatch.
155 _running->Close = _scheduler.NextTick([this] { Finish(VoteEndReason::AllVoted); });
156}
157
159{
160 if (_running)
161 {
162 Finish(reason);
163 }
164}
165
166void Vote::Finish(VoteEndReason reason)
167{
168 // Taken out first: the callbacks may start the next vote. Dropping it cancels both timers.
169 Ballot ballot = std::move(*_running);
170 _running.reset();
171
172 // A cancelled vote never asks the caller whether it passed.
173 const bool passed = reason != VoteEndReason::Cancelled && ballot.Request.Passed(ballot.Tally);
174
175 SendOutcome(ballot.Request, passed);
176
177 if (Schema::CVoteController controller = Controller())
178 {
179 controller.SetActiveIssueIndex(NoIssue);
180 }
181
182 if (ballot.Request.Finished)
183 {
184 ballot.Request.Finished(passed, reason);
185 }
186}
187
188void Vote::PublishBallot(int slot, int option)
189{
190 // The voter's panel registers the key press from this event.
191 IGameEvent* event = _events.CreateEvent(VoteCast::EventName);
192 if (!event)
193 {
194 return;
195 }
196
197 event->SetInt("vote_option", option);
198 event->SetInt("team", AllTeams);
199 event->SetPlayer("userid", CPlayerSlot(slot));
200 _events.FireEvent(event);
201}
202
203void Vote::PublishCounts(const VoteTally& tally)
204{
205 // The panel reads its tally from this event.
206 IGameEvent* event = _events.CreateEvent(VoteChanged::EventName);
207 if (!event)
208 {
209 return;
210 }
211
212 event->SetInt("vote_option1", tally.Yes);
213 event->SetInt("vote_option2", tally.No);
214 event->SetInt("vote_option3", 0);
215 event->SetInt("vote_option4", 0);
216 event->SetInt("vote_option5", 0);
217 event->SetInt("potentialVotes", tally.Eligible);
218 _events.FireEvent(event);
219}
220
221void Vote::SendStart(const Ballot& ballot)
222{
223 CRecipientFilter filter = Recipients();
224 PostUserMessage(_interfaces, _voteStartType, VoteStartMessage, filter, [&ballot](CNetMessage* raw) {
225 auto* start = raw->ToPB<CCSUsrMsg_VoteStart>();
226 start->set_team(AllTeams);
227 start->set_player_slot(ballot.Request.Caller);
228 start->set_vote_type(-1);
229 start->set_disp_str(ballot.Request.Title);
230 start->set_details_str(ballot.Request.Detail);
231 start->set_is_yes_no_vote(true);
232 return true;
233 });
234}
235
236void Vote::SendOutcome(const VoteRequest& request, bool passed)
237{
238 // Pass and fail are distinct message types, so each gets its own cache slot.
239 auto& cached = passed ? _votePassType : _voteFailedType;
240 CRecipientFilter filter = Recipients();
241
242 PostUserMessage(_interfaces, cached, passed ? VotePassMessage : VoteFailedMessage, filter,
243 [&request, passed](CNetMessage* raw) {
244 if (passed)
245 {
246 auto* pass = raw->ToPB<CCSUsrMsg_VotePass>();
247 pass->set_team(AllTeams);
248 pass->set_vote_type(-1);
249 pass->set_disp_str(request.Title);
250 pass->set_details_str(request.Detail);
251 }
252 else
253 {
254 auto* fail = raw->ToPB<CCSUsrMsg_VoteFailed>();
255 fail->set_team(AllTeams);
256 fail->set_reason(0);
257 }
258 return true;
259 });
260}
261
262} // namespace VoltMod
A player's identity behind a slot: name, money, team, scoreboard row. It survives death and respawn; ...
runtime.Entities: finds and creates entities. Everything it returns is valid for this frame only; see...
Creates, fires and listens to game events.
The roster: every connected player, and the signals for the connection lifecycle.
std::span< Player *const > All() const
Event< Player & > Disconnected
A player is leaving. Raised while they are still in the roster, so the handler can read their identit...
One connected player, owned by PlayerManager for the length of the connection.
Definition Player.hpp:23
One-shot delays and repeating timers, run on the game thread.
Definition Scheduler.hpp:18
Vote(Interfaces &interfaces, EntitySystem &entities, PlayerManager &players, GameEvents &events, Scheduler &scheduler)
Definition Vote.cpp:36
bool TryCastBallot(int slot, std::string_view option)
Definition Vote.cpp:99
bool Start(VoteRequest request)
Definition Vote.cpp:62
void End(VoteEndReason reason)
Definition Vote.cpp:158
bool PostUserMessage(Interfaces &interfaces, NetMessageInfo_t *&cached, std::string_view partialName, IRecipientFilter &filter, const std::function< bool(CNetMessage *)> &fill)
static constexpr int NoOption
Definition Vote.cpp:29
static constexpr std::string_view ControllerClass
static constexpr std::string_view VoteFailedMessage
Definition Vote.cpp:34
static constexpr int YesNoIssueIndex
Definition Vote.cpp:23
static constexpr std::string_view VotePassMessage
Definition Vote.cpp:33
constexpr bool IsValidSlot(int slot)
Definition Slot.hpp:13
VoteEndReason
Definition Vote.hpp:24
@ Cancelled
an admin (or a peer feature) called it off
Definition Vote.hpp:27
@ AllVoted
every eligible player cast a ballot
Definition Vote.hpp:25
static constexpr std::string_view VoteStartMessage
Definition Vote.cpp:32
static constexpr int NoIssue
Definition Vote.cpp:24
static constexpr int AllTeams
Definition Vote.cpp:25
static constexpr int YesOption
Definition Vote.cpp:28
Centralized holder for all SDK interface pointers.
static constexpr std::string_view EventName
static constexpr std::string_view EventName
std::function< bool(const VoteTally &)> Passed
Definition Vote.hpp:52
int Eligible
players who could vote
Definition Vote.hpp:33