-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMainWindow.xaml.cs
848 lines (751 loc) · 38.8 KB
/
MainWindow.xaml.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
using MeltyHook;
using Microsoft.Win32;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Markup;
using System.Windows.Media.Imaging;
namespace OverlayControl
{
/// <summary>
/// Main window for the OverlayControl application.
/// </summary>
public partial class MainWindow : Window, IComponentConnector
{
#region Properties
public static List<string> CharacterList = new List<string>();
public static string[] CharacterArray = new string[0x64];
public static List<string> Moons = new List<string>() { "Crescent", "Full", "Half", "Null" };
/// <summary>
/// The current match being tracked by OverlayControl and meltyhook.
/// </summary>
public Match CurrentMatch
{
get => _currentMatch;
set
{
_currentMatch = value;
// Disable the Save Current Match context menu item if the current match is null
if (value == null)
mnuSaveCurrentMatch.IsEnabled = false;
// Enable the context menu item if the current match is being defined
else
mnuSaveCurrentMatch.IsEnabled = true;
}
}
#endregion
#region String properties
public string Player1
{
get
{
// Check for sponsor tag
if (txtSponsor1.Text.Trim() == string.Empty)
return txtPlayer1.Text;
else
return txtSponsor1.Text + " | " + txtPlayer1.Text;
}
set => txtPlayer1.Text = value;
}
public string Player2
{
get
{
// Check for sponsor tag
if (txtSponsor2.Text.Trim() == string.Empty)
return txtPlayer2.Text;
else
return txtSponsor2.Text + " | " + txtPlayer2.Text;
}
set => txtPlayer2.Text = value;
}
public string Character1 => cmbMoon1.Text[0].ToString() + "-" + cmbChar1.Text;
public string Character2 => cmbMoon2.Text[0].ToString() + "-" + cmbChar2.Text;
public string Round
{
get
{
// Group Phase
if (Regex.Match(txtRound.Text, @"\d+").Success)
return string.Concat(txtRound.Text.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Where(w => w.Length >= 1 && char.IsLetter(w[0])).Select(w => char.ToUpper(w[0]))) + Regex.Match(txtRound.Text, @"\d+").Value;
// Bracket Phase
else if (Regex.Replace(txtRound.Text, @"\s+", "").EndsWith("s"))
return string.Concat(txtRound.Text.Replace("Semis", "Semi Finals").Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Where(w => w.Length >= 1).Select(w => char.ToUpper(w[0]))) + 's';
else
return string.Concat(txtRound.Text.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Where(w => w.Length >= 1).Select(w => char.ToUpper(w[0])));
}
set => txtRound.Text = value;
}
public string Tournament
{
get => txtTournament.Text;
set => txtTournament.Text = value;
}
#endregion
#region Private variables
private readonly VisualsWindow _visuals = new VisualsWindow(new BitmapImage(new Uri("cutins/Random.png", UriKind.Relative)), new BitmapImage(new Uri("moons/Null.png", UriKind.Relative)),
new BitmapImage(new Uri("cutins/Random.png", UriKind.Relative)), new BitmapImage(new Uri("moons/Null.png", UriKind.Relative)),
new BitmapImage(new Uri("flags/_null.png", UriKind.Relative)), new BitmapImage(new Uri("flags/_null.png", UriKind.Relative)));
private readonly MeltyBlood _hook = new MeltyBlood();
private Match _currentMatch = null;
private readonly Settings _settings = null;
private bool _isLooping = false;
private int _scoreCurrent1 = 0;
private int _scoreCurrent2 = 0;
#endregion
#region Interface
#region Window
/// <summary>
/// Constructor for the application's main window.
/// </summary>
public MainWindow()
{
_settings = Settings.Instance;
InitializeComponent();
// Initialize sources
cmbChar1.ItemsSource = _hook.CharacterNames[2].Where(c => c != null).OrderBy(c => c);
cmbChar2.ItemsSource = _hook.CharacterNames[2].Where(c => c != null).OrderBy(c => c);
cmbMoon1.ItemsSource = (IEnumerable)Moons;
cmbMoon2.ItemsSource = (IEnumerable)Moons;
cmbCountry1.ItemsSource = (Player.Countries[])Enum.GetValues(typeof(Player.Countries));
cmbCountry2.ItemsSource = (Player.Countries[])Enum.GetValues(typeof(Player.Countries));
// Load settings
_settings = Settings.Instance;
_settings.Load("config.xml");
mnuResetScores.IsChecked = _settings.ResetScores;
mnuCatchScoresUp.IsChecked = _settings.CatchScoresUp;
// Mark settings as loaded
_settings.AreLoaded = true;
// Load previously entered information
if (File.Exists("commentary.txt"))
txtCommentary.Text = File.ReadAllText("commentary.txt").Trim();
if (File.Exists("player1.txt"))
txtPlayer1.Text = File.ReadAllText("player1.txt").Trim();
if (File.Exists("player2.txt"))
txtPlayer2.Text = File.ReadAllText("player2.txt").Trim();
if (File.Exists("pronouns1.txt"))
txtPronouns1.Text = File.ReadAllText("pronouns1.txt").Trim();
if (File.Exists("pronouns2.txt"))
txtPronouns2.Text = File.ReadAllText("pronouns2.txt").Trim();
if (File.Exists("round.txt"))
txtRound.Text = File.ReadAllText("round.txt").Trim();
if (File.Exists("score1.txt"))
txtScore1.Text = File.ReadAllText("score1.txt").Trim();
if (File.Exists("score2.txt"))
txtScore2.Text = File.ReadAllText("score2.txt").Trim();
if (File.Exists("sponsor1.txt"))
txtSponsor1.Text = File.ReadAllText("sponsor1.txt").Trim();
if (File.Exists("sponsor2.txt"))
txtSponsor2.Text = File.ReadAllText("sponsor2.txt").Trim();
if (File.Exists("tournament.txt"))
txtTournament.Text = File.ReadAllText("tournament.txt").Trim();
if (File.Exists("player1_grands.txt"))
chkLosersSide1.IsChecked = File.ReadAllText("player1_grands.txt").EndsWith("[L]");
if (File.Exists("player2_grands.txt"))
chkLosersSide2.IsChecked = File.ReadAllText("player2_grands.txt").EndsWith("[L]");
if (File.Exists("matchcount.txt"))
{
string matchCount = File.ReadAllText("matchcount.txt");
txtMatchCount.Text = matchCount.Substring(matchCount.LastIndexOf(' ') + 1);
cmbMatchCount.Text = matchCount.Substring(0, matchCount.LastIndexOf(' '));
}
}
/// <summary>
/// Cancelable event fired when attempting to close the application's main window.
/// </summary>
/// <param name="sender">The control that was used to fire this event.</param>
/// <param name="e">Provides data for the cancelable event.</param>
private void mainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
if (CurrentMatch != null)
{
// Prompt the user to save the current match before closing
MessageBoxResult result = MessageBox.Show("There is a currently active match! Save to timestamps before exiting?",
"Exit OverlayControl", System.Windows.MessageBoxButton.YesNoCancel, System.Windows.MessageBoxImage.Warning);
if (result == MessageBoxResult.Yes)
saveCurrentMatchToFile();
else if (result == MessageBoxResult.Cancel)
{
e.Cancel = true;
return;
}
}
// Shutdown the application completely to close all of its windows
Application.Current.Shutdown();
}
#endregion
#region Buttons
/// <summary>
/// Event fired when button btnShowImages is clicked.
/// </summary>
/// <param name="sender">The button that was pressed to fire this event.</param>
/// <param name="e">Contains state information and event data.</param>
private void btnShowImages_Click(object sender, RoutedEventArgs e)
{
// Update images
if (cmbChar1.Text != "")
_visuals.ChangeSource(new BitmapImage(new Uri("cutins/" + cmbChar1.Text + ".png", UriKind.Relative)), new BitmapImage(new Uri("moons/" + cmbMoon1.Text + ".png", UriKind.Relative)),
new BitmapImage(new Uri("cutins/" + cmbChar2.Text + ".png", UriKind.Relative)), new BitmapImage(new Uri("moons/" + cmbMoon2.Text + ".png", UriKind.Relative)),
new BitmapImage(new Uri("flags/" + cmbCountry1.Text + ".png", UriKind.Relative)), new BitmapImage(new Uri("flags/" + cmbCountry2.Text + ".png", UriKind.Relative)));
// Return if images are already visible
if (_visuals.IsVisible)
return;
_visuals.Show();
}
/// <summary>
/// Event fired when button btnUpdateOverlay is clicked.
/// </summary>
/// <param name="sender">The button that was pressed to fire this event.</param>
/// <param name="e">Contains state information and event data.</param>
private void btnUpdateOverlay_Click(object sender, RoutedEventArgs e)
{
// Update every part of the overlay
File.WriteAllText("./player1.txt", txtPlayer1.Text);
File.WriteAllText("./player2.txt", txtPlayer2.Text);
File.WriteAllText("./player1_grands.txt", (bool)chkLosersSide1.IsChecked ? txtPlayer1.Text + " [L]" : txtPlayer1.Text);
File.WriteAllText("./player2_grands.txt", (bool)chkLosersSide2.IsChecked ? txtPlayer2.Text + " [L]" : txtPlayer2.Text);
File.WriteAllText("./sponsor1.txt", txtSponsor1.Text);
File.WriteAllText("./sponsor2.txt", txtSponsor2.Text);
File.WriteAllText("./pronouns1.txt", txtPronouns1.Text);
File.WriteAllText("./pronouns2.txt", txtPronouns2.Text);
File.WriteAllText("./round.txt", txtRound.Text);
File.WriteAllText("./commentary.txt", txtCommentary.Text);
File.WriteAllText("./tournament.txt", txtTournament.Text);
File.WriteAllText("./matchcount.txt", cmbMatchCount.Text.Trim() + ' ' + txtMatchCount.Text);
updateScores();
updateVisuals();
}
/// <summary>
/// Event fired when button btnSwapPlayers is clicked.
/// </summary>
/// <param name="sender">The button that was pressed to fire this event.</param>
/// <param name="e">Contains state information and event data.</param>
private void btnSwapPlayers_Click(object sender, RoutedEventArgs e)
{
string sponsor = txtSponsor1.Text;
txtSponsor1.Text = txtSponsor2.Text;
txtSponsor2.Text = sponsor;
string name = txtPlayer1.Text;
txtPlayer1.Text = txtPlayer2.Text;
txtPlayer2.Text = name;
object selectedChar = cmbChar1.SelectedItem;
cmbChar1.SelectedItem = cmbChar2.SelectedItem;
cmbChar2.SelectedItem = selectedChar;
object selectedMoon = cmbMoon1.SelectedItem;
cmbMoon1.SelectedItem = cmbMoon2.SelectedItem;
cmbMoon2.SelectedItem = selectedMoon;
string score = txtScore1.Text;
txtScore1.Text = txtScore2.Text;
txtScore2.Text = score;
string pronouns = txtPronouns1.Text;
txtPronouns1.Text = txtPronouns2.Text;
txtPronouns2.Text = pronouns;
object country = cmbCountry1.SelectedItem;
cmbCountry1.SelectedItem = cmbCountry2.SelectedItem;
cmbCountry2.SelectedItem = country;
bool? inLosers = chkLosersSide1.IsChecked;
chkLosersSide1.IsChecked = chkLosersSide2.IsChecked;
chkLosersSide2.IsChecked = inLosers;
}
/// <summary>
/// Event fired when button btnResetScores is clicked.
/// </summary>
/// <param name="sender">The button that was pressed to fire this event.</param>
/// <param name="e">Contains state information and event data.</param>
private void btnResetScores_Click(object sender, RoutedEventArgs e)
{
txtScore1.Text = "0";
txtScore2.Text = "0";
}
/// <summary>
/// Event fired when button btnHookToMBAACC is clicked.
/// </summary>
/// <param name="sender">The button that was pressed to fire this event.</param>
/// <param name="e">Contains state information and event data.</param>
private void btnHookToMBAACC_Click(object sender, RoutedEventArgs e) => hookToMelty();
/// <summary>
/// Event fired when button btnSwitchProcess is clicked.
/// </summary>
/// <param name="sender">The button that was pressed to fire this event.</param>
/// <param name="e">Contains state information and event data.</param>
private void btnSwitchProcess_Click(object sender, RoutedEventArgs e) => _hook.SwapActiveProcess();
#endregion
#region Context menu items
#region Timestamps
/// <summary>
/// Event fired when context menu item mnuSaveCurrentMatch is clicked.
/// </summary>
/// <param name="sender">The control that fired this event.</param>
/// <param name="e">Contains state information and event data.</param>
private void mnuSaveCurrentMatch_Click(object sender, RoutedEventArgs e)
{
if (!saveCurrentMatchToFile())
{
MessageBox.Show("There is no currently active match. Match cannot be saved to file.",
"Error trying to save match", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error);
}
// Set CurrentMatch to null to prevent further tracking of the same match
CurrentMatch = null;
}
/// <summary>
/// Event fired when context menu item mnuFinalizeCurrent is clicked.
/// </summary>
/// <param name="sender">The button that was pressed to fire this event.</param>
/// <param name="e">Contains state information and event data.</param>
private void mnuFinalizeCurrent_Click(object sender, RoutedEventArgs e)
{
// Prompt the user for the relevant timestamp
PromptTimestampDialog prompt = new PromptTimestampDialog();
if (prompt.ShowDialog() == true)
{
// Initialize and open save file dialog
SaveFileDialog saveFileDialog = new SaveFileDialog
{
Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*",
OverwritePrompt = true,
FileName = "timestamps_" + Tournament + "_final.txt"
};
if (saveFileDialog.ShowDialog() == true)
{
// Parse the time and save new file
try
{
finalizeTimestamps(prompt.GivenTime, saveFileDialog.FileName);
}
catch (Exception)
{
MessageBox.Show("The inputted time was not in a valid format. Please double-check the entered time.",
"Error trying to read timestamp", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error);
}
}
}
}
/// <summary>
/// Event fired when context menu item mnuBrowseTimestamps is clicked.
/// </summary>
/// <param name="sender">The button that was pressed to fire this event.</param>
/// <param name="e">Contains state information and event data.</param>
private void mnuBrowseTimestamps_Click(object sender, RoutedEventArgs e)
{
// Initialize file browser
OpenFileDialog openFileDialog = new OpenFileDialog()
{
Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*",
FileName = "timestamps_" + Tournament + ".txt"
};
if (openFileDialog.ShowDialog() == true)
{
// Once a file is selected, prompt the user for the relevant timestamp
PromptTimestampDialog prompt = new PromptTimestampDialog();
if (prompt.ShowDialog() == true)
{
// Initialize and open save file dialog
SaveFileDialog saveFileDialog = new SaveFileDialog
{
Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*",
OverwritePrompt = true,
FileName = "timestamps_" + Tournament + "_final.txt"
};
if (saveFileDialog.ShowDialog() == true)
{
// Parse the time and save new file
try
{
finalizeTimestamps(prompt.GivenTime, openFileDialog.FileName, saveFileDialog.FileName);
}
catch (Exception)
{
MessageBox.Show("The inputted time was not in a valid format. Please double-check the entered time.",
"Error trying to read timestamp", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error);
}
}
}
}
}
#endregion
#region Settings
/// <summary>
/// Event fired when context menu item mnuResetScores is checked.
/// </summary>
/// <param name="sender">The control that fired this event.</param>
/// <param name="e">Contains state information and event data.</param>
private void mnuResetScores_Checked(object sender, RoutedEventArgs e)
{
// Avoid saving settings that were just loaded in
if (_settings.AreLoaded)
_settings.ResetScores = true;
}
/// <summary>
/// Event fired when context menu item mnuResetScores is unchecked.
/// </summary>
/// <param name="sender">The control that fired this event.</param>
/// <param name="e">Contains state information and event data.</param>
private void mnuResetScores_Unchecked(object sender, RoutedEventArgs e)
{
// Avoid saving settings that were just loaded in
if (_settings.AreLoaded)
_settings.ResetScores = false;
}
/// <summary>
/// Event fired when context menu item mnuCatchScoresUp is checked.
/// </summary>
/// <param name="sender">The control that fired this event.</param>
/// <param name="e">Contains state information and event data.</param>
private void mnuCatchScoresUp_Checked(object sender, RoutedEventArgs e)
{
// Avoid saving settings that were just loaded in
if (_settings.AreLoaded)
_settings.CatchScoresUp = true;
}
/// <summary>
/// Event fired when context menu item mnuCatchScoresUp is unchecked.
/// </summary>
/// <param name="sender">The control that fired this event.</param>
/// <param name="e">Contains state information and event data.</param>
private void mnuCatchScoresUp_Unchecked(object sender, RoutedEventArgs e)
{
// Avoid saving settings that were just loaded in
if (_settings.AreLoaded)
_settings.CatchScoresUp = false;
}
#endregion
#endregion
#region Text Boxes
// Only allow numbers in score and match count text boxes
/// <summary>
/// Event fired when a text box that should only contain numbers is typed into.
/// </summary>
/// <param name="sender">The text box that fired this event.</param>
/// <param name="e">Contains state information and event data.</param>
private void txtNumber_PreviewTextInput(object sender, System.Windows.Input.TextCompositionEventArgs e) =>
e.Handled = new Regex("[^0-9]+").IsMatch(e.Text);
/// <summary>
/// Event fired when a text box that should only contain numbers is pasted into.
/// </summary>
/// <param name="sender">The text box that fired this event.</param>
/// <param name="e">Contains state information and event data.</param>
private void txtNumber_Pasting(object sender, DataObjectPastingEventArgs e)
{
// Check if data is a string
if (e.DataObject.GetDataPresent(typeof(string)))
{
// Check if the data string only contains numbers; if not, cancel
if (new Regex("[^0-9]+").IsMatch((string)e.DataObject.GetData(typeof(string))))
e.CancelCommand();
}
// If data is not a string, cancel paste
else
e.CancelCommand();
}
/// <summary>
/// Event fired when a text box that should only contain numbers has data dragged down into it via mouse.
/// </summary>
/// <param name="sender">The text box that fired this event.</param>
/// <param name="e">Contains state information and event data.</param>
private void txtNumber_PreviewDragEnter(object sender, DragEventArgs e)
{
// Check if data is a string
if (e.Data.GetDataPresent(typeof(string)))
{
// Check if the data string only contains numbers; if not, cancel
e.Handled = new Regex("[^0-9]+").IsMatch((string)e.Data.GetData(typeof(string)));
}
// If data is not a string, cancel drag-down
else
e.Handled = true;
}
#endregion
#endregion
#region Logic
/// <summary>
/// Recalculates the timestamps saved in the current tournament's timestamp file, writing them to a new file chosen by the user.
/// </summary>
/// <param name="vodTime">Time inputted by the user, representing the start time of the first match of a tournament.</param>
/// <param name="saveFileName">Save file chosen by the user.</param>
private void finalizeTimestamps(TimeSpan vodTime, string saveFileName) =>
// Call overloaded method with default file name
finalizeTimestamps(vodTime, "./timestamps_" + Tournament + ".txt", saveFileName);
/// <summary>
/// Recalculates the timestamps saved in the user's chosen timestamp file, writing them to a new file chosen by the user.
/// </summary>
/// <param name="vodTime">Time inputted by the user, representing the start time of the first match of a tournament.</param>
/// <param name="openFileName"></param>Timestamp file location chosen by the user.
/// <param name="saveFileName">Save file location chosen by the user.</param>
private void finalizeTimestamps(TimeSpan vodTime, string openFileName, string saveFileName)
{
if (File.Exists(openFileName))
{
// Separate the lines
List<string> lines = File.ReadLines(openFileName).ToList();
string saveFileContents = "";
foreach (string l in lines)
{
if (l.IndexOf(' ') != -1)
{
string oldTime = l.Substring(0, l.IndexOf(' '));
TimeSpan parsedTime;
if (oldTime.Length == 5)
// Add 0 hour marker if necessary
if (TimeSpan.TryParse("0:" + oldTime, CultureInfo.CurrentCulture, out parsedTime))
{
TimeSpan newTime = parsedTime + vodTime;
if (newTime.TotalHours >= 1)
saveFileContents += decimal.Truncate((decimal)newTime.TotalHours).ToString("00") + ":" +
newTime.Minutes.ToString("00") + ":" +
newTime.Seconds.ToString("00") + l.Substring(l.IndexOf(' ')) + "\n";
else
saveFileContents += newTime.ToString(@"mm\:ss") + l.Substring(l.IndexOf(' ')) + "\n";
}
else
// No timestamps found in this line, write it back as is
saveFileContents += l + "\n";
else if (oldTime.Length == 8)
// If hours are already there, parse the time as is
if (TimeSpan.TryParse(oldTime, CultureInfo.CurrentCulture, out parsedTime))
{
TimeSpan newTime = parsedTime + vodTime;
if (newTime.TotalHours >= 1)
saveFileContents += decimal.Truncate((decimal)newTime.TotalHours).ToString("00") + ":" +
newTime.Minutes.ToString("00") + ":" +
newTime.Seconds.ToString("00") + l.Substring(l.IndexOf(' ')) + "\n";
else
saveFileContents += newTime.ToString(@"mm\:ss") + l.Substring(l.IndexOf(' ')) + "\n";
}
else
// No timestamps found in this line, write it back as is
saveFileContents += l + "\n";
}
else
// No timestamps found in this line, write it back as is
saveFileContents += l + "\n";
}
// Save the file
File.WriteAllText(saveFileName, saveFileContents);
}
}
/// <summary>
/// Starts the threads containing OverlayControl's automatic detection of game state by hooking to MBAA.exe.
/// </summary>
private void hookToMelty()
{
// Change to opposite state
_isLooping = !_isLooping;
if (_isLooping)
// Turning the hook loop on
{
bool isFirstLoop = true;
// Initialize intro state
// This variable will be set every frame to the current value found in MBAACC
// Possible values are 2 (during character intros), 1 (pre-round movement) and 0 (during the round proper).
// When it turns to 1, the match has started for timestamp purposes.
int lastIntroState = 2;
// Update button description
btnHookToMBAACC.Content = "Unhook from MBAACC";
// Thread that voids the current stream info when the game closes
Task.Factory.StartNew(() =>
{
while (_isLooping)
{
// Verify if Melty is there
if (!_hook.SearchForMelty())
{
// If no Melty is found, clear the cut-ins and scores
if (!_hook.GetMB())
{
Dispatcher.Invoke(() => cmbChar1.Text = "Random");
Dispatcher.Invoke(() => cmbChar2.Text = "Random");
Dispatcher.Invoke(() => cmbMoon1.Text = "Null");
Dispatcher.Invoke(() => cmbMoon2.Text = "Null");
Dispatcher.Invoke(() => updateVisuals());
_scoreCurrent1 = 0;
_scoreCurrent2 = 0;
}
// If a Melty is found, set the scores visually back to 0
else
{
Dispatcher.Invoke(() => txtScore1.Text = "0");
Dispatcher.Invoke(() => txtScore2.Text = "0");
Dispatcher.Invoke(() => updateScores());
}
}
// Loop every second
System.Threading.Thread.Sleep(1000);
}
});
// Thread that updates character, score and timestamp info
Task.Factory.StartNew(() =>
{
while (_isLooping)
{
// Verify if Melty is there
if (_hook.SearchForMelty())
{
// Read from Melty's memory
bool select1 = _hook.ReadMem((int)MeltyMem.CC_P1_SELECTOR_MODE_ADDR, 1)[0] >= 1;
bool select2 = _hook.ReadMem((int)MeltyMem.CC_P2_SELECTOR_MODE_ADDR, 1)[0] >= 1;
string char1 = _hook.CharacterNames[(Int32)NameType.Short][_hook.ReadMem((int)MeltyMem.CC_P1_CHARACTER_ADDR, 1)[0]];
string char2 = _hook.CharacterNames[(Int32)NameType.Short][_hook.ReadMem((int)MeltyMem.CC_P2_CHARACTER_ADDR, 1)[0]];
string moon1 = Moons[_hook.ReadMem((int)MeltyMem.CC_P1_MOON_SELECTOR_ADDR, 1)[0]];
string moon2 = Moons[_hook.ReadMem((int)MeltyMem.CC_P2_MOON_SELECTOR_ADDR, 1)[0]];
int score1 = _hook.ReadMem((int)MeltyMem.CC_P1_SCORE_ADDR, 1)[0];
int score2 = _hook.ReadMem((int)MeltyMem.CC_P2_SCORE_ADDR, 1)[0];
// Update the cut-ins
if (char1 != null && char1.Length > 1)
Dispatcher.Invoke(() => cmbChar1.Text = char1);
else
Dispatcher.Invoke(() => cmbChar1.Text = "Null");
if (char2 != null && char2.Length > 1)
Dispatcher.Invoke(() => cmbChar2.Text = char2);
else
Dispatcher.Invoke(() => cmbChar2.Text = "Null");
if (moon1 != null && moon1.Length > 1 && select1)
Dispatcher.Invoke(() => cmbMoon1.Text = moon1);
else
Dispatcher.Invoke(() => cmbMoon1.Text = "Null");
if (moon2 != null && moon2.Length > 1 && select2)
Dispatcher.Invoke(() => cmbMoon2.Text = moon2);
else
Dispatcher.Invoke(() => cmbMoon2.Text = "Null");
Dispatcher.Invoke(() => updateVisuals());
// If this is the first loop, make sure the score is caught up to the in-game one
// It can be manually edited after the fact if in-game score is not accurate to the set count
if (isFirstLoop)
{
isFirstLoop = false;
Dispatcher.Invoke(() => txtScore1.Text = score1.ToString());
Dispatcher.Invoke(() => txtScore2.Text = score2.ToString());
Dispatcher.Invoke(() => updateScores());
}
else
{
// Update the scores if necessary
if (score1 > _scoreCurrent1)
{
Dispatcher.Invoke(() => txtScore1.Text = (int.Parse(txtScore1.Text) + 1).ToString());
Dispatcher.Invoke(() => updateScores());
}
if (score2 > _scoreCurrent2)
{
Dispatcher.Invoke(() => txtScore2.Text = (int.Parse(txtScore2.Text) + 1).ToString());
Dispatcher.Invoke(() => updateScores());
}
}
// Update the app's score counter
_scoreCurrent1 = score1;
_scoreCurrent2 = score2;
// Check if a new match is starting
int currentIntroState = _hook.ReadMem((int)MeltyMem.CC_INTRO_STATE_ADDR, 1)[0];
if (lastIntroState != currentIntroState)
{
lastIntroState = currentIntroState;
if (lastIntroState == 1)
Dispatcher.Invoke(new Action(() => manageCurrentMatch()));
}
}
// Run this once per in-game frame
System.Threading.Thread.Sleep(16);
}
});
}
else
// Turning the hook loop off
{
// Update button description
btnHookToMBAACC.Content = "Hook to MBAACC";
}
}
/// <summary>
/// Detects the state of the Match currently held in memory and writes it into the timestamps file if a new match has begun.
/// </summary>
private void manageCurrentMatch()
{
// Check if there is currently a match being tracked
if (CurrentMatch != null)
{
// If we have a new match, save previous match to file
if (CurrentMatch.IsNewMatch(Player1, Player2))
{
saveCurrentMatchToFile();
// Create new match once the previous one is saved
CurrentMatch = new Match(Player1, Player2, Character1, Character2, Round);
}
else
{
// If not, check if either of them changed characters and update match status
if (CurrentMatch.IsReversed(Player1, Player2) == false)
{
if (!CurrentMatch.Characters1.Contains(Character1))
CurrentMatch.Characters1.Add(Character1);
if (!CurrentMatch.Characters2.Contains(Character2))
CurrentMatch.Characters2.Add(Character2);
}
else if (CurrentMatch.IsReversed(Player1, Player2) == true)
{
if (!CurrentMatch.Characters1.Contains(Character2))
CurrentMatch.Characters1.Add(Character2);
if (!CurrentMatch.Characters2.Contains(Character1))
CurrentMatch.Characters2.Add(Character1);
}
}
}
// If previous match is null, go ahead and create new match
else
{
CurrentMatch = new Match(Player1, Player2, Character1, Character2, Round);
}
}
/// <summary>
/// Saves the current active Match to the tournament's timestamps file.
/// </summary>
/// <returns>If the match was successfully saved to the timestamps file.</returns>
private bool saveCurrentMatchToFile()
{
// Check if file exists
if (!File.Exists("./timestamps_" + Tournament + ".txt"))
// If it doesn't, create file and save initial timestamp
File.WriteAllText("./timestamps_" + Tournament + ".txt", CurrentMatch.StartTime.ToBinary().ToString());
try
{
// Get the first match's time
long firstMatchBin = long.Parse(File.ReadLines("./timestamps_" + Tournament + ".txt").First());
DateTime firstMatchTime = DateTime.FromBinary(firstMatchBin);
TimeSpan timestamp = CurrentMatch.StartTime - firstMatchTime;
// Append current match with timestamp relative to first match of the tournament
if (timestamp.TotalHours >= 1)
File.AppendAllText("./timestamps_" + Tournament + ".txt",
"\n" + timestamp.ToString(@"hh\:mm\:ss") + " " + CurrentMatch.ToString());
else
File.AppendAllText("./timestamps_" + Tournament + ".txt",
"\n" + timestamp.ToString(@"mm\:ss") + " " + CurrentMatch.ToString());
return true;
}
// If there was an error, there is no current match. Return false.
catch { return false; }
}
/// <summary>
/// Saves the scores currently entered in the score text boxes to the relevant .txt files.
/// </summary>
private void updateScores()
{
File.WriteAllText("./score1.txt", txtScore1.Text);
File.WriteAllText("./score2.txt", txtScore2.Text);
}
/// <summary>
/// Updates the VisualsWindow window's image sources according to the characters, moon styles and country flags entered into the main window.
/// </summary>
private void updateVisuals()
{
if (cmbChar1.Text != "" && cmbChar2.Text != "")
_visuals.ChangeSource(new BitmapImage(new Uri("cutins/" + cmbChar1.Text + ".png", UriKind.Relative)), new BitmapImage(new Uri("moons/" + cmbMoon1.Text + ".png", UriKind.Relative)),
new BitmapImage(new Uri("cutins/" + cmbChar2.Text + ".png", UriKind.Relative)), new BitmapImage(new Uri("moons/" + cmbMoon2.Text + ".png", UriKind.Relative)),
new BitmapImage(new Uri("flags/" + cmbCountry1.Text + ".png", UriKind.Relative)), new BitmapImage(new Uri("flags/" + cmbCountry2.Text + ".png", UriKind.Relative)));
}
#endregion
}
}