-
Notifications
You must be signed in to change notification settings - Fork 4
/
GCMonitor.cs
1441 lines (1200 loc) · 51.5 KB
/
GCMonitor.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
/*
The MIT License (MIT)
Copyright (c) 2014 sarbian
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Threading;
using KSP.IO;
using UnityEngine;
using Debug = UnityEngine.Debug;
using Resources = GCMonitor.Properties.Resources;
namespace GCMonitor
{
[KSPAddon(KSPAddon.Startup.Instantly, false)]
public class GCMonitor : MonoBehaviour
{
private const int width = 1024;
private const int height = 512;
const int GraphLabels = 4;
const float labelSpace = 20f * (GraphLabels + 1) / GraphLabels; //fraction because we add Space 1 less time than we draw a Label
private Rect windowPos = new Rect(80, 80, 400, 200);
private Rect windowConfigPos = new Rect(80 + 410, 80, 200, 100);
private Rect fpsPos = new Rect(10, 200, 80, 50);
private bool showUI = false;
private bool showConfUI = false;
private bool hiddenUI = false;
readonly Texture2D memoryTexture = new Texture2D(width, height);
float ratio;
private GUIStyle fpsLabelStyle;
int timeScale = 1;
bool killThread = false;
memoryState[] memoryHistory = new memoryState[width];
int activeSecond = 0;
int previousActiveSecond = 0;
int displayUpToSecond = 0;
int lastDisplayedSecond = 0;
bool fullUpdate = true;
[Persistent]
bool OnlyUpdateWhenDisplayed = true;
[Persistent]
bool memoryGizmo = true;
[Persistent]
bool realMemory = true;
[Persistent]
bool gpuMemory = false;
[Persistent]
bool relative = false;
[Persistent]
bool colorfulMode = false;
[Persistent]
bool useAppLauncher = false;
[Persistent]
double warnPercent = 0.90d;
[Persistent]
double alertPercent = 0.95d;
[Persistent]
int fpsSize = 10;
[Persistent]
bool displayMem = true;
[Persistent]
bool displayMemRss = false;
[Persistent]
bool displayPeakRss = false;
[Persistent]
bool displayGpu = true;
[Persistent]
bool displayFps = true;
[Persistent]
float fpsX = 10;
[Persistent]
float fpsY = 200;
private IButton tbButton;
private ApplicationLauncherButton alButton;
long displayMaxMemory = 200;
long displayMinMemory = 0;
static ulong peakMemory;
long topMemory;
private readonly float updateInterval = 4;
private float dt = 0;
private int frameCount = 0;
private float updateRate;
private float fps;
private string fpsString = string.Empty;
private static Stopwatch watch;
int lastColCount = 0;
Texture2D cat;
Color[] catPixels;
Color[] blackSquare;
Color[] blackLine;
Color[] line;
private static NumberFormatInfo spaceFormat;
Color color = new Color();
struct memoryState
{
public long min;
public long max;
public ulong rss;
public long gc;
public long gpu;
}
struct processMemory
{
public ulong rss;
public ulong vsz;
public ulong max;
public processMemory(ulong rss, ulong vsz, ulong max)
{
this.rss = rss;
this.vsz = vsz;
this.max = max;
}
}
//// Windows x86
//private const string kDllPath_Win_x86 = "GameData/GCMonitor/getRSS_x86.dll";
//[DllImport(dllName: kDllPath_Win_x86, EntryPoint = "getCurrentVM")]
//private static extern UIntPtr getCurrentVM_Win_x86();
//[DllImport(dllName: kDllPath_Win_x86, EntryPoint = "getMaximumVM")]
//private static extern UIntPtr getMaximumVM_Win_x86();
//
//// Windows x64
//private const string kDllPath_Win_x64 = "GameData/GCMonitor/getRSS_x64.dll";
//[DllImport(dllName: kDllPath_Win_x64, EntryPoint = "getCurrentVM")]
//private static extern UIntPtr getCurrentVM_Win_x64();
//[DllImport(dllName: kDllPath_Win_x64, EntryPoint = "getMaximumVM")]
//private static extern UIntPtr getMaximumVM_Win_x64();
[DllImport("psapi.dll")]
private static extern int GetProcessMemoryInfo(IntPtr hProcess, [Out] PROCESS_MEMORY_COUNTERS counters, int size);
[StructLayout(LayoutKind.Sequential)]
private class PROCESS_MEMORY_COUNTERS
{
public uint cb;
public uint PageFaultCount;
public uint PeakWorkingSetSize;
public uint WorkingSetSize;
public uint QuotaPeakPagedPoolUsage;
public uint QuotaPagedPoolUsage;
public uint QuotaPeakNonPagedPoolUsage;
public uint QuotaNonPagedPoolUsage;
public uint PagefileUsage;
public uint PeakPagefileUsage;
}
[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern bool GlobalMemoryStatusEx([In, Out] MEMORYSTATUSEX lpBuffer); // use of [In, Out] is voluntary. see http://www.pinvoke.net/default.aspx/kernel32/GlobalMemoryStatusEx.html
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
private class MEMORYSTATUSEX
{
public uint dwLength;
public uint dwMemoryLoad;
public ulong ullTotalPhys;
public ulong ullAvailPhys;
public ulong ullTotalPageFile;
public ulong ullAvailPageFile;
public ulong ullTotalVirtual;
public ulong ullAvailVirtual;
public ulong ullAvailExtendedVirtual;
public MEMORYSTATUSEX()
{
this.dwLength = (uint)Marshal.SizeOf(typeof(MEMORYSTATUSEX));
}
}
private static MEMORYSTATUSEX msex;
private static PROCESS_MEMORY_COUNTERS pmc;
private static processMemory getProcessMemoryWin()
{
GlobalMemoryStatusEx(msex);
GetProcessMemoryInfo(new IntPtr(-1), pmc, Marshal.SizeOf(typeof(PROCESS_MEMORY_COUNTERS)));
return new processMemory(pmc.WorkingSetSize, msex.ullTotalVirtual - msex.ullAvailVirtual, msex.ullTotalVirtual);
}
// next struct and method from https://github.com/dotnet/corefx/blob/master/src/Common/src/Interop/Linux/procfs/Interop.ProcFsStat.cs
internal struct ParsedStat
{
// Commented out fields are available in the stat data file but
// are currently not used. If/when needed, they can be uncommented,
// and the corresponding entry can be added back to StatParser, replacing
// the MoveNext() with the appropriate ParseNext* call and assignment.
internal int pid;
internal string comm;
internal char state;
//internal int ppid;
//internal int pgrp;
internal int session;
//internal int tty_nr;
//internal int tpgid;
//internal uint flags;
//internal ulong minflt;
//internal ulong cminflt;
//internal ulong majflt;
//internal ulong cmajflt;
internal ulong utime;
internal ulong stime;
//internal long cutime;
//internal long cstime;
//internal long priority;
internal long nice;
//internal long num_threads;
//internal long itrealvalue;
internal ulong starttime;
internal ulong vsize;
internal long rss;
internal ulong rsslim;
//internal ulong startcode;
//internal ulong endcode;
internal ulong startstack;
//internal ulong kstkesp;
//internal ulong kstkeip;
//internal ulong signal;
//internal ulong blocked;
//internal ulong sigignore;
//internal ulong sigcatch;
//internal ulong wchan;
//internal ulong nswap;
//internal ulong cnswap;
//internal int exit_signal;
//internal int processor;
//internal uint rt_priority;
//internal uint policy;
//internal ulong delayacct_blkio_ticks;
//internal ulong guest_time;
//internal long cguest_time;
}
private const string SelfStat = "/proc/self/stat";
private static void ParseStatFile()
{
string statFileContents = System.IO.File.ReadAllText(SelfStat);
var parser = new StringParser(statFileContents, ' ');
linuxStat.pid = parser.ParseNextInt32();
linuxStat.comm = parser.ParseRaw(delegate (string str, ref int startIndex, ref int endIndex)
{
if (str[startIndex] == '(')
{
int i;
for (i = endIndex; i < str.Length && str[i - 1] != ')'; i++) ;
if (str[i - 1] == ')')
{
endIndex = i;
return str.Substring(startIndex + 1, i - startIndex - 2);
}
}
throw new InvalidDataException();
});
linuxStat.state = parser.ParseNextChar();
parser.MoveNextOrFail(); // ppid
parser.MoveNextOrFail(); // pgrp
linuxStat.session = parser.ParseNextInt32();
parser.MoveNextOrFail(); // tty_nr
parser.MoveNextOrFail(); // tpgid
parser.MoveNextOrFail(); // flags
parser.MoveNextOrFail(); // majflt
parser.MoveNextOrFail(); // cmagflt
parser.MoveNextOrFail(); // minflt
parser.MoveNextOrFail(); // cminflt
linuxStat.utime = parser.ParseNextUInt64();
linuxStat.stime = parser.ParseNextUInt64();
parser.MoveNextOrFail(); // cutime
parser.MoveNextOrFail(); // cstime
parser.MoveNextOrFail(); // priority
linuxStat.nice = parser.ParseNextInt64();
parser.MoveNextOrFail(); // num_threads
parser.MoveNextOrFail(); // itrealvalue
linuxStat.starttime = parser.ParseNextUInt64();
linuxStat.vsize = parser.ParseNextUInt64();
linuxStat.rss = parser.ParseNextInt64();
linuxStat.rsslim = parser.ParseNextUInt64();
parser.MoveNextOrFail(); // startcode
parser.MoveNextOrFail(); // endcode
linuxStat.startstack = parser.ParseNextUInt64();
parser.MoveNextOrFail(); // kstkesp
parser.MoveNextOrFail(); // kstkeip
parser.MoveNextOrFail(); // signal
parser.MoveNextOrFail(); // blocked
parser.MoveNextOrFail(); // sigignore
parser.MoveNextOrFail(); // sigcatch
parser.MoveNextOrFail(); // wchan
parser.MoveNextOrFail(); // nswap
parser.MoveNextOrFail(); // cnswap
parser.MoveNextOrFail(); // exit_signal
parser.MoveNextOrFail(); // processor
parser.MoveNextOrFail(); // rt_priority
parser.MoveNextOrFail(); // policy
parser.MoveNextOrFail(); // delayacct_blkio_ticks
parser.MoveNextOrFail(); // guest_time
parser.MoveNextOrFail(); // cguest_time
}
private static ParsedStat linuxStat;
private static processMemory getProcessMemoryLinux()
{
ParseStatFile();
return new processMemory((ulong)linuxStat.rss, linuxStat.vsize, linuxStat.rsslim);
}
// OSX
private struct time_value
{
public int seconds;
public int microseconds;
}
private struct task_basic_info
{
public int suspend_count;
public IntPtr virtual_size;
public IntPtr resident_size;
public time_value user_time;
public time_value system_time;
public int policy;
}
private enum task_flavor_t
{
TASK_BASIC_INFO_32 = 4,
TASK_BASIC_INFO_64 = 5,
}
[DllImport("libc.dylib")]
private static extern IntPtr mach_task_self();
[DllImport("libc.dylib")]
private static extern int task_info(IntPtr task, task_flavor_t flavor, IntPtr taskInfoStructure, ref int structureLength);
private static int structureLengthOSX;
private static task_flavor_t taskFlavorOSX;
private static unsafe processMemory getProcessMemoryOSX()
{
var resultOSX = new task_basic_info();
task_info(mach_task_self(), taskFlavorOSX, new IntPtr(&resultOSX), ref structureLengthOSX);
return new processMemory((ulong)resultOSX.resident_size, (ulong)resultOSX.virtual_size, maxAllowedMem);
}
public static ulong warnMem;
public static ulong alertMem;
public static string memoryVszString;
public static ulong memoryVsz;
public static string memoryRssString;
public static string memoryPeakRssString;
public static string gpuMemoryRssString;
public static ulong memoryRss;
public static ulong maxAllowedMem;
private static processMemory getProcessMemory_unimplemented()
{
return new processMemory(0, 0, 0);
}
private delegate processMemory GetProcessMemory();
private GetProcessMemory getProcessMemory;
internal void Awake()
{
DontDestroyOnLoad(gameObject);
if (File.Exists<GCMonitor>("GCMonitor.cfg"))
{
ConfigNode config = ConfigNode.Load(IOUtils.GetFilePathFor(this.GetType(), "GCMonitor.cfg"));
ConfigNode.LoadObjectFromConfig(this, config);
}
fpsPos.Set(fpsX, fpsY, 200, 50);
updateRate = updateInterval;
line = new Color[height];
blackLine = new Color[height];
for (int i = 0; i < blackLine.Length; i++)
blackLine[i] = Color.black;
cat = new Texture2D(33, 20, TextureFormat.ARGB32, false);
cat.LoadImage(Resources.cat);
catPixels = cat.GetPixels();
blackSquare = new Color[32 * height];
for (int i = 0; i < blackSquare.Length; i++)
blackSquare[i] = Color.black;
spaceFormat = (NumberFormatInfo)CultureInfo.InvariantCulture.NumberFormat.Clone();
spaceFormat.NumberGroupSeparator = " ";
Debug.Log("[GCMonitor] Setting up getRSS delegates");
switch (Application.platform)
{
case RuntimePlatform.LinuxPlayer:
linuxStat = new ParsedStat();
getProcessMemory = getProcessMemoryLinux;
break;
case RuntimePlatform.OSXPlayer:
taskFlavorOSX = IsX64() ? task_flavor_t.TASK_BASIC_INFO_64 : task_flavor_t.TASK_BASIC_INFO_32;
structureLengthOSX = Marshal.SizeOf(typeof(task_basic_info)) / IntPtr.Size;
getProcessMemory = getProcessMemoryOSX;
break;
case RuntimePlatform.WindowsPlayer:
msex = new MEMORYSTATUSEX();
pmc = new PROCESS_MEMORY_COUNTERS();
getProcessMemory = getProcessMemoryWin;
InitGpuMonitor();
break;
default:
getProcessMemory = getProcessMemory_unimplemented;
break;
}
try
{
processMemory p = getProcessMemory();
Debug.Log("[GCMonitor] Delegates OK " + ConvertToMBString(p.vsz) + " / " + ConvertToMBString(p.max));
}
catch (Exception e)
{
Debug.Log("[GCMonitor] Unable to find getRSS implementation\n" + e);
getProcessMemory = getProcessMemory_unimplemented;
}
maxAllowedMem = IsX64() ? (ulong) (SystemInfo.systemMemorySize << 20) : uint.MaxValue;
if (Application.platform == RuntimePlatform.WindowsPlayer && getProcessMemory().max != 0)
{
maxAllowedMem = getProcessMemory().max;
Debug.Log("[GCMonitor] Maximum usable memoryVsz " + ConvertToGBString(maxAllowedMem) + " / " + ConvertToMBString(maxAllowedMem));
}
warnMem = (ulong)(maxAllowedMem * warnPercent);
alertMem = (ulong)(maxAllowedMem * alertPercent);
GameEvents.onShowUI.Add(ShowGUI);
GameEvents.onHideUI.Add(HideGUI);
watch = new Stopwatch();
watch.Start();
// Does not exist on our mono version :(
//GC.RegisterForFullGCNotification(10, 10);
Thread threadGCCollector = new Thread(GCCollector);
threadGCCollector.Start();
}
internal void OnDestroy()
{
killThread = true;
GameEvents.onShowUI.Remove(ShowGUI);
GameEvents.onHideUI.Remove(HideGUI);
ConfigNode node = new ConfigNode("GCMonitor");
ConfigNode.CreateConfigFromObject(this, node);
node.Save(IOUtils.GetFilePathFor(this.GetType(), "GCMonitor.cfg"));
}
private static bool IsX64()
{
return (IntPtr.Size == 8);
}
enum MemState
{
NORMAL,
WARNING,
ALERT1,
ALERT2
}
private bool rmb;
private bool lmb;
private MemState activeMemState;
public void Update()
{
frameCount++;
//dt += Time.timeScale / Time.deltaTime;
dt += Time.deltaTime;
if (dt > 1.0f / updateRate)
{
fps = frameCount / dt;
fpsString = fps.ToString("##0.0") + " FPS";
frameCount = 0;
dt -= 1.0f / updateRate;
}
processMemory memory = getProcessMemory();
memoryVsz = memory.vsz;
memoryVszString = ConvertToMBString(memoryVsz);
memoryRss = memory.rss;
memoryRssString = ConvertToMBString(memoryRss);
memoryPeakRssString = ConvertToMBString(peakMemory);
if (adapter != null)
{
adapter.UpdateValues();
gpuMemoryRssString = ConvertToMBString(adapter.DedicatedVramUsage);
}
lmb = lmb | Input.GetMouseButtonDown(0);
rmb = rmb | Input.GetMouseButtonDown(1);
UpdateButton();
if (GameSettings.MODIFIER_KEY.GetKey() && Input.GetKeyDown(KeyCode.F1))
{
showUI = !showUI;
}
if (GameSettings.MODIFIER_KEY.GetKey() && Input.GetKeyDown(KeyCode.F))
{
memoryGizmo = !memoryGizmo;
}
if (!showUI)
return;
long newdisplayMaxMemory = displayMaxMemory;
long newdisplayMinMemory = displayMinMemory;
if (fullUpdate)
{
newdisplayMaxMemory = newdisplayMinMemory = 0;
}
long maxMemory = 0;
long minMemory = 0;
for (int i = 0; i < memoryHistory.Length; i++)
{
long mem = realMemory ? (long)memoryHistory[i].rss : (gpuMemory ? memoryHistory[i].gpu : memoryHistory[i].max);
if (relative)
{
int index = i != 0 ? (i - 1) : memoryHistory.Length - 1;
long pmem = realMemory ? (long)memoryHistory[index].rss : (gpuMemory ? memoryHistory[index].gpu : memoryHistory[index].max);
mem = pmem == 0 ? 0 : mem - pmem;
}
if (mem > maxMemory)
maxMemory = mem;
if (mem < minMemory)
minMemory = mem;
}
if ((maxMemory * 1.1f) > newdisplayMaxMemory)
{
newdisplayMaxMemory = (long)(maxMemory * 1.2f);
}
if ((minMemory * 1.1f) < newdisplayMinMemory)
{
newdisplayMinMemory = (long)(minMemory * 1.2f);
}
if (relative)
{
newdisplayMaxMemory = Math.Min(Math.Max(newdisplayMaxMemory, -newdisplayMinMemory), 1024 * 1024 * 5);
newdisplayMinMemory = Math.Max(Math.Min(newdisplayMinMemory, -newdisplayMaxMemory), -1024 * 1024 * 5);
}
if (newdisplayMaxMemory != displayMaxMemory || newdisplayMinMemory != displayMinMemory)
{
displayMaxMemory = newdisplayMaxMemory;
displayMinMemory = newdisplayMinMemory;
fullUpdate = true;
}
if (fullUpdate)
{
fullUpdate = false;
ratio = (float)memoryTexture.height / (displayMaxMemory - displayMinMemory);
UpdateTexture(displayUpToSecond);
}
else
{
// To avoid problem with the thread updating
// displayUpToSecond while we're in the while loop
int localdisplayUpToSecond = displayUpToSecond;
if (lastDisplayedSecond != localdisplayUpToSecond)
{
while (lastDisplayedSecond != localdisplayUpToSecond)
{
lastDisplayedSecond = (lastDisplayedSecond + 1) % width;
UpdateTexture(lastDisplayedSecond, localdisplayUpToSecond);
}
memoryTexture.Apply();
}
}
}
private void UpdateButton()
{
MemState state;
if (memoryVsz < warnMem)
{
state = MemState.NORMAL;
}
else if (memoryVsz < alertMem)
{
state = MemState.WARNING;
}
else
{
if (Mathf.FloorToInt(Time.realtimeSinceStartup) % 2 == 0)
{
state = MemState.ALERT1;
}
else
{
state = MemState.ALERT2;
}
}
if (tbButton == null && ToolbarManager.ToolbarAvailable)
{
print("Toolbar config");
tbButton = ToolbarManager.Instance.add("GCMonitor", "GCMonitor");
tbButton.ToolTip = "GCMonitor";
tbButton.TexturePath = "GCMonitor/GCMonitor24N";
tbButton.OnClick += tbButtonClick;
tbButton.Visible = true;
}
if (useAppLauncher && alButton == null && ApplicationLauncher.Ready)
{
print("Launcher config");
Texture2D buttonTexture = GameDatabase.Instance.GetTexture("GCMonitor/GCMonitor38N", false);
alButton = ApplicationLauncher.Instance.AddModApplication(
alButtonClick, alButtonClick,
alHover, alHover,
null, null,
ApplicationLauncher.AppScenes.ALWAYS,
buttonTexture);
}
if (!useAppLauncher && alButton != null)
{
ApplicationLauncher.Instance.RemoveApplication(alButton);
}
if (tbButton != null)
{
tbButton.ToolTip = memoryVszString;
}
if (state == activeMemState)
return;
activeMemState = state;
switch (state)
{
case MemState.NORMAL:
updateLauncher("GCMonitor/GCMonitor38N");
updateToolBar("GCMonitor/GCMonitor24N");
break;
case MemState.WARNING:
updateLauncher("GCMonitor/GCMonitor38W");
updateToolBar("GCMonitor/GCMonitor24W");
break;
case MemState.ALERT1:
updateLauncher("GCMonitor/GCMonitor38A1");
updateToolBar("GCMonitor/GCMonitor24A1");
break;
case MemState.ALERT2:
updateLauncher("GCMonitor/GCMonitor38A2");
updateToolBar("GCMonitor/GCMonitor24A2");
break;
}
}
private void tbButtonClick(ClickEvent e)
{
if (e.MouseButton == 0)
memoryGizmo = !memoryGizmo;
if (e.MouseButton == 1)
showUI = !showUI;
}
private void alHover()
{
lmb = false;
rmb = false;
}
private void alButtonClick()
{
if (lmb)
memoryGizmo = !memoryGizmo;
if (rmb)
showUI = !showUI;
}
private void updateToolBar(string texture)
{
if (tbButton == null)
return;
tbButton.TexturePath = texture;
}
private void updateLauncher(string texture)
{
if (alButton == null)
return;
Texture2D buttonTexture = GameDatabase.Instance.GetTexture(texture, false);
alButton.SetTexture(buttonTexture);
}
public void memoryHistoryUpdate()
{
activeSecond = Mathf.FloorToInt(watch.ElapsedMilliseconds * 0.001f * timeScale) % width;
long mem = GC.GetTotalMemory(false);
if (activeSecond != previousActiveSecond)
{
memoryHistory[activeSecond].min = long.MaxValue;
memoryHistory[activeSecond].max = 0;
memoryHistory[activeSecond].rss = 0;
// GC.MaxGeneration is always 0 on our current mono
// Sum all gen if it ever changes
int colCount = GC.CollectionCount(GC.MaxGeneration);
memoryHistory[previousActiveSecond].gc = colCount - lastColCount;
lastColCount = colCount;
displayUpToSecond = previousActiveSecond;
previousActiveSecond = activeSecond;
}
if (mem < memoryHistory[activeSecond].min)
memoryHistory[activeSecond].min = mem;
if (mem > memoryHistory[activeSecond].max)
memoryHistory[activeSecond].max = mem;
ulong rss = getProcessMemory().vsz;
memoryHistory[activeSecond].rss = rss;
if (rss > peakMemory)
peakMemory = rss;
if (adapter != null)
{
adapter.UpdateValues();
memoryHistory[activeSecond].gpu = adapter.DedicatedVramUsage;
}
}
private void ShowGUI()
{
hiddenUI = false;
}
private void HideGUI()
{
hiddenUI = true;
}
private void GCCollector()
{
while (true)
{
if (!OnlyUpdateWhenDisplayed || showUI)
{
memoryHistoryUpdate();
}
// Removed since those does not work under our mono version :(
// Keep commented in hope we get a mono upgrade after U5
//while (loopThread)
//{
// GCNotificationStatus error = GC.WaitForFullGCApproach();
// if (error == GCNotificationStatus.Succeeded)
// {
// memoryHistoryUpdate();
// }
// else
// {
// break;
// }
//
// error = GC.WaitForFullGCComplete();
// if (error == GCNotificationStatus.Succeeded)
// {
// memoryHistory[activeSecond].gc++;
// memoryHistoryUpdate();
// }
// else
// {
// break;
// }
//}
// Since windows time make this sleep way more I could
// remove it or use 0. Need testing on a slower CPU.
Thread.Sleep(5);
if (killThread)
{
break;
}
}
}
// TODO Convert texture display to GL.quads
// http://docs.unity3d.com/ScriptReference/GL.QUADS.html
// http://docs.unity3d.com/ScriptReference/GL.LoadPixelMatrix.html
private void UpdateTexture(int last)
{
for (int x = 0; x < memoryTexture.width; x++)
{
UpdateTexture(x, last);
}
memoryTexture.Apply();
}
private void UpdateTexture(int x, int last)
{
int min = Mathf.RoundToInt(ratio * (realMemory ? (long)memoryHistory[x].rss : (gpuMemory ? memoryHistory[x].gpu : memoryHistory[x].min)));
int max = Mathf.RoundToInt(ratio * (realMemory ? (long)memoryHistory[x].rss : (gpuMemory ? memoryHistory[x].gpu : memoryHistory[x].max)));
int zero = -Mathf.RoundToInt(ratio * displayMinMemory);
if (relative)
{
int index = x != 0 ? (x - 1) : memoryHistory.Length - 1;
int pmem = Mathf.RoundToInt(ratio * (realMemory ? memoryHistory[index].rss : (gpuMemory ? (ulong)memoryHistory[index].gpu : (ulong)memoryHistory[index].max)));
max = pmem == 0 ? 0 : max - pmem;
max = max + zero;
}
int xPlus1 = (x + 1) % width;
int xPlus2 = (x + 2) % width;
if (!colorfulMode)
{
for (int y = 0; y < memoryTexture.height; y++)
{
if (!relative)
{
if (!(realMemory || gpuMemory) && y < 10 * memoryHistory[x].gc)
color = Color.red;
else if (y <= min && max != 0)
color = Color.grey;
else if (y <= max && max != 0)
color = Color.green;
else
color = Color.black;
}
else
{
if (y < zero && y >= max)
color = Color.green;
else if (y > zero && y <= max)
color = Color.red;
else if (y == zero)
color = Color.grey;
else
color = Color.black;
}
line[y] = color;
}
memoryTexture.SetPixels(x, 0, 1, height, line);
if (x == last)
{
memoryTexture.SetPixels(xPlus1, 0, 1, height, blackLine);
memoryTexture.SetPixels(xPlus2, 0, 1, height, blackLine);
}
}
else
{
memoryTexture.SetPixels(x, 0, cat.width - 1, height, blackSquare);
if (max != 0)
memoryTexture.SetPixels(x, max, cat.width, cat.height, catPixels);
}
}
public void OnGUI()
{
if (memoryGizmo && !hiddenUI)
{
if (fpsLabelStyle == null)
fpsLabelStyle = new GUIStyle(GUI.skin.label);
fpsLabelStyle.fontSize = fpsSize;
Vector2 size = fpsLabelStyle.CalcSize(new GUIContent(memoryVszString));
fpsX = Mathf.Clamp(fpsX, 0, Screen.width);
fpsY = Mathf.Clamp(fpsY, 0, Screen.height);
fpsPos.Set(fpsX, fpsY, 200, size.y);
if (displayMem)
{
DrawOutline(fpsPos, memoryVszString, 1, fpsLabelStyle, Color.black,
memoryVsz > alertMem ? Color.red : memoryVsz > warnMem ? XKCDColors.Orange : Color.white);
fpsPos.Set(fpsPos.xMin, fpsPos.yMin + size.y, 200, size.y);
}
if (displayMemRss)
{
DrawOutline(fpsPos, memoryRssString, 1, fpsLabelStyle, Color.black, Color.white);
fpsPos.Set(fpsPos.xMin, fpsPos.yMin + size.y, 300, size.y);
}
if (displayPeakRss)
{
DrawOutline(fpsPos, memoryPeakRssString, 1, fpsLabelStyle, Color.black, Color.white);
fpsPos.Set(fpsPos.xMin, fpsPos.yMin + size.y, 300, size.y);
}
if (displayGpu)
{
DrawOutline(fpsPos, gpuMemoryRssString, 1, fpsLabelStyle, Color.black, Color.white);
fpsPos.Set(fpsPos.xMin, fpsPos.yMin + size.y, 300, size.y);
}
if (displayFps)
{
DrawOutline(fpsPos, fpsString, 1, fpsLabelStyle, Color.black, Color.white);
}
}
if (showUI && !hiddenUI)