-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRaidEventHooks.cs
More file actions
1365 lines (1206 loc) · 52.6 KB
/
RaidEventHooks.cs
File metadata and controls
1365 lines (1206 loc) · 52.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using Comfort.Common;
using EFT;
using Fika.Core.Main.Components;
using Fika.Core.Main.GameMode;
using Fika.Core.Main.Players;
using Fika.Core.Main.Utils;
using Fika.Core.Modding;
using Fika.Core.Modding.Events;
using Fika.Core.Networking;
using Fika.Core.Networking.LiteNetLib;
using UnityEngine;
namespace ZSlayerHeadlessTelemetry;
public class RaidEventHooks
{
private readonly TelemetryReporter _reporter;
private readonly LogStreamService _logStream;
private readonly string _sourceId;
private bool _inRaid;
private string _currentMap = "";
private Coroutine _periodicCoroutine;
private Coroutine _positionCoroutine;
private MonoBehaviour _coroutineHost;
private float _positionIntervalSec = 1.0f; // default 1s, configurable via server
// Cached references from events (singletons may not work on headless)
private CoopGame _cachedGame;
private CoopHandler _cachedCoopHandler;
// System info (collected once, sent with every performance report)
private object _systemInfo;
private TimeSpan _lastCpuTime;
private DateTime _lastCpuCheck = DateTime.UtcNow;
// FPS tracking
private float _fpsMin = float.MaxValue;
private float _fpsMax;
private float _fpsSum;
private int _fpsCount;
// Bot tracking tick counter (report bots every other tick = ~10s)
private int _tickCount;
// Kill counter for raid summary
private int _raidKillCount;
// Error deduplication (keyed by report name)
private readonly Dictionary<string, int> _errorCounts = new();
// Per-player kill tracking (keyed by profileId)
private readonly Dictionary<string, int> _playerKillCounts = new();
private readonly Dictionary<string, (int pmc, int scav, int boss)> _playerKillTypes = new();
// XP tracking (snapshot at raid start, diff at end)
private readonly Dictionary<string, long> _xpSnapshots = new();
// Track registered death handlers to avoid duplicates
private readonly HashSet<int> _registeredDeathHandlers = new();
// Wall clock fallback for raid timer
private DateTime _raidStartWallClock = DateTime.MinValue;
// Snapshot of human players — updated every periodic tick, used at raid end
// (HumanPlayers may be cleared before OnGameEnded fires)
private List<FikaPlayer> _lastKnownHumans = new();
// Inventory snapshots for raid profit tracking (keyed by profileId)
private readonly Dictionary<string, List<(string templateId, int count)>> _inventorySnapshots = new();
// System-wide CPU tracking (P/Invoke delta-based)
private long _lastSysIdle, _lastSysKernel, _lastSysUser;
// Reflection cache for accessing protected Player fields
private static readonly FieldInfo LastAggressorField =
typeof(Player).GetField("LastAggressor", BindingFlags.NonPublic | BindingFlags.Instance);
private static readonly FieldInfo LastDamageInfoField =
typeof(Player).GetField("LastDamageInfo", BindingFlags.NonPublic | BindingFlags.Instance);
public bool IsInRaid => _inRaid;
public RaidEventHooks(TelemetryReporter reporter, LogStreamService logStream, string sourceId)
{
_reporter = reporter;
_logStream = logStream;
_sourceId = sourceId;
}
public void Subscribe()
{
FikaEventDispatcher.SubscribeEvent<FikaGameCreatedEvent>(OnGameCreated);
FikaEventDispatcher.SubscribeEvent<FikaRaidStartedEvent>(OnRaidStarted);
FikaEventDispatcher.SubscribeEvent<FikaGameEndedEvent>(OnGameEnded);
}
public void Unsubscribe()
{
StopPeriodicReporting();
}
private void OnGameCreated(FikaGameCreatedEvent e)
{
try
{
var game = e.Game as CoopGame;
if (game == null) return;
_cachedGame = game;
// Try multiple location sources — Location_0.Id may be null on headless
_currentMap = "";
try { _currentMap = Singleton<GameWorld>.Instance?.LocationId ?? ""; } catch { }
if (string.IsNullOrEmpty(_currentMap))
try { _currentMap = game.Location_0?.Id ?? ""; } catch { }
_inRaid = false;
_raidKillCount = 0;
_playerKillCounts.Clear();
_playerKillTypes.Clear();
_xpSnapshots.Clear();
_inventorySnapshots.Clear();
DamageTracker.Reset();
ResetFpsTracking();
_tickCount = 0;
_registeredDeathHandlers.Clear();
_reporter.Post("raid-state", new
{
sourceId = _sourceId,
status = "loading",
map = _currentMap,
raidTimer = 0,
raidTimeLeft = 0,
timeOfDay = "",
weather = "",
players = new { pmcAlive = 0, pmcDead = 0, scavAlive = 0, total = 0 }
});
Plugin.Log.LogInfo($"[ZSlayerHQ] Game created — map: {_currentMap}");
}
catch (Exception ex)
{
Plugin.Log.LogWarning($"[ZSlayerHQ] OnGameCreated error: {ex.Message}");
}
}
private void OnRaidStarted(FikaRaidStartedEvent e)
{
try
{
_inRaid = true;
_raidStartWallClock = DateTime.UtcNow;
// Cache CoopHandler reference for periodic reports
CoopHandler.TryGetCoopHandler(out _cachedCoopHandler);
// Retry map detection if it was empty at game creation
if (string.IsNullOrEmpty(_currentMap))
{
try { _currentMap = Singleton<GameWorld>.Instance?.LocationId ?? ""; } catch { }
}
// Snapshot XP for all human players at raid start
try
{
if (_cachedCoopHandler != null)
{
foreach (var player in _cachedCoopHandler.HumanPlayers ?? new List<FikaPlayer>())
{
var profileId = player.ProfileId ?? "";
var xp = player.Profile?.Info?.Experience ?? 0;
if (!string.IsNullOrEmpty(profileId))
_xpSnapshots[profileId] = xp;
}
Plugin.Log.LogInfo($"[ZSlayerHQ] XP snapshots taken for {_xpSnapshots.Count} players, map: {_currentMap}");
// Snapshot inventory for raid profit tracking
foreach (var player in _cachedCoopHandler.HumanPlayers ?? new List<FikaPlayer>())
{
try
{
var pid = player.ProfileId ?? "";
if (string.IsNullOrEmpty(pid)) continue;
var items = new List<(string, int)>();
var allItems = player.Profile?.Inventory?.GetPlayerItems((EFT.InventoryLogic.EPlayerItems)2);
if (allItems != null)
{
foreach (var item in allItems)
{
try
{
var tpl = item.TemplateId.ToString();
if (!string.IsNullOrEmpty(tpl))
items.Add((tpl, item.StackObjectsCount));
}
catch { /* skip item */ }
}
}
_inventorySnapshots[pid] = items;
}
catch { /* skip player */ }
}
Plugin.Log.LogInfo($"[ZSlayerHQ] Inventory snapshots taken for {_inventorySnapshots.Count} players");
}
}
catch (Exception xpEx)
{
Plugin.Log.LogWarning($"[ZSlayerHQ] XP snapshot error: {xpEx.Message}");
}
_reporter.Post("raid-state", new
{
sourceId = _sourceId,
status = "in-raid",
map = _currentMap,
raidTimer = 0,
raidTimeLeft = 0,
timeOfDay = "",
weather = "",
players = new { pmcAlive = 0, pmcDead = 0, scavAlive = 0, total = 0 }
});
StartPeriodicReporting();
Plugin.Log.LogInfo("[ZSlayerHQ] Raid started — periodic telemetry active");
}
catch (Exception ex)
{
Plugin.Log.LogWarning($"[ZSlayerHQ] OnRaidStarted error: {ex.Message}");
}
}
private void OnGameEnded(FikaGameEndedEvent e)
{
try
{
_inRaid = false;
StopPeriodicReporting();
Plugin.Log.LogInfo($"[ZSlayerHQ] OnGameEnded fired — exitStatus: {e.ExitStatus}, exitName: {e.ExitName}, map: {_currentMap}, kills: {_raidKillCount}");
SendRaidSummary(e.ExitStatus, e.ExitName);
_reporter.Post("raid-state", new
{
sourceId = _sourceId,
status = "idle",
map = _currentMap,
raidTimer = 0,
raidTimeLeft = 0,
timeOfDay = "",
weather = "",
players = new { pmcAlive = 0, pmcDead = 0, scavAlive = 0, total = 0 }
});
_registeredDeathHandlers.Clear();
_lastKnownHumans.Clear();
Plugin.Log.LogInfo("[ZSlayerHQ] Raid ended — telemetry stopped, summary sent");
}
catch (Exception ex)
{
Plugin.Log.LogWarning($"[ZSlayerHQ] OnGameEnded error: {ex.Message}\n{ex.StackTrace}");
}
}
// ══════════════════════════════════════════════════════════
// Periodic Reporting (coroutine every 5 seconds)
// ══════════════════════════════════════════════════════════
private void StartPeriodicReporting()
{
_coroutineHost = UnityEngine.Object.FindObjectOfType<Plugin>();
if (_coroutineHost == null)
{
var go = new GameObject("ZSlayerTelemetry");
UnityEngine.Object.DontDestroyOnLoad(go);
_coroutineHost = go.AddComponent<CoroutineHelper>();
}
// Fetch configured map refresh rate from server
FetchMapRefreshRate();
_periodicCoroutine = _coroutineHost.StartCoroutine(PeriodicReportLoop());
_positionCoroutine = _coroutineHost.StartCoroutine(PositionReportLoop());
}
private void StopPeriodicReporting()
{
if (_periodicCoroutine != null && _coroutineHost != null)
{
_coroutineHost.StopCoroutine(_periodicCoroutine);
_periodicCoroutine = null;
}
if (_positionCoroutine != null && _coroutineHost != null)
{
_coroutineHost.StopCoroutine(_positionCoroutine);
_positionCoroutine = null;
}
}
private async void FetchMapRefreshRate()
{
try
{
// Ask server for the configured position update interval
// Uses reporter's shared HttpClient — no extra socket allocation
var url = _reporter.BaseUrl + "/map-refresh-rate";
var result = await _reporter.Http.GetStringAsync(url);
var json = Newtonsoft.Json.Linq.JObject.Parse(result);
var rate = (float?)json["intervalSec"] ?? 1.0f;
_positionIntervalSec = Mathf.Clamp(rate, 0.05f, 10f);
Plugin.Log.LogInfo($"[ZSlayerHQ] Map refresh rate: {_positionIntervalSec}s");
}
catch (Exception ex)
{
Plugin.Log.LogWarning($"[ZSlayerHQ] Failed to fetch map refresh rate, using default {_positionIntervalSec}s: {ex.Message}");
}
}
private IEnumerator PeriodicReportLoop()
{
while (_inRaid)
{
yield return new WaitForSeconds(5f);
if (!_inRaid) yield break;
// Each report is isolated so one failure doesn't cascade to the rest
_tickCount++;
try { ReportRaidState(); } catch (Exception ex) { LogReportError("RaidState", ex); }
try { ReportPlayers(); } catch (Exception ex) { LogReportError("Players", ex); }
try { ReportPerformance(); } catch (Exception ex) { LogReportError("Performance", ex); }
if (_tickCount == 1 || _tickCount % 2 == 0)
{
try { ReportBots(); } catch (Exception ex) { LogReportError("Bots", ex); }
try { ReportDamageStats(); } catch (Exception ex) { LogReportError("DamageStats", ex); }
}
try { RegisterDeathHandlers(); } catch (Exception ex) { LogReportError("DeathHandlers", ex); }
// Flush console log buffer (during raid, every 5s)
try
{
var logEntries = _logStream.DrainBuffer();
if (logEntries.Count > 0)
_reporter.Post("console", new { sourceId = _sourceId, entries = logEntries });
}
catch (Exception ex) { LogReportError("Console", ex); }
}
}
private IEnumerator PositionReportLoop()
{
while (_inRaid)
{
yield return new WaitForSeconds(_positionIntervalSec);
if (!_inRaid) yield break;
try
{
ReportPositions();
}
catch (Exception ex)
{
LogReportError("Positions", ex);
}
}
}
// ══════════════════════════════════════════════════════════
// Raid State
// ══════════════════════════════════════════════════════════
private void ReportRaidState()
{
var game = _cachedGame;
if (game == null)
{
// Fallback: try singleton
try { game = Singleton<IFikaGame>.Instance as CoopGame; } catch { }
if (game == null)
{
try { game = Singleton<AbstractGame>.Instance as CoopGame; } catch { }
}
if (game != null) _cachedGame = game;
}
// Player counts
int pmcAlive = 0, pmcDead = 0, totalHumans = 0;
try
{
var coopHandler = _cachedCoopHandler;
if (coopHandler == null) CoopHandler.TryGetCoopHandler(out coopHandler);
if (coopHandler != null)
{
var humans = coopHandler.HumanPlayers ?? new List<FikaPlayer>();
pmcAlive = humans.Count(p => !p.IsAI && p.HealthController?.IsAlive == true);
pmcDead = humans.Count(p => !p.IsAI && p.HealthController?.IsAlive == false);
totalHumans = humans.Count;
if (humans.Count > 0)
_lastKnownHumans = new List<FikaPlayer>(humans);
}
}
catch { /* disposed player — use 0 */ }
// Raid timer
int raidTimer = 0;
int raidTimeLeft = 0;
try
{
if (game?.GameTimer != null)
{
raidTimer = (int)game.GameTimer.PastTime.TotalSeconds;
if (game.GameTimer.SessionTime.HasValue)
raidTimeLeft = Math.Max(0, (int)(game.GameTimer.SessionTime.Value.TotalSeconds - raidTimer));
}
}
catch (Exception ex)
{
Plugin.Log.LogWarning($"[ZSlayerHQ] GameTimer error: {ex.Message}");
}
// Wall-clock fallback — always works even if GameTimer is broken
if (raidTimer == 0 && _raidStartWallClock != DateTime.MinValue)
{
raidTimer = (int)(DateTime.UtcNow - _raidStartWallClock).TotalSeconds;
}
// Time of day
var timeOfDay = "";
try
{
var gameWorld = Singleton<GameWorld>.Instance;
if (gameWorld?.GameDateTime != null)
{
var dt = gameWorld.GameDateTime.Calculate();
timeOfDay = dt.ToString("HH:mm");
}
}
catch { /* ignore */ }
if (string.IsNullOrEmpty(timeOfDay))
{
try
{
var gameWorld = Singleton<GameWorld>.Instance;
if (gameWorld != null)
{
var gdtProp = gameWorld.GetType().GetProperty("GameDateTime");
var gdt = gdtProp?.GetValue(gameWorld);
if (gdt != null)
{
var calcMethod = gdt.GetType().GetMethod("Calculate");
if (calcMethod != null)
{
var result = calcMethod.Invoke(gdt, null);
if (result is DateTime dtResult)
timeOfDay = dtResult.ToString("HH:mm");
}
}
}
}
catch { /* ignore */ }
}
// Always post — never return early without posting
_reporter.Post("raid-state", new
{
sourceId = _sourceId,
status = "in-raid",
map = _currentMap,
raidTimer,
raidTimeLeft,
timeOfDay,
weather = "",
players = new
{
pmcAlive,
pmcDead,
scavAlive = 0,
total = totalHumans
}
});
}
// ══════════════════════════════════════════════════════════
// Player Status
// ══════════════════════════════════════════════════════════
private void ReportPlayers()
{
var coopHandler = _cachedCoopHandler;
if (coopHandler == null && !CoopHandler.TryGetCoopHandler(out coopHandler)) return;
var humans = coopHandler.HumanPlayers;
if (humans == null) return;
// Build ping mapping: match peers to non-local players by connection order
Dictionary<string, int> profilePings = null;
try
{
var server = Singleton<FikaServer>.Instance;
if (server?.NetServer != null)
{
var peerList = new List<LiteNetPeer>();
server.NetServer.GetConnectedPeers(peerList);
if (peerList.Count > 0)
{
var orderedPeers = peerList.OrderBy(p => p.Id).ToList();
var nonLocalPlayers = humans.Where(p => !p.IsYourPlayer).OrderBy(p => p.NetId).ToList();
profilePings = new Dictionary<string, int>();
for (int i = 0; i < Math.Min(orderedPeers.Count, nonLocalPlayers.Count); i++)
{
var pid = nonLocalPlayers[i].ProfileId ?? "";
if (!string.IsNullOrEmpty(pid))
profilePings[pid] = orderedPeers[i].Ping;
}
}
}
}
catch { /* ignore ping lookup failures */ }
var playerList = new List<object>();
foreach (var player in humans)
{
try
{
var health = GetPlayerHealthPercent(player);
int? pingMs = null;
// Host/headless player is local — show 0ms ping
if (player.IsYourPlayer)
{
pingMs = 0;
}
else if (profilePings != null && profilePings.TryGetValue(player.ProfileId ?? "", out var ping))
{
pingMs = ping;
}
playerList.Add(new
{
name = player.Profile?.Nickname ?? "",
profileId = player.ProfileId ?? "",
type = GetPlayerType(player),
side = player.Side.ToString().ToLowerInvariant(),
level = player.Profile?.Info?.Level ?? 0,
alive = player.HealthController?.IsAlive ?? false,
health,
pingMs
});
}
catch { /* skip player on error */ }
}
_reporter.Post("players", new
{
sourceId = _sourceId,
map = _currentMap,
players = playerList
});
}
// ══════════════════════════════════════════════════════════
// Performance (FPS)
// ══════════════════════════════════════════════════════════
private void ReportPerformance()
{
var fps = Mathf.RoundToInt(1f / Time.deltaTime);
UpdateFpsTracking(fps);
// Calculate CPU usage from process time delta
double cpuUsage = 0;
try
{
var proc = Process.GetCurrentProcess();
var now = DateTime.UtcNow;
var cpuTime = proc.TotalProcessorTime;
var elapsed = (now - _lastCpuCheck).TotalMilliseconds;
if (elapsed > 0 && _lastCpuTime.TotalMilliseconds > 0)
{
var cpuDelta = (cpuTime - _lastCpuTime).TotalMilliseconds;
cpuUsage = Math.Round(cpuDelta / elapsed / Environment.ProcessorCount * 100, 1);
cpuUsage = Math.Min(cpuUsage, 100);
}
_lastCpuTime = cpuTime;
_lastCpuCheck = now;
}
catch { /* ignore */ }
// Get memory — try process working set first, fall back to GC
long memoryMb = 0;
try
{
var ws = Process.GetCurrentProcess().WorkingSet64;
memoryMb = ws > 0 ? ws / (1024 * 1024) : GC.GetTotalMemory(false) / (1024 * 1024);
}
catch
{
memoryMb = GC.GetTotalMemory(false) / (1024 * 1024);
}
// Collect system info once
if (_systemInfo == null)
{
_systemInfo = new
{
cpuModel = SystemInfo.processorType ?? "",
cpuCores = SystemInfo.processorCount,
cpuFrequencyMhz = SystemInfo.processorFrequency,
gpuModel = SystemInfo.graphicsDeviceName ?? "",
gpuVramMb = SystemInfo.graphicsMemorySize,
totalRamMb = SystemInfo.systemMemorySize,
os = SystemInfo.operatingSystem ?? ""
};
}
// System-wide CPU (delta-based via GetSystemTimes)
double systemCpuPercent = 0;
try
{
if (GetSystemTimes(out var sysIdle, out var sysKernel, out var sysUser))
{
if (_lastSysKernel > 0 || _lastSysUser > 0)
{
var idleDelta = sysIdle - _lastSysIdle;
var totalDelta = (sysKernel - _lastSysKernel) + (sysUser - _lastSysUser);
if (totalDelta > 0)
systemCpuPercent = Math.Round((1.0 - (double)idleDelta / totalDelta) * 100, 1);
}
_lastSysIdle = sysIdle;
_lastSysKernel = sysKernel;
_lastSysUser = sysUser;
}
}
catch { /* ignore */ }
// System-wide RAM (via GlobalMemoryStatusEx)
long systemRamUsedMb = 0;
try
{
var memStatus = new MEMORYSTATUSEX { dwLength = (uint)Marshal.SizeOf<MEMORYSTATUSEX>() };
if (GlobalMemoryStatusEx(ref memStatus))
systemRamUsedMb = (long)((memStatus.ullTotalPhys - memStatus.ullAvailPhys) / (1024 * 1024));
}
catch { /* ignore */ }
_reporter.Post("performance", new
{
sourceId = _sourceId,
fps,
fpsAvg = _fpsCount > 0 ? Mathf.RoundToInt(_fpsSum / _fpsCount) : fps,
fpsMin = _fpsMin < float.MaxValue ? Mathf.RoundToInt(_fpsMin) : fps,
fpsMax = Mathf.RoundToInt(_fpsMax),
frameTimeMs = Math.Round(Time.deltaTime * 1000f, 1),
memoryMb,
cpuUsage,
systemCpuPercent,
systemRamUsedMb,
systemInfo = _systemInfo
});
}
private void UpdateFpsTracking(float fps)
{
if (fps < _fpsMin) _fpsMin = fps;
if (fps > _fpsMax) _fpsMax = fps;
_fpsSum += fps;
_fpsCount++;
}
private void ResetFpsTracking()
{
_fpsMin = float.MaxValue;
_fpsMax = 0;
_fpsSum = 0;
_fpsCount = 0;
}
// ══════════════════════════════════════════════════════════
// Bot Counts
// ══════════════════════════════════════════════════════════
private void ReportBots()
{
var coopHandler = _cachedCoopHandler;
if (coopHandler == null && !CoopHandler.TryGetCoopHandler(out coopHandler)) return;
var allPlayers = coopHandler.Players;
if (allPlayers == null) return;
int scavsAlive = 0, scavsDead = 0;
int raidersAlive = 0, raidersDead = 0;
int roguesAlive = 0, roguesDead = 0;
int aiPmcsAlive = 0, aiPmcsDead = 0;
var bosses = new List<object>();
foreach (var kvp in allPlayers)
{
var player = kvp.Value;
if (player == null || !player.IsAI) continue;
try
{
var role = player.Profile?.Info?.Settings?.Role ?? WildSpawnType.marksman;
var alive = player.HealthController?.IsAlive ?? false;
// Check if boss
if (LocaleUtils.IsBoss(role, out var bossName))
{
string killedBy = null;
if (!alive)
{
try
{
var aggressor = LastAggressorField?.GetValue(player) as IPlayer;
killedBy = aggressor?.Profile?.Nickname;
}
catch { /* ignore */ }
}
bosses.Add(new { name = bossName, alive, killedBy });
continue;
}
// AI PMCs (bots with USEC/BEAR side — SPT's AI PMC system)
if (player.Side is EPlayerSide.Usec or EPlayerSide.Bear)
{
if (alive) aiPmcsAlive++; else aiPmcsDead++;
continue;
}
// Categorize by role
switch (role)
{
case WildSpawnType.pmcBot:
case WildSpawnType.exUsec:
if (alive) roguesAlive++; else roguesDead++;
break;
case WildSpawnType.arenaFighter:
case WildSpawnType.crazyAssaultEvent:
if (alive) raidersAlive++; else raidersDead++;
break;
case WildSpawnType.assault:
case WildSpawnType.marksman:
case WildSpawnType.cursedAssault:
case WildSpawnType.assaultGroup:
default:
if (alive) scavsAlive++; else scavsDead++;
break;
}
}
catch { /* skip disposed/invalid bot */ }
}
var totalAlive = scavsAlive + raidersAlive + roguesAlive + aiPmcsAlive;
var totalDead = scavsDead + raidersDead + roguesDead + aiPmcsDead;
// Log bot counts for diagnostics (only every 6th tick = ~30s)
if (_tickCount % 6 == 0)
{
var playerCount = allPlayers?.Count ?? 0;
var aiCount = allPlayers?.Values.Count(p => p != null && p.IsAI) ?? 0;
Plugin.Log.LogInfo($"[ZSlayerHQ] Bots: {playerCount} total players, {aiCount} AI, scav={scavsAlive}/{scavsDead} raider={raidersAlive}/{raidersDead} rogue={roguesAlive}/{roguesDead} boss={bosses.Count} totalAI={totalAlive}/{totalDead}");
}
_reporter.Post("bots", new
{
sourceId = _sourceId,
map = _currentMap,
scavs = new { alive = scavsAlive, dead = scavsDead },
raiders = new { alive = raidersAlive, dead = raidersDead },
rogues = new { alive = roguesAlive, dead = roguesDead },
aiPmcs = new { alive = aiPmcsAlive, dead = aiPmcsDead },
bosses,
totalAI = new
{
alive = totalAlive,
dead = totalDead
}
});
}
// ══════════════════════════════════════════════════════════
// Positions (for live minimap)
// ══════════════════════════════════════════════════════════
private void ReportPositions()
{
var coopHandler = _cachedCoopHandler;
if (coopHandler == null && !CoopHandler.TryGetCoopHandler(out coopHandler)) return;
var allPlayers = coopHandler.Players;
if (allPlayers == null) return;
var positions = new List<object>();
foreach (var kvp in allPlayers)
{
var player = kvp.Value;
if (player == null) continue;
try
{
var pos = player.Position;
var rot = player.Rotation;
var alive = player.HealthController?.IsAlive ?? false;
positions.Add(new
{
name = player.Profile?.Nickname ?? "",
profileId = player.ProfileId ?? "",
type = GetPlayerType(player),
x = Math.Round(pos.x, 1),
y = Math.Round(pos.y, 1), // elevation
z = Math.Round(pos.z, 1),
rotation = Math.Round(rot.x, 1), // horizontal facing
alive,
side = player.Side.ToString().ToLowerInvariant()
});
}
catch { /* skip on error */ }
}
_reporter.Post("positions", new
{
sourceId = _sourceId,
map = _currentMap,
positions
});
}
// ══════════════════════════════════════════════════════════
// Damage Stats
// ══════════════════════════════════════════════════════════
private void ReportDamageStats()
{
if (DamageTracker.TotalHits == 0) return;
_reporter.Post("damage-stats", DamageTracker.ToPayload(_sourceId));
}
// ══════════════════════════════════════════════════════════
// Kill Events (registered on players)
// ══════════════════════════════════════════════════════════
private void RegisterDeathHandlers()
{
var coopHandler = _cachedCoopHandler;
if (coopHandler == null && !CoopHandler.TryGetCoopHandler(out coopHandler)) return;
var allPlayers = coopHandler.Players;
if (allPlayers == null) return;
foreach (var kvp in allPlayers)
{
var player = kvp.Value;
if (player == null) continue;
if (_registeredDeathHandlers.Contains(player.NetId)) continue;
_registeredDeathHandlers.Add(player.NetId);
player.OnPlayerDeadOrUnspawn += (deadPlayer) =>
{
try
{
OnPlayerDied(deadPlayer as FikaPlayer);
}
catch (Exception ex)
{
Plugin.Log.LogWarning($"[ZSlayerHQ] Death handler error: {ex.Message}");
}
};
}
}
private void OnPlayerDied(FikaPlayer victim)
{
if (victim == null) return;
_raidKillCount++;
var game = Singleton<IFikaGame>.Instance as CoopGame;
int raidTime = 0;
if (game?.GameTimer != null)
raidTime = (int)game.GameTimer.PastTime.TotalSeconds;
// Get killer info via reflection (protected fields)
IPlayer killerPlayer = null;
string weaponTpl = "";
string ammoTpl = "";
try
{
killerPlayer = LastAggressorField?.GetValue(victim) as IPlayer;
}
catch { /* ignore */ }
try
{
var damageInfoObj = LastDamageInfoField?.GetValue(victim);
if (damageInfoObj is DamageInfoStruct damageInfo)
{
if (damageInfo.Weapon != null)
weaponTpl = damageInfo.Weapon.TemplateId.ToString();
// Get ammo template ID from SourceId
if (!string.IsNullOrEmpty(damageInfo.SourceId))
ammoTpl = damageInfo.SourceId;
}
}
catch { /* ignore */ }
// Use LastDamagedBodyPart (public EBodyPart field) for reliable body part detection
var bodyPartEnum = victim.LastDamagedBodyPart;
var bodyPart = GetBodyPartName(bodyPartEnum);
var isHeadshot = bodyPartEnum == EBodyPart.Head;
// Calculate distance
double distance = 0;
FikaPlayer killerFikaPlayer = killerPlayer as FikaPlayer;
if (killerFikaPlayer != null)
{
try
{
distance = Math.Round(Vector3.Distance(killerFikaPlayer.Position, victim.Position), 1);
}
catch { /* ignore */ }
}
// Fallback: use KillerId (public property) to find killer name
string killerName = killerPlayer?.Profile?.Nickname ?? "";
string killerType = killerFikaPlayer != null ? GetPlayerType(killerFikaPlayer) : "unknown";
int killerLevel = killerPlayer?.Profile?.Info?.Level ?? 0;
if (killerPlayer == null && !string.IsNullOrEmpty(victim.KillerId))
{
// Try to resolve killer from KillerId
var ch = _cachedCoopHandler;
if (ch != null || CoopHandler.TryGetCoopHandler(out ch))
{
foreach (var kvp in ch.Players)
{
if (kvp.Value?.ProfileId == victim.KillerId)
{
killerName = kvp.Value.Profile?.Nickname ?? "";
killerType = GetPlayerType(kvp.Value);
killerLevel = kvp.Value.Profile?.Info?.Level ?? 0;
try { distance = Math.Round(Vector3.Distance(kvp.Value.Position, victim.Position), 1); } catch { }
break;
}
}
}
}
// Track per-player kill counts and types
var killerProfileId = killerPlayer?.ProfileId ?? victim.KillerId ?? "";
if (!string.IsNullOrEmpty(killerProfileId))
{
_playerKillCounts.TryGetValue(killerProfileId, out var count);
_playerKillCounts[killerProfileId] = count + 1;
var victimType = GetPlayerType(victim);
_playerKillTypes.TryGetValue(killerProfileId, out var types);
_playerKillTypes[killerProfileId] = victimType switch
{
"pmc" => (types.pmc + 1, types.scav, types.boss),
"boss" => (types.pmc, types.scav, types.boss + 1),
_ => (types.pmc, types.scav + 1, types.boss) // scav, raider, rogue, follower
};
}
Plugin.Log.LogInfo($"[ZSlayerHQ] Kill: {killerName}({killerType}) → {victim.Profile?.Nickname}({GetPlayerType(victim)}) [{weaponTpl}] body:{bodyPart} dist:{distance}m hs:{isHeadshot}");
_reporter.Post("kill", new
{
sourceId = _sourceId,
timestamp = DateTime.UtcNow,
raidTime,
map = _currentMap,
killer = new
{
name = killerName,
type = killerType,
level = killerLevel
},
victim = new
{
name = victim.Profile?.Nickname ?? "",
type = GetPlayerType(victim),
level = victim.Profile?.Info?.Level ?? 0
},
weapon = weaponTpl,