-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSimple.cs
6231 lines (5818 loc) · 191 KB
/
Simple.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 SFML.Graphics;
using SFML.Audio;
using SFML.System;
using SFML.Window;
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Diagnostics;
using System.Globalization;
using System.Threading;
using Newtonsoft.Json;
using System.Drawing.Design;
using System.Collections.Generic;
using TcpClient = NetCoreServer.TcpClient;
using System.Net.Sockets;
using System.Net;
using System.Linq;
using System.Text;
using System.IO;
using NetCoreServer;
/// <summary>
/// A <see cref="Simple"/> way of creating Windows games.<br></br><br></br>
/// A brief introduction of how that's done:<br></br>
/// There are two <see cref="Simple"/> structures of something happening:<br></br>
/// 'When' to happen: <see cref="OverrideMethodExample"/><br></br>
/// 'What' to happen: <see cref="Action"/><br></br>
/// Those <see cref="Simple"/> structures use the following data types:<br></br>
/// <see cref="object"/>, <see cref="object"/>[], <see cref="bool"/>,
/// <see cref="double"/>, <see cref="double"/>[], <see cref="string"/>,
/// <see cref="string"/>[] and <paramref name="enum"/> <br></br><br></br>
/// Overriding a method is like subscribing for an event.<br></br>
/// Each time this event happens - the code inside the overridden method executes.<br></br>
/// Some information about the event is carried inside the method's parameters.<br></br>
/// The code inside the method may contain <see cref="Action"/> methods.<br></br>
/// Further information and examples are provided when hovering over methods and classes.<br></br><br></br>
/// Code example:<br></br>
/// <paramref name="class"/> <typeparamref name="MyGame"/> : <see cref="Simple"/><br></br>
/// {<br></br>
/// <paramref name=" "/><paramref name="static"/> <paramref name="void"/> <typeparamref name="Main"/>() =>
/// <see cref="Game.Running.DoStart"/>; // starting the game<br></br><br></br>
/// <paramref name=" "/><paramref name="public"/> <paramref name="override"/> <paramref name="void"/>
/// <typeparamref name="OnGameProgressChanged"/>(<see cref="Progress"/> <paramref name="progress"/>,
/// <see cref="double"/> <paramref name="runtimeTickCount"/>, <see cref="double"/> <paramref name="totalTickCount"/>)<br></br>
/// <paramref name=" "/>{<br></br>
/// <paramref name=" "/><paramref name="if"/> (<paramref name="progress"/> == <see cref="Progress.Start"/>)<br></br>
/// <paramref name=" "/>{<br></br>
/// <paramref name=" "/><see cref="Console.Log"/>.<typeparamref name="DoMessage"/>("Hello World!");
/// // print "Hello World!" at start<br></br>
/// <paramref name=" "/>}<br></br>
/// <paramref name=" "/><paramref name="else"/> <paramref name="if"/> (<paramref name="progress"/> ==
/// <see cref="Progress.Updating"/>)<br></br>
/// <paramref name=" "/>{<br></br>
/// <paramref name=" "/><see cref="Console.Log"/>.<typeparamref name="DoMessage"/>(<paramref name=
/// "runtimeTickCount"/>); // keep printing the amount of executions of this if statement<br></br>
/// <paramref name=" "/>}<br></br>
/// <paramref name=" "/>}<br></br>
/// }
/// </summary>
public class Simple
{
///<summary>
///text, <paramref name="param"/>, <see cref="char"/>, <typeparamref name="Type"/>
///</summary>
private static void SummaryExample() { }
#region Enums
public enum Direction
{
Up, Down, Left, Right, UpRight, UpLeft, DownRight, DownLeft
}
public enum Motion
{
PerTick, PerSecond
}
public enum Color
{
White, Black,
LightGray, Gray, DarkGray,
LightRed, Red, DarkRed,
LightGreen, Green, DarkGreen,
LightBlue, Blue, DarkBlue,
LightYellow, Yellow, DarkYellow,
LightMagenta, Magenta, DarkMagenta,
LightCyan, Cyan, DarkCyan,
LightOrange, Orange, DarkOrange
}
public enum Progress
{
Start, Updating, End
}
public enum WindowState
{
/// <summary>
/// Same as <see cref="WindowState.Normal"/>
/// </summary>
Unmaximized = 0,
/// <summary>
/// Same as <see cref="WindowState.Unmaximized"/>
/// </summary>
Normal = 0,
Minimized = 1, Maximized = 2
}
public enum RAMUsage
{
Percent, GB
}
public enum KeyboardKey
{
/// <summary>
/// Unhandled key
/// </summary>
Unknown = -1,
A = 0, B = 1, C = 2, D = 3, E = 4, F = 5, G = 6, H = 7, I = 8, J = 9, K = 10, L = 11, M = 12, N = 13, O = 14,
P = 15, Q = 16, R = 17, S = 18, T = 19, U = 20, V = 21, W = 22, X = 23, Y = 24, Z = 25,
Num0 = 26, Num1 = 27, Num2 = 28, Num3 = 29, Num4 = 30, Num5 = 31, Num6 = 32, Num7 = 33, Num8 = 34, Num9 = 35,
Escape = 36, LeftControl = 37, LeftShift = 38, LeftAlt = 39,
/// <summary>
/// The left OS specific key.<br></br><br></br>
/// Windows, Linux: <typeparamref name="window"/><br></br>
/// MacOS X: <typeparamref name="apple"/><br></br>
/// etc.
/// </summary>
LeftSystem = 40,
RightControl = 41, RightShift = 42, RightAlt = 43,
/// <summary>
/// The right OS specific key.<br></br><br></br>
/// Windows, Linux: <typeparamref name="window"/><br></br>
/// MacOS X: <typeparamref name="apple"/><br></br>
/// etc.
/// </summary>
RightSystem = 44, Menu = 45, LeftBracket = 46, RightBracket = 47, Semicolon = 48, Comma = 49, Period = 50,
Dot = 50, Quote = 51, Slash = 52, Backslash = 53, Tilde = 54, Equal = 55, Dash = 56, Space = 57, Enter = 58,
Return = 58, Backspace = 59, Tab = 60, PageUp = 61, PageDown = 62, End = 63, Home = 64, Insert = 65, Delete = 66,
/// <summary>
/// The Num[+] key
/// </summary>
Add = 67,
/// <summary>
/// The Num[-] key
/// </summary>
Minus = 68,
/// <summary>
/// The Num[*] key
/// </summary>
Multiply = 69,
/// <summary>
/// The Num[/] key
/// </summary>
Divide = 70,
LeftArrow = 71, RightArrow = 72, UpArrow = 73, DownArrow = 74, Numpad0 = 75, Numpad1 = 76, Numpad2 = 77,
Numpad3 = 78, Numpad4 = 79, Numpad5 = 80, Numpad6 = 81, Numpad7 = 82, Numpad8 = 83, Numpad9 = 84, F1 = 85,
F2 = 86, F3 = 87, F4 = 88, F5 = 89, F6 = 90, F7 = 91, F8 = 92, F9 = 93, F10 = 94, F11 = 95, F12 = 96, F13 = 97,
F14 = 98, F15 = 99, Pause = 100,
}
public enum KeyboardAction
{
Pressed, Released
}
public enum MouseButton
{
Unknown = -1, Left = 0, Right = 1, Middle = 2, ExtraButton1 = 3, ExtraButton2 = 4
}
public enum MouseWheel
{
Vertical, Horizontal
}
public enum MouseAction
{
CursorMoved, CursorHoveredWindow, CursorUnhoveredWindow
}
public enum MouseButtonAction
{
ButtonClicked, ButtonReleased, ButtonDoubleClicked
}
public enum PopUpIcon
{
None, Info, Error, Warning
}
public enum WindowAction
{
Focused, Unfocused, Resized, Closed
}
public enum AssetType
{
Texture, Font, Sound, Music
}
public enum MessageReceiver
{
Server, AllClients, ServerAndAllClients
}
public enum NumberTimeConvertion
{
MillisecondsToSeconds,
SecondsToMilliseconds, SecondsToMinutes, SecondsToHours,
MinutesToMilliseconds, MinutesToSeconds, MinutesToHours, MinutesToDays,
HoursToSeconds, HoursToMinutes, HoursToDays, HoursToWeeks,
DaysToMinutes, DaysToHours, DaysToWeeks,
WeeksToHours, WeeksToDays
}
public enum NumberLimitation
{
ClosestBound, Overflow
}
public enum NumberRoundToward
{
Closest, Up, Down
}
public enum NumberRoundWhen5
{
TowardEven, AwayFromZero, TowardZero, TowardNegativeInfinity, TowardPositiveInfinity
}
public enum TextStyle
{
Regular, Bold, Italic, Strikethrough, Underline
}
private enum UnitEffect
{
TintRed, TintGreen, TintBlue, Opacity,
Gamma, Desaturation, Inversion, Contrast, Brightness,
Outline, OutlineOffset, OutlineRed, OutlineGreen, OutlineBlue,
Fill, FillRed, FillGreen, FillBlue,
Blink, BlinkSpeed,
Blur, BlurStrengthX, BlurStrengthY,
Earthquake, EarthquakeX, EarthquakeY,
Stretch, StretchX, StretchY, StretchSpeedX, StretchSpeedY,
Water, WaterStrengthX, WaterStrengthY, WaterSpeedX, WaterSpeedY,
Edge, EdgeThreshold, EdgeThickness, EdgeRed, EdgeGreen, EdgeBlue,
Pixelate, PixelateThreshold,
GridX, GridY, GridCellWidth, GridCellHeight, GridCellSpacingX, GridCellSpacingY,
GridRedX, GridRedY, GridGreenX, GridGreenY, GridBlueX, GridBlueY,
WindX, WindY, WindSpeedX, WindSpeedY,
VibrateX, VibrateY,
WaveSinX, WaveSinY, WaveCosX, WaveCosY, WaveSinSpeedX, WaveSinSpeedY, WaveCosSpeedX, WaveCosSpeedY,
MaskRed, MaskGreen, MaskBlue,
}
private enum UnitNumber
{
Depth, LocalAngle, GlobalAngle, LocalScaleWidth, GlobalScaleWidth, LocalScaleHeight, GlobalScaleHeight, LocalX, LocalY,
GlobalX, GlobalY, OriginPercentX, OriginPercentY, ParallaxX, ParallaxY, ParallaxScale, ParallaxAngle,
DisplayPercentX, DisplayPercentY, DisplayPercentWidth, DisplayPercentHeight, RepeatAmountX, RepeatAmountY,
TextStyle, TextOutlineSize, TextOutlineRed, TextOutlineGreen, TextOutlineBlue, TextOutlineOpacity,
TextSpacingLine, TextSpacingSymbol, TextCharacterSize
}
private enum UnitText
{
ID, ParentID, FontPath, Text, TexturePath, MaskTargetID
}
private enum UnitFact
{
Exists, IsHidden, IsDisabled, HasSmoothTexture, MasksIn, IsRepeated
}
private enum UnitTexts
{
AllObjectIDs, ChildrenIDs, MaskIDs
}
private enum CameraNumber
{
X, Y, Angle, Zoom
}
#endregion
#region Run instance
private static Simple game;
private static Form form;
private static RenderWindow window;
private static Clock time, tickDeltaTime, frameDeltaTime;
private static List<string> pickedIDs;
private static string directory, connectToServerInfo, multiplayerMsgSep, multiplayerMsgComponentSep;
private static PerformanceCounter _ramAvailable;
private static PerformanceCounter _ramUsedPercent;
private static PerformanceCounter _cpuPercent;
private static double totalRam, ramAvailable, ramUsedPercent, cpuPercent, serverPort, percentLoaded,
runtimeTickCount, runtimeFrameCount;
private static bool render, clientIsConnected, serverIsRunning, assetLoadBegin, assetLoadUpdate, assetLoadEnd;
private static Dictionary<string, string> clientRealIDs;
private static List<string> clientIDs;
private static Server server;
private static Client client;
private static Thread resourceLoading;
private static List<QueuedAsset> queuedAssets;
private static Dictionary<string, Texture> textures;
private static Dictionary<string, Font> fonts;
private static Dictionary<string, Music> music;
private static Dictionary<string, Sound> sounds;
private static Sprite world, camera;
private static SFML.Graphics.View view;
private class QueuedAsset
{
public string path;
public AssetType asset;
public string error;
}
#endregion
private class Data
{
[JsonProperty]
public bool consoleIsShown, pauseOnWindowUnfocused, renderSuspended, vSync, sleepPrevented, multiplayerLogMessagesToConsole;
[JsonProperty]
public string clientID, ip;
[JsonProperty]
public double frameRateLimit, totalTickCount, totalFrameCount, totalTime;
[JsonProperty]
public SFML.Graphics.Color backgroundColor;
[JsonProperty]
public Dictionary<string, List<object>> storage;
[JsonProperty]
public Dictionary<string, bool> gates, timerPauses, animationReversed;
[JsonProperty]
public Dictionary<string, double> timers, timerDurations, gateEntriesCount, animationTicks;
[JsonProperty]
public Dictionary<string, UnitInstance> objects;
[JsonProperty]
public SortedDictionary<double, List<string>> objectsDepthSorted;
[JsonProperty]
public Dictionary<CameraNumber, double> cameraNumbers;
[JsonProperty]
public List<string> animationIDs;
}
private static Data data;
#region Some complicated shit
#region Sleep Prevention
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern EXECUTION_STATE SetThreadExecutionState(EXECUTION_STATE esFlags);
[Flags]
private enum EXECUTION_STATE : uint
{
ES_AWAYMODE_REQUIRED = 0x00000040,
ES_CONTINUOUS = 0x80000000,
ES_DISPLAY_REQUIRED = 0x00000002,
ES_SYSTEM_REQUIRED = 0x00000001
// Legacy flag, should not be used.
// ES_USER_PRESENT = 0x00000004
}
#endregion
#region Window Maximize/Minimize
[DllImport("SDL2.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern void SDL_MaximizeWindow(IntPtr window);
#endregion
#region Show Console
private static void Form1_Load(object sender, EventArgs e)
{
AllocConsole();
}
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool AllocConsole();
#endregion
#region Select/Edit Mode Console
private enum StdHandle : int
{
STD_INPUT_HANDLE = -10,
STD_OUTPUT_HANDLE = -11,
STD_ERROR_HANDLE = -12,
}
[DllImport("kernel32.dll", SetLastError = true)]
private static extern IntPtr GetStdHandle(int nStdHandle); //returns Handle
public enum ConsoleMode : uint
{
ENABLE_ECHO_INPUT = 0x0004,
ENABLE_EXTENDED_FLAGS = 0x0080,
ENABLE_INSERT_MODE = 0x0020,
ENABLE_LINE_INPUT = 0x0002,
ENABLE_MOUSE_INPUT = 0x0010,
ENABLE_PROCESSED_INPUT = 0x0001,
ENABLE_QUICK_EDIT_MODE = 0x0040,
ENABLE_WINDOW_INPUT = 0x0008,
ENABLE_VIRTUAL_TERMINAL_INPUT = 0x0200,
//screen buffer handle
ENABLE_PROCESSED_OUTPUT = 0x0001,
ENABLE_WRAP_AT_EOL_OUTPUT = 0x0002,
ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004,
DISABLE_NEWLINE_AUTO_RETURN = 0x0008,
ENABLE_LVB_GRID_WORLDWIDE = 0x0010
}
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool GetConsoleMode(IntPtr hConsoleHandle, out uint lpMode);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool SetConsoleMode(IntPtr hConsoleHandle, uint dwMode);
#endregion
#region Total RAM
[DllImport("kernel32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool GetPhysicallyInstalledSystemMemory(out long TotalMemoryInKilobytes);
#endregion
#endregion
#region Events
private static void CreateEvents()
{
window.Closed += new EventHandler(game._Stop);
window.GainedFocus += new EventHandler(game._OnWindowFocused);
window.LostFocus += new EventHandler(game._OnWindowUnfocused);
window.Resized += new EventHandler<SizeEventArgs>(game._OnWindowResized);
window.KeyPressed += new EventHandler<SFML.Window.KeyEventArgs>(game._OnKeyboardKeyPressed);
window.KeyReleased += new EventHandler<SFML.Window.KeyEventArgs>(game._OnKeyboardKeyReleased);
window.SetKeyRepeatEnabled(false);
form.KeyPress += new KeyPressEventHandler(game._OnTextInput);
window.MouseButtonPressed += new EventHandler<MouseButtonEventArgs>(game._OnMouseButtonClicked);
window.MouseButtonReleased += new EventHandler<MouseButtonEventArgs>(game._OnMouseButtonReleased);
form.MouseDoubleClick += new MouseEventHandler(game._OnMouseButtonDoubleClicked);
form.InputLanguageChanged += new InputLanguageChangedEventHandler(game._OnInputLanguageChanged);
window.MouseMoved += new EventHandler<MouseMoveEventArgs>(game._OnMouseMoved);
window.MouseEntered += new EventHandler(game._OnMouseHoveredWindow);
window.MouseLeft += new EventHandler(game._OnMouseUnoveredWindow);
window.MouseWheelScrolled += new EventHandler<MouseWheelScrollEventArgs>(game._OnMouseWheelScrolled);
}
#region Game
private void _Stop(object sender, EventArgs e)
{
Game.Running.DoStop();
}
public virtual void OnGameProgressChanged(Progress progress, double runtimeTickCount, double totalTickCount) { }
public virtual void OnFrameDrawn(double runtimeFrameCount, double totalFrameCount) { }
#endregion
#region Window
public virtual void OnWindowAction(WindowAction action) { }
private void _OnWindowFocused(object sender, EventArgs e)
{
render = true;
OnWindowAction(WindowAction.Focused);
}
private void _OnWindowUnfocused(object sender, EventArgs e)
{
OnWindowAction(WindowAction.Unfocused);
}
private void _OnWindowResized(object sender, EventArgs e)
{
render = true;
OnWindowAction(WindowAction.Resized);
}
#endregion
#region Keyboard
private void _OnKeyboardKeyPressed(object sender, EventArgs e)
{
var keyArgs = (SFML.Window.KeyEventArgs)e;
var key = (KeyboardKey)keyArgs.Code;
OnKeyboardKey(key, KeyboardAction.Pressed);
}
private void _OnKeyboardKeyReleased(object sender, EventArgs e)
{
var keyArgs = (SFML.Window.KeyEventArgs)e;
var key = (KeyboardKey)keyArgs.Code;
OnKeyboardKey(key, KeyboardAction.Released);
}
private void _OnTextInput(object sender, EventArgs e)
{
var keyArgs = (KeyPressEventArgs)e;
var keyStr = keyArgs.KeyChar.ToString();
keyStr = keyStr.Replace('\r', '\n');
if (keyStr == "\b") keyStr = "";
OnKeyboardTextInput(keyStr, keyStr == "\b", keyStr == Environment.NewLine, keyStr == "\t");
}
public virtual void OnKeyboardKey(KeyboardKey key, KeyboardAction action) { }
public virtual void OnKeyboardTextInput(string textSymbol, bool isBackspace, bool isEnter, bool isTab) { }
private void _OnInputLanguageChanged(object sender, EventArgs e)
{
var langArgs = (InputLanguageChangedEventArgs)e;
var culture = langArgs.InputLanguage.Culture;
OnInputLanguageChanged(culture.EnglishName, culture.NativeName, culture.Name);
}
public virtual void OnInputLanguageChanged(string englishName, string nativeName, string languageCode) { }
#endregion
#region Mouse
private void _OnMouseButtonClicked(object sender, EventArgs e)
{
var buttonArgs = (MouseButtonEventArgs)e;
var button = (MouseButton)buttonArgs.Button;
OnMouseButtonAction(button, MouseButtonAction.ButtonClicked);
}
private void _OnMouseButtonReleased(object sender, EventArgs e)
{
var buttonArgs = (MouseButtonEventArgs)e;
var button = (MouseButton)buttonArgs.Button;
OnMouseButtonAction(button, MouseButtonAction.ButtonReleased);
}
private void _OnMouseButtonDoubleClicked(object sender, EventArgs e)
{
var buttonArgs = (MouseEventArgs)e;
var button = MouseButton.Unknown;
switch (buttonArgs.Button)
{
case MouseButtons.Left: button = MouseButton.Left; break;
case MouseButtons.Right: button = MouseButton.Right; break;
case MouseButtons.Middle: button = MouseButton.Middle; break;
case MouseButtons.XButton1: button = MouseButton.ExtraButton1; break;
case MouseButtons.XButton2: button = MouseButton.ExtraButton2; break;
}
OnMouseButtonAction(button, MouseButtonAction.ButtonDoubleClicked);
}
private void _OnMouseMoved(object sender, EventArgs e)
{
OnMouseAction(MouseAction.CursorMoved);
}
private void _OnMouseHoveredWindow(object sender, EventArgs e)
{
OnMouseAction(MouseAction.CursorHoveredWindow);
}
private void _OnMouseUnoveredWindow(object sender, EventArgs e)
{
OnMouseAction(MouseAction.CursorUnhoveredWindow);
}
private void _OnMouseWheelScrolled(object sender, EventArgs e)
{
var arguments = (MouseWheelScrollEventArgs)e;
var wheel = (MouseWheel)arguments.Wheel;
OnMouseWheelScrolled(arguments.Delta == 1 ? Direction.Up : Direction.Down, wheel);
}
public virtual void OnMouseAction(MouseAction action) { }
public virtual void OnMouseButtonAction(MouseButton button, MouseButtonAction action) { }
public virtual void OnMouseWheelScrolled(Direction direction, MouseWheel wheel) { }
#endregion
#region Multiplayer
public virtual void OnMultiplayerMessageReceived(string fromID, string message) { }
public virtual void OnMultiplayerClientConnected(string clientID) { }
public virtual void OnMultiplayerClientDisconnected(string clientID) { }
public virtual void OnMultiplayerConnected() { }
public virtual void OnMultiplayerDisconnected() { }
public virtual void OnMultiplayerTakenID(string newID) { }
#endregion
#region Other
/// <summary>
/// An example of the "When to happen" <see cref="Simple"/> structure.
/// </summary>
public virtual void OverrideMethodExample(object parameter) { }
public virtual void OnTimerOver(string timerID) { }
public virtual void OnAssetLoadingProgressChanged(Progress progress, double percentLoaded) { }
public virtual void OnAnimationTick(string animationID, double tick, bool reversed) { }
#endregion
#endregion
#region Main
private static void CreateWindow()
{
form = new Form();
var w = (int)VideoMode.DesktopMode.Width;
var h = (int)VideoMode.DesktopMode.Height;
form.SetBounds(w, h, w / 2, h / 2);
window = new RenderWindow(form.Handle);
window.SetVisible(true);
window.SetTitle("Simple Game");
}
private static void SetStartDefaults()
{
Game.BackgroundColor.SetToSample(Color.Black);
render = true;
view = new SFML.Graphics.View(new Vector2f(0, 0), new Vector2f(window.Size.X, window.Size.Y));
window.SetView(view);
data.storage = new Dictionary<string, List<object>>();
directory = AppDomain.CurrentDomain.BaseDirectory;
data.gates = new Dictionary<string, bool>();
data.gateEntriesCount = new Dictionary<string, double>();
data.timers = new Dictionary<string, double>();
data.timerDurations = new Dictionary<string, double>();
data.timerPauses = new Dictionary<string, bool>();
data.multiplayerLogMessagesToConsole = true;
data.objects = new Dictionary<string, UnitInstance>();
data.objectsDepthSorted = new SortedDictionary<double, List<string>>();
data.cameraNumbers = new Dictionary<CameraNumber, double>();
data.ip = Multiplayer.Client.Connection.IP.SameDevice.Get();
data.animationReversed = new Dictionary<string, bool>();
data.animationTicks = new Dictionary<string, double>();
data.animationIDs = new List<string>();
pickedIDs = new List<string>();
clientRealIDs = new Dictionary<string, string>();
clientIDs = new List<string>();
queuedAssets = new List<QueuedAsset>();
textures = new Dictionary<string, Texture>();
fonts = new Dictionary<string, Font>();
sounds = new Dictionary<string, Sound>();
music = new Dictionary<string, Music>();
world = new Sprite();
camera = new Sprite();
serverPort = 1234;
multiplayerMsgComponentSep = "j#@%f";
multiplayerMsgSep = "_#!~xc";
}
private static void Run()
{
while (window.IsOpen)
{
Thread.Sleep(1); // calming down the cpu
if (data.pauseOnWindowUnfocused && window.HasFocus() == false) continue; // pause on window focus
render = runtimeFrameCount == 1; // always render the first frame, otherwise reset each frame to false
Application.DoEvents();
window.DispatchEvents();
data.totalTickCount++;
runtimeTickCount++;
data.totalTime += tickDeltaTime.ElapsedTime.AsSeconds();
UpdateTimers();
if (assetLoadBegin) game.OnAssetLoadingProgressChanged(Progress.Start, 0);
assetLoadBegin = false;
if (assetLoadUpdate) game.OnAssetLoadingProgressChanged(Progress.Updating, Asset.Loading.Get());
assetLoadUpdate = false;
if (assetLoadEnd) game.OnAssetLoadingProgressChanged(Progress.End, 100);
assetLoadEnd = false;
game.OnGameProgressChanged(Progress.Updating, runtimeTickCount, data.totalTickCount);
tickDeltaTime.Restart();
// calm down performance counters to avoid wrong values
var picked = pickedIDs.ToArray();
Instance.PickedIDs.Set("performance-counters-gate-key-;;;asflij");
if (Instance.Gate.Opened.DoGet((int)time.ElapsedTime.AsSeconds() % 2 == 0)) UpdatePerformanceCounters();
Instance.PickedIDs.Set(picked);
if (render == false || data.renderSuspended) continue;
data.totalFrameCount++;
runtimeFrameCount++;
frameDeltaTime.Restart();
window.Clear(data.backgroundColor);
Draw();
game.OnFrameDrawn(runtimeFrameCount, data.totalFrameCount);
window.Display();
}
}
private static void Draw()
{
var reversed = data.objectsDepthSorted.Reverse();
foreach (var kvp in reversed)
{
foreach (var obj in kvp.Value)
{
data.objects[obj].Update();
data.objects[obj].Draw();
}
}
}
private static void UpdatePerformanceCounters()
{
ramAvailable = _ramAvailable.NextValue() / 1000;
ramUsedPercent = _ramUsedPercent.NextValue();
cpuPercent = _cpuPercent.NextValue();
}
private static void UpdateTimers()
{
var IDsToPause = new List<string>();
foreach (var kvp in data.timers)
{
if (data.timerPauses[kvp.Key]) continue;
var delta = tickDeltaTime.ElapsedTime.AsSeconds();
data.timers[kvp.Key] -= delta;
if (kvp.Value - delta * 2 <= 0)
{
IDsToPause.Add(kvp.Key);
}
}
foreach (var ID in IDsToPause)
{
data.timers[ID] = data.timerDurations[ID];
if (data.animationIDs.Contains(ID))
{
if (data.animationTicks.ContainsKey(ID) == false) data.animationTicks[ID] = 0;
var reversed = data.animationReversed.ContainsKey(ID) && data.animationReversed[ID];
data.animationTicks[ID] += reversed ? -1 : 1;
game.OnAnimationTick(ID, data.animationTicks[ID], reversed);
continue;
}
data.timerPauses[ID] = true;
game.OnTimerOver(ID);
}
}
#endregion
/// <summary>
/// An example of the <see cref="Simple"/>.<see cref="Action"/> structure.<br></br><br></br>
/// This is one of the two structures in <see cref="Simple"/>. It covers the 'What' and 'How' things should happen in
/// the game.<br></br>
/// To check the other structure that covers 'When' something should happen, hover <see cref="Simple"/> and
/// <see cref="OverrideMethodExample"/>.<br></br><br></br>
/// The <see cref="Action"/> consists of 3 types of methods<br></br>
/// where the 'What' aspect is replaced by <see cref="Action"/> and<br></br>
/// the 'How' aspect is replaced by <see cref="object"/> (can be multiple or optional, see example bellow):<br></br>
/// <see cref="Get"/><br></br>
/// <see cref="Set"/><br></br>
/// <see cref="Do"/><br></br><br></br>
/// <see cref="Action"/> examples in code:<br></br>
/// <paramref name="var"/> <paramref name="cameraZoom"/> = <see cref="Camera.Zoom.Get"/>;
/// <paramref name=" "/>
/// // take the camera zoom as a scale number, default is 1 <br></br>
/// <paramref name="var"/> <paramref name="fps"/> = <see cref="Performance.Frame.Rate"/>.<typeparamref name="Get"/>(averaged:
/// true);<paramref name=" "/> // get the average frames per second since the start<br></br>
/// <see cref="Instance.PickedIDs"/>.<typeparamref name="Set"/>("player", "enemy");
/// <paramref name=" "/>// select some instances by their IDs
/// <br></br>
/// <see cref="Instance.Unit.Appearance.Opacity"/>.<typeparamref name="Set"/>(opacityPercent: 50);
/// // make the selected instances 50% transparent, default is 100% <br></br>
/// <see cref="Game.Running.DoStop"/>;<paramref name=" "/>
/// // stop the game<br></br>
/// <br></br><br></br>
/// Hover <see cref="Simple"/>, <see cref="Get"/>, <see cref="Set"/> and <see cref="Do"/> for more information.
/// </summary>
public static class Action
{
public static object Get(object value) => default;
public static void Set(object value) { }
public static void Do(object value) { }
}
public static class Instance
{
/// <summary>
/// A way to select on which <see cref="Instance"/> to perform <see cref="Action"/> methods on.<br></br><br></br>
/// Make sure picking happens before the <see cref="Action"/> methods.<br></br>
/// Make sure to pick only one ID before <see cref="Action.Get"/> methods.<br></br>
/// Hover <see cref="Action"/> and <see cref="Instance"/> for more information.
/// </summary>
public static class PickedIDs
{
public static void Set(params string[] IDs)
{
pickedIDs.Clear();
if (IDs == null) return;
for (int i = 0; i < IDs.Length; i++)
{
if (IDs[i] == null) continue; // skip null
if (pickedIDs.Contains(IDs[i])) continue; // already picked
pickedIDs.Add(IDs[i]);
}
}
public static string[] Get()
{
return pickedIDs.ToArray();
}
}
public static class Unit
{
public static class Appearance
{
public static class Parallax
{
public static class Position
{
public static void Set(double percentX, double percentY)
{
SetX(percentX);
SetY(percentY);
}
public static void SetX(double percent)
{
if (Statics.NoIDPickedError()) return;
var picked = PickedIDs.Get();
foreach (var objectID in picked)
{
PickedIDs.Set(objectID);
if (ExistanceCheck()) continue;
data.objects[objectID].numbers[UnitNumber.ParallaxX] = percent;
render = true; // TODO validate
}
PickedIDs.Set(picked);
}
public static void SetY(double percent)
{
if (Statics.NoIDPickedError()) return;
var picked = PickedIDs.Get();
foreach (var objectID in picked)
{
PickedIDs.Set(objectID);
if (ExistanceCheck()) continue;
data.objects[objectID].numbers[UnitNumber.ParallaxY] = percent;
render = true; // TODO validate
}
PickedIDs.Set(picked);
}
public static double GetX()
{
return GetNumber(UnitNumber.ParallaxX);
}
public static double GetY()
{
return GetNumber(UnitNumber.ParallaxY);
}
}
public static class Scale
{
public static void Set(double percent)
{
if (Statics.NoIDPickedError()) return;
var picked = PickedIDs.Get();
foreach (var objectID in picked)
{
PickedIDs.Set(objectID);
if (ExistanceCheck()) continue;
data.objects[objectID].numbers[UnitNumber.ParallaxScale] = percent;
render = true; // TODO validate
}
PickedIDs.Set(picked);
}
public static double Get()
{
return GetNumber(UnitNumber.ParallaxScale);
}
}
public static class Angle
{
public static void Set(double percent)
{
if (Statics.NoIDPickedError()) return;
var picked = PickedIDs.Get();
foreach (var objectID in picked)
{
PickedIDs.Set(objectID);
if (ExistanceCheck()) continue;
data.objects[objectID].numbers[UnitNumber.ParallaxAngle] = percent;
render = true; // TODO validate
}
PickedIDs.Set(picked);
}
public static double Get()
{
return GetNumber(UnitNumber.ParallaxAngle);
}
}
}
public static class Mask
{
public static class IDs
{
public static class Target
{
public static void Set(string unitID)
{
if (Statics.NoIDPickedError()) return;
var picked = PickedIDs.Get();
PickedIDs.Set(unitID);
if (Statics.DoesNotExistError(data.objects, "Unit")) return;
foreach (var objectID in picked)
{
PickedIDs.Set(objectID);
if (ExistanceCheck()) continue;
if (data.objects[objectID].textCollections.ContainsKey(UnitTexts.MaskIDs) == false)
{
data.objects[objectID].textCollections.Add(UnitTexts.MaskIDs, new List<string>());
}
data.objects[unitID].shader.SetUniform("has_mask", false);
data.objects[objectID].shader.SetUniform("has_mask", true);
data.objects[objectID].textCollections[UnitTexts.MaskIDs].Add(unitID);
data.objects[unitID].texts[UnitText.MaskTargetID] = objectID;
render = true; // TODO validate
}
PickedIDs.Set(picked);
}
public static string Get()
{
return GetText(UnitText.MaskTargetID);
}
}
public static class Masks
{
public static string[] Get()
{
return GetTexts(UnitTexts.MaskIDs);
}
}
}
public static class Extracted
{
public static void Set(bool extracted)
{
if (Statics.NoIDPickedError()) return;
var picked = PickedIDs.Get();
foreach (var objectID in picked)
{
PickedIDs.Set(objectID);
if (ExistanceCheck()) continue;
data.objects[objectID].facts[UnitFact.MasksIn] = extracted;
data.objects[objectID].shader.SetUniform("mask_out", extracted == false);
Texture.FilePath.Set(Texture.FilePath.Get()); // update the texture to prevent the weird upside-down flipping
}
PickedIDs.Set(picked);
}
public static bool Get()
{
return GetFact(UnitFact.MasksIn) == false;
}
}
public static class Color
{
public static void Set(double percentRed, double percentGreen, double percentBlue)
{
SetRed(percentRed);
SetGreen(percentGreen);
SetBlue(percentBlue);
}
public static void SetToSample(Simple.Color color)
{
var c = Statics.GetColorFromSample(color);
Set(
Number.Converted.To.Percent.Get(c.R, 0, 255),
Number.Converted.To.Percent.Get(c.G, 0, 255),
Number.Converted.To.Percent.Get(c.B, 0, 255));
}
public static void SetRed(double percentRed)
{
SetShaderArg(UnitEffect.MaskRed, "mask_red", percentRed, percentRed, true);
}
public static void SetGreen(double percentGreen)
{
SetShaderArg(UnitEffect.MaskGreen, "mask_green", percentGreen, percentGreen, true);
}
public static void SetBlue(double percentBlue)
{
SetShaderArg(UnitEffect.MaskBlue, "mask_blue", percentBlue, percentBlue, true);
}
public static double GetRed()
{
return GetEffect(UnitEffect.MaskRed);
}
public static double GetGreen()
{
return GetEffect(UnitEffect.MaskGreen);
}
public static double GetBlue()
{
return GetEffect(UnitEffect.MaskBlue);
}
}
}
public static class Opacity
{
public static void Set(double opacityPercent)
{
if (Statics.NoIDPickedError()) return;
opacityPercent = Number.Limited.Get(opacityPercent, 0, 100);
var p255 = Number.Converted.From.Percent.Get(opacityPercent, 0, 255);
var picked = PickedIDs.Get();
foreach (var objectID in picked)
{
PickedIDs.Set(objectID);
if (ExistanceCheck()) continue;
var c = data.objects[objectID].sprite.Color;
data.objects[objectID].sprite.Color = new SFML.Graphics.Color(c.R, c.G, c.B, (byte)p255);
data.objects[objectID].shaderArgs[UnitEffect.Opacity] = opacityPercent;
render = true; // TODO validate
}
PickedIDs.Set(picked);
}
public static double Get()
{
return GetEffect(UnitEffect.Opacity);
}
}
public static class Hidden
{
public static void Set(bool hidden)
{
if (Statics.NoIDPickedError()) return;
var picked = PickedIDs.Get();
foreach (var objectID in picked)
{
PickedIDs.Set(objectID);
if (ExistanceCheck()) continue;
if (Get() == hidden) continue; // same value, skip re-rendering the screen
data.objects[objectID].facts[UnitFact.IsHidden] = hidden;
render = true;
}
PickedIDs.Set(picked);
}