forked from NtsFranz/Spark
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProgram.cs
3889 lines (3288 loc) · 111 KB
/
Program.cs
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
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Numerics;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using Spark.Properties;
using Microsoft.Win32;
using Newtonsoft.Json;
using static Logger;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Management;
using System.Resources;
using EchoVRAPI;
using NetMQ;
using Newtonsoft.Json.Linq;
using Microsoft.Web.WebView2.Core;
namespace Spark
{
/// <summary>
/// Main
/// </summary>
internal class Program
{
/// <summary>
/// Set this to false to finish up and close
/// </summary>
public static bool running = true;
public enum ConnectionState {
NotConnected,
Menu, // loading screen or menu - the response is not json
NoAPI, // user has not enabled API access
InLobby, // error code for lobby -6
InGame // in an arena or combat match
}
public static ConnectionState connectionState;
public static ConnectionState lastConnectionState;
public static ConnectionState lastConnectionStateEvent;
public static bool InGame => connectionState == ConnectionState.InGame;
public const string APIURL = "https://api.ignitevr.gg";
// public const string APIURL = "http://127.0.0.1:8000";
public const string WRITE_API_URL = "http://127.0.0.1:6723/";
// public static string currentAccessCodeUsername = "";
public static string InstalledSpeakerSystemVersion = "";
public static bool IsSpeakerSystemUpdateAvailable;
public static ConcurrentQueue<AccumulatedFrame> rounds = new ConcurrentQueue<AccumulatedFrame>();
public static AccumulatedFrame CurrentRound => rounds.LastOrDefault() ?? emptyRound;
public static AccumulatedFrame LastRound => rounds.TakeLast(2).FirstOrDefault() ?? emptyRound;
private static readonly AccumulatedFrame emptyRound = new AccumulatedFrame(Frame.CreateEmpty());
public static IEnumerable<GoalData> LastGoals => rounds.SelectMany(r => r.goals);
public static IEnumerable<EventData> LastJousts => rounds.SelectMany(r => r.events.Where(e=>e.eventType.IsJoust()));
/// <summary>
/// Contains the last state so that we can do a diff to determine state changes
/// This acts like a set of flags.
/// </summary>
public static Frame lastFrame;
public static Frame lastLastFrame;
public static Frame lastLastLastFrame;
private static int lastFrameSumOfStats;
private static Frame lastValidStatsFrame;
private static int lastValidSumOfStatsAge = 0;
private static long frameIndex = 0;
private static long lastProcessedFrameIndex = 0;
private class UserAtTime
{
public float gameClock;
public Player player;
}
// { [stunner, stunnee], [stunner, stunnee] }
static List<UserAtTime[]> stunningMatchedPairs = new List<UserAtTime[]>();
private const float stunMatchingTimeout = 4f;
public static string lastDateTimeString;
public static string lastJSON;
public static string lastBonesJSON;
public static ulong fetchFrameIndex = 0;
private static readonly object lastJSONLock = new object();
private static readonly object lastFrameLock = new object();
public static readonly object logOutputWriteLock = new object();
public static readonly object gameStateLock = new object();
public static DateTime lastDataTime;
static float minTillAutorestart = 3;
static bool wasThrown;
static int lastThrowPlayerId = -1;
public static float serverScoreSmoothingFactor = .95f;
/// <summary>
/// Not actually Hz. 1/Hz.
/// </summary>
public static float StatsIntervalMs => statsDeltaTimes[SparkSettings.instance.lowFrequencyMode ? 1 : 0];
private static bool? lastLowFreqMode = null;
// 30 or 15 hz main fetch speed
private static readonly List<float> statsDeltaTimes = new List<float> { 33.3333333f, 66.6666666f };
public static LiveWindow liveWindow;
private static ClosingDialog closingWindow;
private static readonly Dictionary<string, Window> popupWindows = new Dictionary<string, Window>();
private static float smoothDeltaTime = -1;
public static bool hostingLiveReplay = false;
public static string echoVRIP = "";
public static int echoVRPort = 6721;
public static bool overrideEchoVRPort;
public static string hostedAtlasSessionId;
public static LiveWindow.AtlasWhitelist atlasWhitelist = new LiveWindow.AtlasWhitelist();
public static TTSController synth;
public static ReplayClips replayClips;
public static ReplayFilesManager replayFilesManager;
public static CameraWriteController cameraWriteController;
public static CameraWrite cameraWriteWindow;
public static EchoGPController echoGPController;
public static WebSocketServerManager webSocketMan;
public static SpeechRecognition speechRecognizer;
public static LoggerEvents loggerEvents;
private static CancellationTokenSource autorestartCancellation;
private static CancellationTokenSource fetchThreadCancellation;
private static CancellationTokenSource liveReplayCancel;
public static Thread atlasHostingThread;
private static Thread IPSearchThread1;
private static Thread IPSearchThread2;
public static OBS obs;
public static Medal medal;
private static OverlayServer overlayServer;
public static SpectateMeController spectateMeController;
public static UploadController uploadController;
public static LocalDatabase localDatabase;
public static NetMQEvents netMQEvents;
private static readonly HttpClient fetchClient = new HttpClient();
// private static readonly System.Timers.Timer fetchTimer = new System.Timers.Timer();
private static readonly Stopwatch fetchSw = new Stopwatch();
private static Timer ccuCounter;
public static CameraController cameraController;
public static CoreWebView2Environment webView2Environment;
#region Event Callbacks
public static Action SparkClosing;
/// <summary>
/// Called by the fetch thread when a frame is successfully fetched
/// Subscribe to this for raw json data. Only use this in a context that doesn't care about the deserialzed frames.
/// params: timestamp, session string, bones string (or null)
/// </summary>
public static Action<DateTime, string, string> FrameFetched;
/// <summary>
/// Called when a frame is finished with conversion.
/// Subscribe to this for Frame objects
/// </summary>
public static Action<Frame> NewFrame;
/// <summary>
/// Called when a frame is finished with conversion and it is an Echo Arena frame
/// </summary>
public static Action<Frame> NewArenaFrame;
/// <summary>
/// Called when a frame is finished with conversion and it is an Echo Combat frame
/// </summary>
public static Action<Frame> NewCombatFrame;
/// <summary>
/// Called when connectedToGame state changes.
/// This could be on loading screen or lobby
/// string is the raw /session, but this may be from html from a menu
/// </summary>
public static Action<DateTime, string> ConnectedToGame;
/// <summary>
/// Called when connectedToGame state changes to Not_Connected.
/// </summary>
public static Action DisconnectedFromGame;
/// <summary>
/// When the connectedToGame state changes to InGame
/// </summary>
public static Action<Frame> JoinedGame;
/// <summary>
/// When the connectedToGame state changes to Not_Connected and the previous state was InGame
/// </summary>
public static Action<Frame> LeftGame;
/// <summary>
/// We changed session ids. This happens for first join and switching matches
/// </summary>
public static Action<Frame> NewMatch;
public static Action<Frame, AccumulatedFrame.FinishReason> RoundOver;
/// <summary>
/// A new round started. This only happens for secondary rounds in private matches.
/// Frame is the first frame of the new round with scores at 0-0
/// </summary>
public static Action<Frame> NewRound;
public static Action<Frame> JoinedLobby;
public static Action<Frame> LeftLobby;
public static Action<Frame, Team, Player> PlayerJoined;
public static Action<Frame, Team, Player> PlayerLeft;
/// <summary>
/// frame, fromteam, toteam, player
/// </summary>
public static Action<Frame, Team, Team, Player> PlayerSwitchedTeams;
// TODO add player/team who requested the reset
/// <summary>
/// Frame is the last frame of the last match
/// </summary>
public static Action<Frame> MatchReset;
/// <summary>
/// Frame, nearest player, distance to podium
/// </summary>
public static Action<Frame, Player, float> PauseRequest;
/// <summary>
/// Frame, nearest player, distance to podium
/// </summary>
public static Action<Frame, Player, float> GamePaused;
/// <summary>
/// Frame, nearest player, distance to podium
/// </summary>
public static Action<Frame, Player, float> GameUnpaused;
/// <summary>
/// lastFrame, newFrame
/// </summary>
public static Action<Frame, Frame> GameStatusChanged;
public static Action<Frame> LocalThrow;
/// <summary>
/// frame, team, player, speed, howlongago
/// </summary>
public static Action<Frame, Team, Player, float, float> BigBoost;
/// <summary>
/// bool is true for left, false for right
/// </summary>
public static Action<Frame, Team, Player, bool> EmoteActivated;
/// <summary>
/// frame, team, player, playspacelocation (compare to head.Pos)
/// </summary>
public static Action<Frame, Team, Player, Vector3> PlayspaceAbuse;
public static Action<Frame, EventData> Save;
public static Action<Frame, EventData> Steal;
/// <summary>
/// frame, stunner_team, stunner_player, stunee_player
/// </summary>
public static Action<Frame, EventData> Stun;
/// <summary>
/// Catch by other team from throw within 7 seconds
/// frame, team, throwplayer, catchplayer
/// </summary>
public static Action<Frame, Team, Player, Player> Interception;
/// <summary>
/// Catch by same team as throw within 7 seconds
/// frame, team, throwplayer, catchplayer
/// </summary>
public static Action<Frame, Team, Player, Player> Pass;
/// <summary>
/// Catch by the other team
/// frame, team, throwplayer, catchplayer
/// </summary>
public static Action<Frame, Team, Player, Player> Turnover;
/// <summary>
/// Any catch, including interceptions, passes, and turnovers
/// frame, team, player
/// </summary>
public static Action<Frame, Team, Player> Catch;
/// <summary>
/// frame, team, player, lefthanded, underhandedness
/// </summary>
public static Action<Frame, Team, Player, bool, float> Throw;
public static Action<Frame, Team, Player> ShotTaken;
/// <summary>
/// Frame, teamcolor, nearest player, distance to podium
/// </summary>
public static Action<Frame, Team.TeamColor, Player, float> RestartRequest;
/// <summary>
/// frame, team, player, neutral joust?, time, maxSpeed, tubeExitSpeed
/// </summary>
public static Action<Frame, Team, Player, bool, float, float, float> Joust;
public static Action<Frame, EventData> JoustEvent;
public static Action<Frame, GoalData> Goal;
/// <summary>
/// This is called on the first frame that the goal happens rather than waiting for stable data
/// </summary>
public static Action<Frame> GoalImmediate;
public static Action<Frame, GoalData> Assist;
public static Action<Frame, Team, Player> LargePing;
public static Action<Frame> RulesChanged;
public static Action ManualClip;
public static Action BadWordDetected;
/// <summary>
/// For any event type that has EventData
/// </summary>
public static Action<EventData> OnEvent;
#region Spark Settings Changed
public static Action OverlayConfigChanged;
public static Action<string> EventLog;
public static Action<string> IPGeolocated;
#endregion
#endregion
private static App app;
public static void Main(string[] args, App app)
{
try
{
Logger.Init();
Program.app = app;
if (args.Contains("-port"))
{
int index = args.ToList().IndexOf("-port");
if (index > -1)
{
if (int.TryParse(args[index + 1], out echoVRPort))
{
overrideEchoVRPort = true;
}
}
else
{
LogRow(LogType.Error, "ERROR 3984. This shouldn't happen");
}
}
FetchUtils.client.DefaultRequestHeaders.Add("version", AppVersionString());
FetchUtils.client.DefaultRequestHeaders.Add("User-Agent", "Spark/" + AppVersionString());
FetchUtils.client.BaseAddress = new Uri(APIURL);
if (CheckIfLaunchedWithCustomURLHandlerParam(args))
{
return; // wait for the dialog to quit the program
}
// allow multiple instances if the port is overriden
if (IsSparkOpen() && !overrideEchoVRPort)
{
Task.Run(async () =>
{
HttpClient localClient = new HttpClient();
localClient.Timeout = TimeSpan.FromSeconds(1);
try
{
string responseBody = await localClient.GetStringAsync("http://localhost:6724/api/focus_spark");
Console.WriteLine(responseBody);
}
catch (Exception)
{
// ignored
}
Quit();
});
return;
// MessageBox box = new MessageBox(Resources.instance_already_running_message, Resources.Error);
// box.Show();
// //while(box!= null)
// {
// Thread.Sleep(10);
// }
//return; // wait for the dialog to quit the program
}
netMQEvents = new NetMQEvents();
InstalledSpeakerSystemVersion = FindEchoSpeakerSystemInstallVersion();
if (InstalledSpeakerSystemVersion.Length > 0)
{
string[] latestSpeakerSystemVer = GetLatestSpeakerSystemURLVer();
IsSpeakerSystemUpdateAvailable = latestSpeakerSystemVer[1] != InstalledSpeakerSystemVersion;
}
SparkSettings.instance.sparkExeLocation = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Spark.exe");
SparkSettings.instance.Save();
RegisterUriScheme("atlas", "ATLAS Protocol");
RegisterUriScheme("spark", "Spark Protocol");
obs = new OBS();
medal = new Medal();
// if logged in with discord
if (!string.IsNullOrEmpty(SparkSettings.instance.discordOAuthRefreshToken))
{
DiscordOAuth.OAuthLoginRefresh(SparkSettings.instance.discordOAuthRefreshToken);
}
else
{
DiscordOAuth.RevertToPersonal();
}
_ = Task.Run(() =>
{
string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "IgniteVR", "Spark", "WebView");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
//webView2Environment = await CoreWebView2Environment.CreateAsync(null, path);
Debug.WriteLine(Directory.Exists(path));
});
liveWindow = new LiveWindow();
liveWindow.Closed += (_, _) => liveWindow = null;
liveWindow.Show();
if (!SparkSettings.instance.firstTimeSetupShown)
{
ToggleWindow(typeof(FirstTimeSetupWindow));
SparkSettings.instance.firstTimeSetupShown = true;
}
// Check for command-line flags
if (args.Contains("-slowmode"))
{
SparkSettings.instance.lowFrequencyMode = true;
}
if (args.Contains("-autorestart"))
{
SparkSettings.instance.autoRestart = true;
}
if (args.Contains("-showdatabaselog"))
{
SparkSettings.instance.showDatabaseLog = true;
}
// make an exception for certain users
// Note that these usernames are not the access codes. Don't even try.
if (DiscordOAuth.AccessCode.series_name == "ignitevr")
{
ENABLE_LOGGER = false;
}
ReadSettings();
if (!SparkSettings.instance.onlyActivateHighlightsWhenGameIsOpen &&
SparkSettings.instance.isNVHighlightsEnabled)
{
HighlightsHelper.SetupNVHighlights();
}
else
{
HighlightsHelper.InitHighlightsSDK(true);
}
// only enable Highlights when game is open
ConnectedToGame += (_, _) =>
{
if (!HighlightsHelper.isNVHighlightsEnabled)
{
HighlightsHelper.SetupNVHighlights();
}
};
DisconnectedFromGame += () =>
{
if (SparkSettings.instance.onlyActivateHighlightsWhenGameIsOpen)
{
HighlightsHelper.CloseNVHighlights();
}
};
// TODO don't initialize twice and get this to work without discord login maybe
synth = new TTSController();
DiscordOAuth.Authenticated += () =>
{
synth = new TTSController();
// Configure the audio output.
synth.SetOutputToDefaultAudioDevice();
synth.SetRate(SparkSettings.instance.TTSSpeed);
};
// this sets up the event listeners for replay clips
replayClips = new ReplayClips();
// Set up listeners for camera-related events
cameraWriteController = new CameraWriteController();
// sets up listeners for replay file saving
replayFilesManager = new ReplayFilesManager();
// sets up listeners for Echo GP timer
echoGPController = new EchoGPController();
webSocketMan = new WebSocketServerManager();
speechRecognizer = new SpeechRecognition();
loggerEvents = new LoggerEvents();
spectateMeController = new SpectateMeController();
uploadController = new UploadController();
localDatabase = new LocalDatabase();
cameraController = new CameraController();
// web server asp.net
try
{
overlayServer = new OverlayServer();
}
catch (Exception e)
{
LogRow(LogType.Error, e.ToString());
}
UpdateEchoExeLocation();
DiscordRichPresence.Start();
spectateMeController.spectateMe = SparkSettings.instance.spectateMeOnByDefault;
autorestartCancellation = new CancellationTokenSource();
Task.Run(AutorestartTask, autorestartCancellation.Token);
fetchThreadCancellation = new CancellationTokenSource();
Task.Run(MainLoop, fetchThreadCancellation.Token);
liveReplayCancel = new CancellationTokenSource();
_ = Task.Run(LiveReplayHostingTask, liveReplayCancel.Token);
_ = Task.Run(async () =>
{
try
{
EchoVRSettingsManager.ReloadLoadingTips();
if (EchoVRSettingsManager.loadingTips != null)
{
JToken toolsAll = EchoVRSettingsManager.loadingTips["tools-all"];
JArray tips = (JArray)EchoVRSettingsManager.loadingTips["tools-all"]?["tips"];
if (tips != null)
{
// keep only those without SPARK in the title
tips = new JArray(tips.Where(t => (string)t[1] != "SPARK"));
ResourceSet resourceSet =
LoadingTips.ResourceManager.GetResourceSet(CultureInfo.CurrentUICulture, true,
true);
if (resourceSet != null)
{
// loop through the resource strings
foreach (DictionaryEntry entry in resourceSet)
{
string tip = entry.Value?.ToString();
if (tip != null)
{
if (tips.All(existingTip => (string)existingTip[2] != tip))
{
tips.Add(new JArray("", "SPARK", tip));
}
}
else
{
LogRow(LogType.Error, "Loading tip was null.");
}
}
}
if (toolsAll != null) toolsAll["tips"] = tips;
}
EchoVRSettingsManager.WriteEchoVRLoadingTips(EchoVRSettingsManager.loadingTips);
}
}
catch (Exception e)
{
Logger.Error(e.ToString());
}
// wait 5 seconds for login to happen
await Task.Delay(5000);
AutoUploadTabletStats();
});
//HighlightsHelper.CloseNVHighlights();
ccuCounter = new Timer(CCUCounter, null, 0, 60000);
#region Add Listeners
JoinedGame += OnJoinedGame;
LeftGame += OnLeftGame;
#endregion
}
catch (Exception e)
{
Logger.Error(e.ToString());
Quit();
}
}
private static void OnLeftGame(Frame obj)
{
//
}
public static Version AppVersion()
{
return Application.Current.GetType().Assembly.GetName().Version;
}
public static string AppVersionString()
{
Version version = AppVersion();
return $"{version.Major}.{version.Minor}.{version.Build}";
}
public static bool IsWindowsStore()
{
#if WINDOWS_STORE_RELEASE
return true;
#else
return false;
#endif
}
private static void CCUCounter(object state)
{
_ = FetchUtils.client.PostAsync($"/spark_is_open?hw_id={DeviceId}&client_name={SparkSettings.instance.client_name}", null);
}
/// <summary>
/// This is just a failsafe so that the program doesn't leave a dangling thread.
/// </summary>
private static void KillAll()
{
if (liveWindow != null)
{
liveWindow.Close();
liveWindow = null;
}
overlayServer?.Stop();
}
private static async Task GentleClose()
{
running = false;
if (closingWindow != null)
{
closingWindow.label.Content = Resources.Closing___;
}
netMQEvents?.CloseApp();
await Task.Delay(50);
overlayServer?.Stop();
while (atlasHostingThread != null && atlasHostingThread.IsAlive)
{
if (closingWindow != null) closingWindow.label.Content = Resources.Shutting_down_Atlas___;
await Task.Delay(10);
}
autorestartCancellation?.Cancel();
fetchThreadCancellation?.Cancel();
liveReplayCancel?.Cancel();
ccuCounter?.Dispose();
if (replayFilesManager != null)
{
while (replayFilesManager.zipping ||
replayFilesManager.replayThreadActive ||
replayFilesManager.splitting)
{
if (closingWindow != null) closingWindow.label.Content = Resources.Compressing_Replay_File___;
await Task.Delay(10);
}
}
if (closingWindow != null) closingWindow.label.Content = Resources.Closing_NVIDIA_Highlights___;
HighlightsHelper.CloseNVHighlights();
if (closingWindow != null) closingWindow.label.Content = Resources.Closing_Speaker_System___;
liveWindow?.KillSpeakerSystem();
if (closingWindow != null) closingWindow.label.Content = "Closing PubSub System...";
AsyncIO.ForceDotNet.Force();
NetMQConfig.Cleanup(false);
if (closingWindow != null) closingWindow.label.Content = Resources.Closing___;
app.ExitApplication();
await Task.Delay(100);
if (closingWindow != null) closingWindow.label.Content = "Failed to close gracefully. Using an axe instead...";
LogRow(LogType.Error, "Failed to close gracefully. Using an axe instead...");
KillAll();
}
/// <summary>
/// Checks if another instance of Spark is open
/// </summary>
/// <returns>True if another is open, false if not.</returns>
private static bool IsSparkOpen()
{
try
{
Process[] process = Process.GetProcessesByName("IgniteBot");
Process[] processesSpark = Process.GetProcessesByName("Spark");
return process?.Length > 1 || processesSpark?.Length > 1;
}
catch (Exception e)
{
LogRow(LogType.Error, "Error getting other Spark windows\n" + e.ToString());
}
return false;
}
private static async Task MainLoop()
{
fetchClient.Timeout = TimeSpan.FromSeconds(5);
DateTime lastFetch = DateTime.UtcNow;
while (running)
{
fetchSw.Restart();
frameIndex++;
long localFrameIndex = frameIndex;
// fetch the session or bones data
List<Task<HttpResponseMessage>> tasks = new List<Task<HttpResponseMessage>>
{
fetchClient.GetAsync($"http://{echoVRIP}:{echoVRPort}/session")
};
if (SparkSettings.instance.fetchBones)
{
tasks.Add(fetchClient.GetAsync($"http://{echoVRIP}:{echoVRPort}/player_bones"));
}
lastFetch = DateTime.UtcNow;
try
{
HttpResponseMessage[] results = await Task.WhenAll(tasks);
if (results[0].IsSuccessStatusCode)
{
string session = await results[0].Content.ReadAsStringAsync();
string bones = null;
if (results.Length > 1 && results[1].IsSuccessStatusCode)
{
bones = await results[1].Content.ReadAsStringAsync();
}
// add this data to the public variable
lock (lastJSONLock)
{
lastJSON = session;
lastBonesJSON = bones;
}
DateTime frameTime = DateTime.UtcNow;
lastDataTime = DateTime.UtcNow;
if (connectionState == ConnectionState.NotConnected)
{
_ = Task.Run(() =>
{
ConnectedToGame?.Invoke(frameTime, session);
});
}
connectionState = ConnectionState.InGame;
// early quit if the program was quit while fetching
if (!running) return;
// tell the processing methods that stuff is available
_ = Task.Run(() =>
{
FrameFetched?.Invoke(frameTime, session, bones);
});
// parse the API data
Frame f = Frame.FromJSON(frameTime, session, bones);
if (f != null)
{
// tell the processing methods that stuff is available
ProcessFrame(f, lastFrame, localFrameIndex);
NewFrame?.Invoke(f);
}
else
{
LogRow(LogType.Error, "Converting to Frame failed. Investigate 🕵");
LeftGame?.Invoke(lastFrame);
}
lock (lastFrameLock)
{
// for the very first frame, copy it to the other previous frames
lastFrame ??= f;
lastLastLastFrame = lastLastFrame;
lastLastFrame = lastFrame;
lastFrame = f;
}
}
else // not a success status code
{
await FetchFail(results);
}
}
catch (TaskCanceledException)
{
await FetchFail(null);
}
catch (HttpRequestException)
{
await FetchFail(null);
}
catch (Exception ex)
{
LogRow(LogType.Error, $"Error in fetch request.\n{ex}");
}
lastConnectionState = connectionState;
// wait for next frame time based on time last frame was actually fetched
int delay = Math.Clamp((int)(StatsIntervalMs - fetchSw.ElapsedMilliseconds - 3), 0, 1000);
if (delay > 0)
{
Thread.Sleep(delay);
}
}
}
private static async Task FetchFail(HttpResponseMessage[] results)
{
// just revert to not connected to be sure. This will be set properly lower down
connectionState = ConnectionState.NotConnected;
if (results != null)
{
string session = await results[0].Content.ReadAsStringAsync();
if (session.Length > 0 && session[0] == '{')
{
Frame f = Frame.FromJSON(DateTime.UtcNow, session, null);
if (f == null)
{
LogRow(LogType.Error, "Error parsing error frame");
return;
}
if (lastConnectionState == ConnectionState.NotConnected)
{
ConnectedToGame?.Invoke(f.recorded_time, session);
}
// check error codes
switch (f.err_code)
{
case -2: // api disabled
connectionState = ConnectionState.NoAPI;
break;
case -6: // lobby
if (lastConnectionState != ConnectionState.InLobby)
{
try
{
JoinedLobby?.Invoke(f);
}
catch (Exception exp)
{
LogRow(LogType.Error, "Error processing action", exp.ToString());
}
}
connectionState = ConnectionState.InLobby;
break;
}
}
else
{
connectionState = ConnectionState.Menu;
// in loading screen, where the response is not json
if (lastConnectionState == ConnectionState.NotConnected)
{
ConnectedToGame?.Invoke(DateTime.UtcNow, session);
}
}
}
else
{
// Not connected to game
if (lastConnectionState != ConnectionState.NotConnected)
{
_ = Task.Run(() => { DisconnectedFromGame?.Invoke(); });
}
}
// left game
if (lastConnectionState == ConnectionState.InGame && lastFrame != null)
{
try
{
_ = Task.Run(() => { LeftGame?.Invoke(lastFrame); });
}
catch (Exception exp)
{
LogRow(LogType.Error, "Error processing action", exp.ToString());
}
}
// make sure this gets set back to nonconnected to send rejoin events
lastConnectionStateEvent = connectionState;
// add this data to the public variable
lock (lastJSONLock)
{
lastJSON = null;
lastBonesJSON = null;
}
// add additional delay to prevent spamming the request when idle
await Task.Delay(1000);
}