88
99extern " C" {
1010#include < z64.h>
11+ #include " variables.h"
1112extern PlayState* gPlayState ;
1213}
1314
@@ -18,19 +19,131 @@ void CrowdControl::Enable() {
1819}
1920
2021void CrowdControl::Disable () {
22+ // Joins the network thread, so after this only the game thread touches CC state
2123 Network::Disable ();
24+
25+ ClearPayloadQueues ();
26+
27+ // Timed effects stop ticking once disabled, so undo them rather than leaving them stuck on. Removal can be
28+ // refused (e.g. during a textbox or cutscene), so they're moved to a pending list that the frame hook keeps
29+ // retrying until each one is actually removed. They're kept apart from activeEffects so re-enabling doesn't
30+ // resume them against the new CC session.
31+ for (auto & effect : activeEffects) {
32+ effectsPendingRemoval.push_back (std::move (effect));
33+ }
34+ activeEffects.clear ();
35+ SPDLOG_INFO (" [CrowdControl] Disabled, removing {} timed effect(s)" , effectsPendingRemoval.size ());
36+ ProcessPendingRemovals ();
37+
2238 ShipInit::Init (CVAR_REMOTE_CROWD_CONTROL (" Enabled" ));
2339}
2440
25- void CrowdControl::OnConnected () {
26- ccThreadProcess = std::thread (&CrowdControl::ProcessActiveEffects, this );
41+ // Returns true once the effect no longer needs removing (removed, or can never be removed). Returns false when
42+ // removal is only temporarily refused (gameplay paused, textbox, cutscene, no save loaded), so the caller should
43+ // retry later. Ignoring that result would drop the effect while its state stays applied for good.
44+ bool CrowdControl::TryRemoveEffect (Effect* effect) {
45+ auto * removable = dynamic_cast <RemovableGameInteractionEffect*>(effect->giEffect .get ());
46+ if (removable == nullptr ) {
47+ return true ;
48+ }
49+
50+ GameInteractionEffectQueryResult result = GameInteractor::RemoveEffect (*removable);
51+ if (result == GameInteractionEffectQueryResult::TemporarilyNotPossible) {
52+ return false ;
53+ }
54+ if (result != GameInteractionEffectQueryResult::Possible) {
55+ SPDLOG_WARN (" [CrowdControl] Timed effect {} could not be removed" , effect->id );
56+ }
57+ return true ;
58+ }
59+
60+ void CrowdControl::ProcessPendingRemovals () {
61+ auto it = effectsPendingRemoval.begin ();
62+ while (it != effectsPendingRemoval.end ()) {
63+ if (TryRemoveEffect (it->get ())) {
64+ it = effectsPendingRemoval.erase (it);
65+ } else {
66+ it++;
67+ }
68+ }
69+ }
70+
71+ bool CrowdControl::NeedsFrameUpdate () {
72+ return isEnabled || !effectsPendingRemoval.empty ();
2773}
2874
29- void CrowdControl::OnDisconnected () {
30- ccThreadProcess.join ();
75+ // Only cleared on a manual disable. Connection hiccups keep both queues, so effects already received still run
76+ // and any status updates emitted while disconnected are sent once the connection comes back.
77+ void CrowdControl::ClearPayloadQueues () {
78+ {
79+ std::lock_guard<std::mutex> lock (incomingPayloadQueueMutex);
80+ std::queue<nlohmann::json>().swap (incomingPayloadQueue);
81+ }
82+ {
83+ std::lock_guard<std::mutex> lock (outgoingPayloadQueueMutex);
84+ std::queue<nlohmann::json>().swap (outgoingPayloadQueue);
85+ }
3186}
3287
88+ // Effects touch game state (spawning actors, inventory, player), so they must only ever run on the game
89+ // thread. The network thread queues incoming payloads here, and they're executed in OnGameFrameUpdate.
3390void CrowdControl::OnIncomingJson (nlohmann::json payload) {
91+ // Version requests don't touch game state, so answer them right away instead of queuing them as effects
92+ if (payload.contains (" type" ) && payload[" type" ].is_number_integer () &&
93+ payload[" type" ].get <int >() == ResponseType::Version) {
94+ SendVersion (payload.value (" id" , 0u ));
95+ return ;
96+ }
97+
98+ std::lock_guard<std::mutex> lock (incomingPayloadQueueMutex);
99+ incomingPayloadQueue.push (payload);
100+ }
101+
102+ // Announce our version on every connection instead of waiting to be asked. The pack does request it when the
103+ // connection opens, but that request can be lost if it arrives before the pack has finished registering this
104+ // client, and it isn't retried. An unsolicited response with id 0 is accepted all the same.
105+ void CrowdControl::OnConnected () {
106+ SendVersion (0 );
107+ }
108+
109+ void CrowdControl::OnGameFrameUpdate () {
110+ // Effects left over from a disable are retried every frame until they've all been removed.
111+ ProcessPendingRemovals ();
112+
113+ if (!isEnabled) {
114+ return ;
115+ }
116+
117+ // Copy all queued payloads while holding the lock, then process them after releasing
118+ std::queue<nlohmann::json> payloadsToProcess;
119+ {
120+ std::lock_guard<std::mutex> lock (incomingPayloadQueueMutex);
121+ payloadsToProcess.swap (incomingPayloadQueue);
122+ }
123+
124+ while (!payloadsToProcess.empty ()) {
125+ try {
126+ ProcessIncomingPayload (payloadsToProcess.front ());
127+ } catch (const std::exception& e) {
128+ SPDLOG_ERROR (" [CrowdControl] Exception handling incoming JSON: {}" , e.what ());
129+ } catch (...) { SPDLOG_ERROR (" [CrowdControl] Unknown exception handling incoming JSON" ); }
130+ payloadsToProcess.pop ();
131+ }
132+
133+ // Timed effects are ticked once per second. Advance by exactly one second so frame timing doesn't make
134+ // effects run longer than CC's overlay timer, but resync if we've fallen far behind (e.g. a long stall)
135+ // instead of firing a burst of catch-up ticks.
136+ auto now = std::chrono::steady_clock::now ();
137+ if (now - lastActiveEffectsTick >= std::chrono::seconds (1 )) {
138+ lastActiveEffectsTick += std::chrono::seconds (1 );
139+ if (now - lastActiveEffectsTick >= std::chrono::seconds (1 )) {
140+ lastActiveEffectsTick = now;
141+ }
142+ ProcessActiveEffects ();
143+ }
144+ }
145+
146+ void CrowdControl::ProcessIncomingPayload (nlohmann::json payload) {
34147 std::unique_ptr<Effect> incomingEffect = ParseMessage (payload);
35148 if (!incomingEffect) {
36149 return ;
@@ -60,65 +173,78 @@ void CrowdControl::OnIncomingJson(nlohmann::json payload) {
60173 return ;
61174 }
62175
63- activeEffectsMutex.lock ();
64176 activeEffects.push_back (std::move (incomingEffect));
65- activeEffectsMutex.unlock ();
66177 }
67178 }
68179}
69180
70181void CrowdControl::ProcessActiveEffects () {
71- while (isEnabled) {
72- // We only want to send events when status changes, on start we send Success.
73- // If it fails at some point, we send Pause, and when it starts to succeed again we send Success.
74- // CC uses this to pause the timer on the overlay.
75- activeEffectsMutex.lock ();
76- auto it = activeEffects.begin ();
77-
78- while (it != activeEffects.end ()) {
79- Effect* effect = it->get ();
80- EffectResult result = CrowdControl::ExecuteEffect (effect);
81-
82- if (result == EffectResult::Success) {
83- // If time remaining has reached 0, we have finished the effect.
84- if (effect->timeRemaining <= 0 ) {
85- GameInteractor::RemoveEffect (
86- *dynamic_cast <RemovableGameInteractionEffect*>(effect->giEffect .get ()));
182+ // We only want to send events when status changes, on start we send Success.
183+ // If it fails at some point, we send Pause, and when it starts to succeed again we send Success.
184+ // CC uses this to pause the timer on the overlay.
185+ auto it = activeEffects.begin ();
186+
187+ while (it != activeEffects.end ()) {
188+ Effect* effect = it->get ();
189+ EffectResult result = CrowdControl::ExecuteEffect (effect);
190+
191+ if (result == EffectResult::Success) {
192+ // If time remaining has reached 0, we have finished the effect.
193+ // If removal is temporarily refused, keep it and retry on the next tick.
194+ if (effect->timeRemaining <= 0 ) {
195+ if (TryRemoveEffect (effect)) {
87196 it = activeEffects.erase (it);
88197 } else {
89- // If we have a success after previously being paused, tell CC to resume timer.
90- if (effect->isPaused ) {
91- effect->isPaused = false ;
92- EmitMessage (effect->id , effect->timeRemaining , EffectResult::Resumed);
93- // If not paused before, subtract time from the timer and send a Success event if
94- // the result is different from the last time this was ran.
95- // Timed events are put on a thread that runs once per second.
96- } else {
97- effect->timeRemaining -= 1000 ;
98- if (result != effect->lastExecutionResult ) {
99- effect->lastExecutionResult = result;
100- EmitMessage (effect->id , effect->timeRemaining , EffectResult::Success);
101- }
102- }
103198 it++;
104199 }
105- } else { // Timed effects only do Success or Retry
106- if (!effect->isPaused && effect->timeRemaining > 0 ) {
107- effect->isPaused = true ;
108- EmitMessage (effect->id , effect->timeRemaining , EffectResult::Paused);
200+ } else {
201+ // If we have a success after previously being paused, tell CC to resume timer.
202+ if (effect->isPaused ) {
203+ effect->isPaused = false ;
204+ EmitMessage (effect->id , effect->timeRemaining , EffectResult::Resumed);
205+ // If not paused before, subtract time from the timer and send a Success event if
206+ // the result is different from the last time this was ran.
207+ // Timed events are ticked once per second.
208+ } else {
209+ effect->timeRemaining -= 1000 ;
210+ if (result != effect->lastExecutionResult ) {
211+ effect->lastExecutionResult = result;
212+ EmitMessage (effect->id , effect->timeRemaining , EffectResult::Success);
213+ }
109214 }
110215 it++;
111216 }
217+ } else { // Timed effects only do Success or Retry
218+ if (!effect->isPaused && effect->timeRemaining > 0 ) {
219+ effect->isPaused = true ;
220+ EmitMessage (effect->id , effect->timeRemaining , EffectResult::Paused);
221+ }
222+ it++;
112223 }
224+ }
225+ }
113226
114- activeEffectsMutex.unlock ();
115- std::this_thread::sleep_for (std::chrono::seconds (1 ));
227+ void CrowdControl::ProcessOutgoingPackets () {
228+ // Copy all queued payloads while holding the lock, then send them after releasing
229+ std::queue<nlohmann::json> payloadsToSend;
230+ {
231+ std::lock_guard<std::mutex> lock (outgoingPayloadQueueMutex);
232+ payloadsToSend.swap (outgoingPayloadQueue);
116233 }
117234
118- SPDLOG_TRACE (" [CrowdControl] Ending Process thread..." );
235+ while (!payloadsToSend.empty ()) {
236+ SendJsonToRemote (payloadsToSend.front ());
237+ payloadsToSend.pop ();
238+ }
119239}
120240
121241void CrowdControl::EmitMessage (uint32_t eventId, long timeRemaining, EffectResult status) {
242+ // Queued even while disconnected, so CC catches up on effect status after a connection hiccup.
243+ // A manual disable clears the queue.
244+ if (!isEnabled) {
245+ return ;
246+ }
247+
122248 nlohmann::json payload;
123249
124250 payload[" id" ] = eventId;
@@ -128,7 +254,27 @@ void CrowdControl::EmitMessage(uint32_t eventId, long timeRemaining, EffectResul
128254
129255 SPDLOG_INFO (" [CrowdControl] Sending payload:\n {}" , payload.dump ());
130256
131- SendJsonToRemote (payload);
257+ // Queue the payload to be sent on the network thread
258+ std::lock_guard<std::mutex> lock (outgoingPayloadQueueMutex);
259+ outgoingPayloadQueue.push (payload);
260+ }
261+
262+ // Reports this build to CC so the pack can require a minimum version. Team and commit hash tell forks apart.
263+ // The client only reads "version", extra fields are ignored by older clients.
264+ void CrowdControl::SendVersion (uint32_t id) {
265+ nlohmann::json payload;
266+
267+ payload[" id" ] = id;
268+ payload[" type" ] = ResponseType::Version;
269+ payload[" version" ] = std::to_string (gBuildVersionMajor ) + " ." + std::to_string (gBuildVersionMinor ) + " ." +
270+ std::to_string (gBuildVersionPatch );
271+ payload[" team" ] = std::string ((const char *)gBuildTeam );
272+ payload[" commit" ] = std::string (gGitCommitHash );
273+
274+ SPDLOG_INFO (" [CrowdControl] Sending version:\n {}" , payload.dump ());
275+
276+ std::lock_guard<std::mutex> lock (outgoingPayloadQueueMutex);
277+ outgoingPayloadQueue.push (payload);
132278}
133279
134280CrowdControl::EffectResult CrowdControl::ExecuteEffect (Effect* effect) {
@@ -186,7 +332,7 @@ std::unique_ptr<CrowdControl::Effect> CrowdControl::ParseMessage(nlohmann::json
186332
187333 // "parameters" is intentionally not required: most effects (spawn enemies, teleports, status
188334 // effects, etc.) carry no parameters. Its absence is handled safely below, and any type error
189- // is caught by the guard in Network::HandleRemoteJson .
335+ // is caught by the guard in CrowdControl::OnGameFrameUpdate .
190336 if (!dataReceived.contains (" code" ) || !dataReceived.contains (" viewer" )) {
191337 // This seems to happen when the CC session ends
192338 SPDLOG_ERROR (" [CrowdControl] Payload does not contain code or viewer, ignoring." );
@@ -683,3 +829,11 @@ std::unique_ptr<CrowdControl::Effect> CrowdControl::ParseMessage(nlohmann::json
683829
684830 return effect;
685831}
832+
833+ static void RegisterCrowdControl () {
834+ // Stays registered after a disable until any leftover timed effects have been removed
835+ COND_HOOK (OnGameFrameUpdate, CrowdControl::Instance != nullptr && CrowdControl::Instance->NeedsFrameUpdate (),
836+ []() { CrowdControl::Instance->OnGameFrameUpdate (); });
837+ }
838+
839+ static RegisterShipInitFunc initFunc (RegisterCrowdControl, { CVAR_REMOTE_CROWD_CONTROL (" Enabled" ) });
0 commit comments