using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using Microsoft.CodeAnalysis; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("0.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace SkyNet { internal static class ClientHiveMind { private static ClientSnapshot _snapshot = ClientSnapshot.CreateInvalid(); public static void ReceiveHeartbeat(ServerSnapshot server) { _snapshot.Server = server; _snapshot.Valid = true; SkyNetTelemetry.Server = server; } public static ClientSnapshot GetSnapshot() { return _snapshot; } public static void SetSnapshot(ClientSnapshot snap) { _snapshot = snap; SkyNetTelemetry.Server = snap.Server; } } internal static class ClientMetricsEngine { private static FieldInfo _fiTotalSent; private static FieldInfo _fiTotalRecv; private static int _lastSent; private static int _lastRecv; private static float _lastTime; public static void Update() { if (Time.deltaTime > 0f) { SkyNetTelemetry.ClientFPS = 1f / Time.deltaTime; SkyNetTelemetry.ClientFrameMs = Time.deltaTime * 1000f; } else { SkyNetTelemetry.ClientFPS = 0f; SkyNetTelemetry.ClientFrameMs = 0f; } SkyNetTelemetry.ClientSendQueue = 0f; SkyNetTelemetry.ClientRecvQueue = 0f; SkyNetTelemetry.BandwidthCapsApplied = false; SkyNetTelemetry.PingMs = 0f; SkyNetTelemetry.LinkQuality = 1f; SkyNetTelemetry.ClientSendRate = 0f; SkyNetTelemetry.ClientRecvRate = 0f; if (LoopbackDetector.IsLoopback()) { return; } ZNet instance = ZNet.instance; ZNetPeer val = ((instance != null) ? instance.GetServerPeer() : null); if (val == null || val.m_socket == null) { return; } ISocket socket = val.m_socket; Type type = ((object)socket).GetType(); if (_fiTotalSent == null) { _fiTotalSent = type.GetField("m_totalSent", BindingFlags.Instance | BindingFlags.NonPublic); } if (_fiTotalRecv == null) { _fiTotalRecv = type.GetField("m_totalRecv", BindingFlags.Instance | BindingFlags.NonPublic); } if (!(_fiTotalSent == null) && !(_fiTotalRecv == null)) { int num = (int)_fiTotalSent.GetValue(socket); int num2 = (int)_fiTotalRecv.GetValue(socket); float time = Time.time; float num3 = time - _lastTime; if (!(num3 <= 0f)) { int num4 = num - _lastSent; int num5 = num2 - _lastRecv; SkyNetTelemetry.ClientSendRate = (float)num4 / num3 / 1024f; SkyNetTelemetry.ClientRecvRate = (float)num5 / num3 / 1024f; _lastSent = num; _lastRecv = num2; _lastTime = time; } } } } internal static class ClientOverlay { [CompilerGenerated] private static class <>O { public static WindowFunction <0>__DrawWindow; } private static bool _visible; private static Rect _windowRect = new Rect(40f, 40f, 620f, 320f); private static GUIStyle _windowStyle; private static GUIStyle _bgStyle; private static GUIStyle _labelStyle; private static GUISkin _skin; private static Vector2 _scroll; private static bool _stylesReady; private static bool _initialized; private static KeyCode _toggleKey = (KeyCode)285; public static void Initialize() { //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) if (IsPlayerReady() && SharedConfig.Hud_Enabled != null && SharedConfig.Hud_ToggleKey != null) { _visible = SharedConfig.Hud_Enabled.Value; _toggleKey = ParseKeyOrDefault(SharedConfig.Hud_ToggleKey.Value, (KeyCode)285); _initialized = true; _stylesReady = false; SharedLogging.Info("HUD", "ClientOverlay initialized (HUD-only)."); } } public static void Update() { //IL_001c: Unknown result type (might be due to invalid IL or missing references) if (IsPlayerReady()) { if (!_initialized) { Initialize(); } if (_initialized && Input.GetKeyDown(_toggleKey)) { _visible = !_visible; SharedLogging.Info("HUD", "HUD visibility toggled: " + (_visible ? "ON" : "OFF")); } } } public static void OnGUI() { //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Expected O, but got Unknown if (!IsPlayerReady()) { return; } if (!_initialized) { Initialize(); } if (_initialized && _visible) { EnsureStyles(); GUI.skin = _skin; Rect windowRect = _windowRect; object obj = <>O.<0>__DrawWindow; if (obj == null) { WindowFunction val = DrawWindow; <>O.<0>__DrawWindow = val; obj = (object)val; } _windowRect = GUI.Window(9981, windowRect, (WindowFunction)obj, "", _windowStyle); } } private static bool IsPlayerReady() { if ((Object)(object)ZNet.instance != (Object)null) { return (Object)(object)Player.m_localPlayer != (Object)null; } return false; } private static void EnsureStyles() { //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Expected O, but got Unknown //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Expected O, but got Unknown //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Expected O, but got Unknown //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Expected O, but got Unknown //IL_0077: Unknown result type (might be due to invalid IL or missing references) //IL_0081: Expected O, but got Unknown //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Expected O, but got Unknown //IL_00a1: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Expected O, but got Unknown //IL_00b6: Unknown result type (might be due to invalid IL or missing references) //IL_00c0: Expected O, but got Unknown //IL_00cb: Unknown result type (might be due to invalid IL or missing references) //IL_00d5: Expected O, but got Unknown //IL_00e0: Unknown result type (might be due to invalid IL or missing references) //IL_00ea: Expected O, but got Unknown //IL_00f5: Unknown result type (might be due to invalid IL or missing references) //IL_00ff: Expected O, but got Unknown //IL_010a: Unknown result type (might be due to invalid IL or missing references) //IL_0114: Expected O, but got Unknown //IL_011f: Unknown result type (might be due to invalid IL or missing references) //IL_0129: Expected O, but got Unknown //IL_0134: Unknown result type (might be due to invalid IL or missing references) //IL_013e: Expected O, but got Unknown //IL_0149: Unknown result type (might be due to invalid IL or missing references) //IL_0153: Expected O, but got Unknown //IL_015e: Unknown result type (might be due to invalid IL or missing references) //IL_0168: Expected O, but got Unknown //IL_0172: Unknown result type (might be due to invalid IL or missing references) //IL_017c: Expected O, but got Unknown //IL_019c: Unknown result type (might be due to invalid IL or missing references) //IL_01b4: Unknown result type (might be due to invalid IL or missing references) //IL_01be: Expected O, but got Unknown //IL_01c7: Unknown result type (might be due to invalid IL or missing references) //IL_01d1: Expected O, but got Unknown //IL_01db: Unknown result type (might be due to invalid IL or missing references) //IL_01e5: Expected O, but got Unknown //IL_0205: Unknown result type (might be due to invalid IL or missing references) //IL_021e: Unknown result type (might be due to invalid IL or missing references) //IL_0223: Unknown result type (might be due to invalid IL or missing references) //IL_022b: Unknown result type (might be due to invalid IL or missing references) //IL_0237: Expected O, but got Unknown //IL_0241: Unknown result type (might be due to invalid IL or missing references) if (!_stylesReady) { _skin = ScriptableObject.CreateInstance(); GUISkin skin = GUI.skin; _skin.box = new GUIStyle(skin.box); _skin.label = new GUIStyle(skin.label); _skin.window = new GUIStyle(skin.window); _skin.button = new GUIStyle(skin.button); _skin.textField = new GUIStyle(skin.textField); _skin.textArea = new GUIStyle(skin.textArea); _skin.toggle = new GUIStyle(skin.toggle); _skin.horizontalSlider = new GUIStyle(skin.horizontalSlider); _skin.horizontalSliderThumb = new GUIStyle(skin.horizontalSliderThumb); _skin.verticalSlider = new GUIStyle(skin.verticalSlider); _skin.verticalSliderThumb = new GUIStyle(skin.verticalSliderThumb); _skin.horizontalScrollbar = new GUIStyle(skin.horizontalScrollbar); _skin.horizontalScrollbarThumb = new GUIStyle(skin.horizontalScrollbarThumb); _skin.verticalScrollbar = new GUIStyle(skin.verticalScrollbar); _skin.verticalScrollbarThumb = new GUIStyle(skin.verticalScrollbarThumb); _skin.scrollView = new GUIStyle(skin.scrollView); _windowStyle = new GUIStyle(_skin.window); _windowStyle.normal.background = MakeTex(2, 2, new Color(0f, 0f, 0f, 0f)); _windowStyle.border = new RectOffset(0, 0, 0, 0); _windowStyle.padding = new RectOffset(6, 6, 6, 6); _bgStyle = new GUIStyle(_skin.box); _bgStyle.normal.background = MakeTex(2, 2, new Color(0f, 0f, 0f, 0.7f)); _labelStyle = new GUIStyle(_skin.label) { fontSize = 14, richText = true }; _labelStyle.normal.textColor = Color.white; _skin.window = _windowStyle; _skin.box = _bgStyle; _skin.label = _labelStyle; _stylesReady = true; } } private static void DrawWindow(int id) { //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Unknown result type (might be due to invalid IL or missing references) GUI.Box(new Rect(0f, 0f, ((Rect)(ref _windowRect)).width, ((Rect)(ref _windowRect)).height), GUIContent.none, _bgStyle); ServerSnapshot server = SkyNetTelemetry.Server; GUILayout.BeginVertical(Array.Empty()); _scroll = GUILayout.BeginScrollView(_scroll, Array.Empty()); if (string.IsNullOrEmpty(server.Version) || !(server.Version != "unknown")) { GUILayout.Label("WAITING FOR SERVER TELEMETRY…", _labelStyle, Array.Empty()); GUILayout.EndScrollView(); GUILayout.EndVertical(); GUI.DragWindow(); return; } if (LoopbackDetector.IsLoopback()) { GUILayout.Label("LOOPBACK MODE DETECTED", _labelStyle, Array.Empty()); GUILayout.Label("Server metrics unavailable.", _labelStyle, Array.Empty()); GUILayout.Label("Use LAN IP for full telemetry.", _labelStyle, Array.Empty()); GUILayout.Space(10f); } GUILayout.BeginHorizontal(Array.Empty()); GUILayout.BeginVertical((GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(((Rect)(ref _windowRect)).width / 2f - 10f) }); GUILayout.Label("SERVER", _labelStyle, Array.Empty()); WriteLine("Mode: " + server.Mode + ""); WriteLine($"Tick: {server.TickMs:F1} ms"); WriteLine($"Drift: {server.DriftMs:F1} ms"); WriteLine($"Queue: {server.Queue}"); WriteLine($"Churn: {server.ChurnPerSec}/s"); WriteLine($"Zones: {server.ZonesPerSec}/s"); WriteLine($"Out: {server.OutRateKbps:F1} KB/s"); WriteLine($"In: {server.InRateKbps:F1} KB/s"); GUILayout.EndVertical(); GUILayout.BeginVertical((GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(((Rect)(ref _windowRect)).width / 2f - 10f) }); GUILayout.Label("CLIENT", _labelStyle, Array.Empty()); WriteLine($"FPS: {SkyNetTelemetry.ClientFPS:F0}"); WriteLine($"Frame: {SkyNetTelemetry.ClientFrameMs:F1} ms"); WriteLine($"SendQ: {SkyNetTelemetry.ClientSendQueue:F0}"); WriteLine($"RecvQ: {SkyNetTelemetry.ClientRecvQueue:F0}"); WriteLine($"Send: {SkyNetTelemetry.ClientSendRate:F1} KB/s"); WriteLine($"Recv: {SkyNetTelemetry.ClientRecvRate:F1} KB/s"); WriteLine("BW Caps: " + (SkyNetTelemetry.BandwidthCapsApplied ? "APPLIED" : "NO")); GUILayout.EndVertical(); GUILayout.EndHorizontal(); GUILayout.EndScrollView(); GUILayout.EndVertical(); GUI.DragWindow(); } private static void WriteLine(string text) { GUILayout.Label(text, _labelStyle, Array.Empty()); } private static Texture2D MakeTex(int w, int h, Color c) { //IL_0004: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Expected O, but got Unknown //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Unknown result type (might be due to invalid IL or missing references) Texture2D val = new Texture2D(w, h, (TextureFormat)4, false); Color[] array = (Color[])(object)new Color[w * h]; for (int i = 0; i < array.Length; i++) { array[i] = c; } val.SetPixels(array); val.Apply(); return val; } private static KeyCode ParseKeyOrDefault(string value, KeyCode fallback) { //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) if (string.IsNullOrWhiteSpace(value)) { return fallback; } try { return (KeyCode)Enum.Parse(typeof(KeyCode), value, ignoreCase: true); } catch { return fallback; } } } internal class ClientOverlayHost : MonoBehaviour { private void Update() { ClientOverlay.Update(); } private void OnGUI() { ClientOverlay.OnGUI(); } } internal static class SkyNetTelemetry { public static ServerSnapshot Server; public static float ClientFPS; public static float ClientFrameMs; public static float ClientSendQueue; public static float ClientRecvQueue; public static bool BandwidthCapsApplied; public static float PingMs; public static float LinkQuality; public static float ClientSendRate; public static float ClientRecvRate; } [BepInPlugin("wubarrk.skynet", "SkyNet", "1.0.0")] public class SkyNetPlugin : BaseUnityPlugin { private bool _initializedServer; private bool _initializedClient; private void Awake() { SharedLogging.Initialize(((BaseUnityPlugin)this).Logger); SharedConfig.Initialize(((BaseUnityPlugin)this).Config); ((BaseUnityPlugin)this).Logger.LogInfo((object)("[SkyNet] Awake() entered — assembly: " + typeof(SkyNetPlugin).Assembly.FullName)); SharedLogging.Ritual("SkyNet awakening sequence initiated."); if (Application.isBatchMode) { ((BaseUnityPlugin)this).Logger.LogInfo((object)"[SkyNet] Detected batch mode — treating as dedicated server."); TryInitializeServer(); } else { ((BaseUnityPlugin)this).Logger.LogInfo((object)"[SkyNet] Detected non‑batch mode — treating as client."); TryInitializeClient(); } } private void TryInitializeServer() { try { InitializeServer(); _initializedServer = true; ((BaseUnityPlugin)this).Logger.LogInfo((object)"[SkyNet] Server initialization completed."); } catch (Exception ex) { _initializedServer = false; ((BaseUnityPlugin)this).Logger.LogError((object)("[SkyNet] InitializeServer FAILED: " + ex)); SharedLogging.Warn("SERVER", $"InitializeServer FAILED: {ex}"); } } private void TryInitializeClient() { try { InitializeClient(); _initializedClient = true; ((BaseUnityPlugin)this).Logger.LogInfo((object)"[SkyNet] Client initialization completed."); } catch (Exception ex) { _initializedClient = false; ((BaseUnityPlugin)this).Logger.LogError((object)("[SkyNet] InitializeClient FAILED: " + ex)); SharedLogging.Warn("CLIENT", $"InitializeClient FAILED: {ex}"); } } private void InitializeServer() { ((BaseUnityPlugin)this).Logger.LogInfo((object)"[SkyNet] InitializeServer() starting."); Safe("SharedReflectionCache.Build", delegate { SharedReflectionCache.Build(); }); Safe("SharedRPC.RegisterServerRPC", delegate { SharedRPC.RegisterServerRPC(); }); Safe("ServerMetricsEngine.Initialize", delegate { ServerMetricsEngine.Initialize(); }); Safe("ServerLogicEngine.Initialize", delegate { ServerLogicEngine.Initialize(); }); Safe("ServerZDOThrottle.Initialize", delegate { ServerZDOThrottle.Initialize(); }); Safe("ServerAILoadBalancer.Initialize", delegate { ServerAILoadBalancer.Initialize(); }); Safe("ServerZoneWarmup.Initialize", delegate { ServerZoneWarmup.Initialize(); }); Safe("ServerHeartbeat.Initialize", delegate { ServerHeartbeat.Initialize(); }); Safe("ServerEnvironmentEngine.Initialize", delegate { ServerEnvironmentEngine.Initialize(); }); Safe("SkyNetBootSequence.Run", delegate { SkyNetBootSequence.MetricsInit = true; SkyNetBootSequence.LogicInit = true; SkyNetBootSequence.ZDOThrottleInit = true; SkyNetBootSequence.AIInit = true; SkyNetBootSequence.ZoneWarmupInit = true; SkyNetBootSequence.HeartbeatInit = true; SkyNetBootSequence.EnvironmentInit = true; SkyNetBootSequence.Run((BaseUnityPlugin)(object)this, isServer: true); }); ((BaseUnityPlugin)this).Logger.LogInfo((object)"[SkyNet] InitializeServer() finished."); void Safe(string name, Action a) { try { a(); ((BaseUnityPlugin)this).Logger.LogInfo((object)("[SkyNet] OK: " + name)); } catch (Exception arg) { ((BaseUnityPlugin)this).Logger.LogError((object)$"[SkyNet] FAIL in {name}: {arg}"); } } } private void InitializeClient() { //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Expected O, but got Unknown SharedLogging.Info("CLIENT", "Client role confirmed. Engaging client subsystems."); try { ZNet instance = ZNet.instance; if ((Object)(object)instance != (Object)null) { ZRpc serverRPC = instance.GetServerRPC(); if (serverRPC != null) { SharedRPC.RegisterClientRPC(serverRPC); SharedLogging.Info("CLIENT", "Client RPC registration completed."); } } } catch (Exception arg) { SharedLogging.Warn("RPC", $"Client RPC registration failed: {arg}"); } try { GameObject val = new GameObject("SkyNet_ClientOverlayHost"); Object.DontDestroyOnLoad((Object)(object)val); Type typeFromHandle = typeof(ClientOverlayHost); if (typeFromHandle != null) { val.AddComponent(typeFromHandle); SkyNetBootSequence.ClientOverlayInit = true; SharedLogging.Info("CLIENT", "Client overlay host created."); } } catch (Exception arg2) { SharedLogging.Warn("CLIENT", $"Overlay host init failed: {arg2}"); } SkyNetBootSequence.Run((BaseUnityPlugin)(object)this, isServer: false); } private void Update() { if (_initializedServer) { ServerUpdate(); } else if (_initializedClient) { ClientUpdate(); } } private void ServerUpdate() { ServerMetricsEngine.Update(); ServerLogicEngine.Update(); ServerZDOThrottle.Update(); ServerAILoadBalancer.Update(); ServerZoneWarmup.Update(); ServerHeartbeat.Update(); ServerEnvironmentEngine.Update(); } private void ClientUpdate() { try { ZNet instance = ZNet.instance; if ((Object)(object)instance != (Object)null) { ZRpc serverRPC = instance.GetServerRPC(); if (serverRPC != null) { SharedRPC.RegisterClientRPC(serverRPC); } } } catch { } ClientMetricsEngine.Update(); } } [HarmonyPatch(typeof(BaseAI), "UpdateAI")] internal static class Patch_AI_UpdateAI { private static void Prefix() { if (SharedReflectionCache.CanBalanceAI) { ServerMetricsEngine.NotifyAIRawRequest(); } } private static void Postfix() { if (SharedReflectionCache.CanBalanceAI) { ServerMetricsEngine.NotifyAIActualUpdate(); } } } internal static class ServerAILoadBalancer { private static int _aiBudget; private static float _lastReset; public static void Initialize() { _lastReset = SharedUtils.Now; SharedLogging.Info("S-AI", "ServerAILoadBalancer initialized."); } public static void Update() { if (SharedReflectionCache.CanBalanceAI) { float now = SharedUtils.Now; if (now - _lastReset >= 0.05f) { _lastReset = now; ApplyModeBudget(); } } } private static void ApplyModeBudget() { switch (ServerLogicEngine.GetMode()) { case "Boost": _aiBudget = 999999; break; case "Balanced": _aiBudget = 200; break; case "Shield": _aiBudget = 80; break; case "Failsafe": _aiBudget = 10; break; default: _aiBudget = 100; break; } } public static bool AllowAIUpdate() { if (!SharedReflectionCache.CanBalanceAI) { return true; } if (_aiBudget <= 0) { return false; } _aiBudget--; return true; } } internal static class ServerAutoPatcher { private static Harmony _harmony; private const string HARMONY_ID = "wubarrk.skynet.server"; public static void Apply() { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Expected O, but got Unknown if (_harmony == null) { _harmony = new Harmony("wubarrk.skynet.server"); SharedLogging.Info("S-PATCH", "Harmony instance created."); } if (SharedReflectionCache.CanThrottleZDOs) { Patch_SendZDOs(); } else { SharedLogging.Warn("S-PATCH", "ZDO throttling unavailable this run."); } if (SharedReflectionCache.CanThrottleZones) { Patch_GenerateZones(); } else { SharedLogging.Warn("S-PATCH", "Zone throttling unavailable this run."); } if (SharedReflectionCache.CanBalanceAI) { Patch_AI(); } else { SharedLogging.Warn("S-PATCH", "AI load balancing unavailable this run."); } } private static void Patch_SendZDOs() { //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Expected O, but got Unknown MethodInfo zDOMan_SendZDOs = SharedReflectionCache.ZDOMan_SendZDOs; if (!(zDOMan_SendZDOs == null)) { MethodInfo method = typeof(ServerAutoPatcher).GetMethod("SendZDOs_Postfix", BindingFlags.Static | BindingFlags.NonPublic); _harmony.Patch((MethodBase)zDOMan_SendZDOs, (HarmonyMethod)null, new HarmonyMethod(method), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); SharedLogging.Info("S-PATCH", "Patched ZDOMan.SendZDOs (metrics + throttling)."); } } private static void Patch_GenerateZones() { //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Expected O, but got Unknown MethodInfo zoneSystem_GenerateZones = SharedReflectionCache.ZoneSystem_GenerateZones; if (!(zoneSystem_GenerateZones == null)) { MethodInfo method = typeof(ServerAutoPatcher).GetMethod("GenerateZones_Prefix", BindingFlags.Static | BindingFlags.NonPublic); _harmony.Patch((MethodBase)zoneSystem_GenerateZones, new HarmonyMethod(method), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); SharedLogging.Info("S-PATCH", "Patched ZoneSystem.GenerateZones (zone throttling + metrics)."); } } private static void Patch_AI() { //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Expected O, but got Unknown MethodInfo aI_UpdateAI = SharedReflectionCache.AI_UpdateAI; if (!(aI_UpdateAI == null)) { MethodInfo method = typeof(ServerAutoPatcher).GetMethod("AI_UpdateAI_Prefix", BindingFlags.Static | BindingFlags.NonPublic); _harmony.Patch((MethodBase)aI_UpdateAI, new HarmonyMethod(method), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); SharedLogging.Info("S-PATCH", "Patched AI.UpdateAI (AI load balancing)."); } } private static void SendZDOs_Postfix(ZDOMan __instance) { ServerMetricsEngine.NotifySendZDOsCalled(__instance); FieldInfo zDOMan_m_tempSendList = SharedReflectionCache.ZDOMan_m_tempSendList; if (!(zDOMan_m_tempSendList == null) && zDOMan_m_tempSendList.GetValue(__instance) is IList list) { int count = list.Count; if (!ServerZDOThrottle.ConsumeZdoBudget(count)) { list.Clear(); SharedLogging.Info("S-THROTTLE", $"ZDO send throttled: {count} entries dropped this tick."); } } } private static bool GenerateZones_Prefix() { ServerMetricsEngine.NotifyZoneGenerated(); if (!ServerZDOThrottle.ConsumeZoneBudget()) { SharedLogging.Info("S-THROTTLE", "Zone generation throttled this tick."); return false; } return true; } private static bool AI_UpdateAI_Prefix() { if (!ServerAILoadBalancer.AllowAIUpdate()) { return false; } return true; } } internal static class ServerDeepScan { public static void Run() { SharedLogging.Info("S-DEEPSCAN", "Beginning server deep scan…"); SharedReflectionCache.Reset(); Assembly assembly = typeof(ZNet).Assembly; SharedReflectionCache.AssemblyVersion = assembly.GetName().Version?.ToString() ?? "unknown"; SharedReflectionCache.BuildHash = assembly.ManifestModule.ModuleVersionId.ToString(); BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; SharedReflectionCache.ZNetType = typeof(ZNet); SharedReflectionCache.ZDOManType = typeof(ZDOMan); SharedReflectionCache.ZoneSystemType = typeof(ZoneSystem); SharedReflectionCache.ZNetPeerType = typeof(ZNetPeer); SharedReflectionCache.ZSteamSocketType = typeof(ZSteamSocket); if (typeof(EnvMan) != null) { SharedReflectionCache.HasEnvMan = true; SharedLogging.Ritual("Enviro lattice detected: EnvMan subsystem available."); Type typeFromHandle = typeof(EnvMan); SharedReflectionCache.EnvMan_GetWindIntensity = typeFromHandle.GetMethod("GetWindIntensity", bindingAttr); SharedReflectionCache.EnvMan_GetRainIntensity = typeFromHandle.GetMethod("GetRainIntensity", bindingAttr); SharedReflectionCache.EnvMan_GetFogIntensity = typeFromHandle.GetMethod("GetFogIntensity", bindingAttr); SharedLogging.Info("S-DEEPSCAN", $"EnvMan methods: wind={SharedReflectionCache.EnvMan_GetWindIntensity != null}, " + $"rain={SharedReflectionCache.EnvMan_GetRainIntensity != null}, " + $"fog={SharedReflectionCache.EnvMan_GetFogIntensity != null}"); } SharedReflectionCache.ZDOMan_SendZDOs = SharedReflectionCache.ZDOManType.GetMethod("SendZDOs", bindingAttr); if (SharedReflectionCache.ZDOMan_SendZDOs != null) { SharedReflectionCache.Patch_SendZDOs = true; SharedLogging.Info("S-DEEPSCAN", "Found ZDOMan.SendZDOs — patching enabled."); } else { SharedLogging.Warn("S-DEEPSCAN", "ZDOMan.SendZDOs not found — ZDO throttling disabled."); } SharedReflectionCache.ZDOMan_m_tempToSync = SharedReflectionCache.ZDOManType.GetField("m_tempToSync", bindingAttr); SharedReflectionCache.ZDOMan_m_tempToSyncDistant = SharedReflectionCache.ZDOManType.GetField("m_tempToSyncDistant", bindingAttr); if (SharedReflectionCache.ZDOMan_m_tempToSync != null && SharedReflectionCache.ZDOMan_m_tempToSyncDistant != null) { SharedLogging.Ritual("ZDO throttling lattice restored: batching lists discovered."); } else { SharedLogging.Warn("S-DEEPSCAN", "ZDO batching lists not found — throttling dormant."); } SharedReflectionCache.ZDOMan_m_sendQueue = SharedReflectionCache.ZDOManType.GetField("m_sendQueue", bindingAttr); SharedReflectionCache.ZDOMan_m_tempSendList = SharedReflectionCache.ZDOManType.GetField("m_tempSendList", bindingAttr); SharedReflectionCache.ZoneSystem_GenerateZones = SharedReflectionCache.ZoneSystemType.GetMethod("GenerateZones", bindingAttr); SharedReflectionCache.ZoneSystem_m_activeZones = SharedReflectionCache.ZoneSystemType.GetField("m_activeZones", bindingAttr); SharedReflectionCache.ZoneSystem_m_zones = SharedReflectionCache.ZoneSystemType.GetField("m_zones", bindingAttr); SharedReflectionCache.AI_UpdateAI = typeof(Character).GetMethod("UpdateAI", bindingAttr) ?? typeof(BaseAI).GetMethod("UpdateAI", bindingAttr); SharedReflectionCache.CanReadTick = true; SharedReflectionCache.CanReadChurn = true; SharedReflectionCache.CanReadZones = true; SharedReflectionCache.LogSummary(); DeepScanData deepScanData = default(DeepScanData); deepScanData.Version = SharedReflectionCache.AssemblyVersion; deepScanData.BuildHash = SharedReflectionCache.BuildHash; deepScanData.HasZNet = SharedReflectionCache.HasZNet; deepScanData.HasZDOMan = SharedReflectionCache.HasZDOMan; deepScanData.HasZoneSystem = SharedReflectionCache.HasZoneSystem; deepScanData.CanThrottleZDOs = SharedReflectionCache.CanThrottleZDOs; deepScanData.CanThrottleZones = SharedReflectionCache.CanThrottleZones; deepScanData.CanBalanceAI = SharedReflectionCache.CanBalanceAI; deepScanData.CanWarmupZones = SharedReflectionCache.CanWarmupZones; deepScanData.ClientCanSetBandwidth = SharedReflectionCache.ClientCanSetBandwidth; deepScanData.CanReadQueue = SharedReflectionCache.CanReadQueue; deepScanData.CanReadTick = SharedReflectionCache.CanReadTick; deepScanData.CanReadChurn = SharedReflectionCache.CanReadChurn; deepScanData.CanReadZones = SharedReflectionCache.CanReadZones; deepScanData.IsDegraded = SharedReflectionCache.IsDegraded; DeepScanData deepScanData2 = deepScanData; SharedLogging.Info("S-DEEPSCAN", $"DeepScanData: {deepScanData2}"); ServerState.DeepScan = deepScanData2; } } internal static class ServerEnvironmentEngine { private static float _wind; private static float _rain; private static float _fog; private static bool _enabled; public static float Wind => _wind; public static float Rain => _rain; public static float Fog => _fog; public static void Initialize() { _enabled = SharedReflectionCache.HasEnvMan; if (_enabled) { SharedLogging.Info("S-ENV", "Environment engine initialized (lightweight mode)."); } else { SharedLogging.Info("S-ENV", "EnvMan not found — environment engine dormant."); } } public static void Update() { if (!_enabled) { return; } EnvMan instance = EnvMan.instance; if (!((Object)(object)instance == (Object)null)) { if (SharedReflectionCache.EnvMan_GetWindIntensity != null) { _wind = (float)SharedReflectionCache.EnvMan_GetWindIntensity.Invoke(instance, null); } else { _wind = 0f; } if (SharedReflectionCache.EnvMan_GetRainIntensity != null) { _rain = (float)SharedReflectionCache.EnvMan_GetRainIntensity.Invoke(instance, null); } else { _rain = 0f; } if (SharedReflectionCache.EnvMan_GetFogIntensity != null) { _fog = (float)SharedReflectionCache.EnvMan_GetFogIntensity.Invoke(instance, null); } else { _fog = 0f; } } } public static float GetEnvironmentBias() { if (!_enabled) { return 1f; } float num = _wind * 0.4f + _rain * 0.4f + _fog * 0.2f; return Mathf.Lerp(0.9f, 1.2f, Mathf.Clamp01(num)); } } internal static class ServerHeartbeat { private static float _nextSend; public static void Initialize() { _nextSend = Time.time + 6f; SharedLogging.Info("S-HB", "ServerHeartbeat initialized."); } public static void Update() { //IL_0150: Unknown result type (might be due to invalid IL or missing references) //IL_0156: Expected O, but got Unknown float time = Time.time; if (time < _nextSend) { return; } _nextSend = time + 6f; SharedLogging.Info("S-HB", "Mode=" + SkyNetStabilizedMetrics.Mode + " Reason=" + SkyNetStabilizedMetrics.ModeReason + " " + $"Tick={SkyNetStabilizedMetrics.Tick:F1} " + $"Drift={SkyNetStabilizedMetrics.Drift:F1} " + $"Jitter={SkyNetStabilizedMetrics.Jitter:F2} " + $"Stability={SkyNetStabilizedMetrics.Stability:F2} " + $"Trend={SkyNetStabilizedMetrics.Trend:+0.00;-0.00} " + $"Conf={SkyNetStabilizedMetrics.Confidence:F2} " + $"Q={SkyNetStabilizedMetrics.Queue} " + $"C={SkyNetStabilizedMetrics.ChurnPerSec} " + $"Z={SkyNetStabilizedMetrics.ZonesPerSec} " + $"Degraded={SkyNetStabilizedMetrics.IsDegraded}"); ServerSnapshot serverSnapshot = ServerMetricsEngine.BuildSnapshot(ServerLogicEngine.GetMode()); ZPackage val = new ZPackage(); serverSnapshot.Serialize(val); foreach (ZNetPeer peer in ZNet.instance.GetPeers()) { try { peer.m_rpc.Invoke("SkyNet_ServerHeartbeat_v1", new object[1] { val }); } catch (Exception ex) { SharedLogging.Warn("S-HB", $"Failed to send heartbeat to peer {peer.m_uid}: {ex.Message}"); } } } } internal static class ServerLogicEngine { private static string _mode = "Balanced"; private static DateTime _serverStartTime; private static readonly Dictionary _playerLoadWindows = new Dictionary(); private static bool _startupLoggedActive; private static bool _startupLoggedCleared; private static bool _configWarned; private static bool _envBiasLogged; private const int WindowSize = 60; private static readonly float[] _tickWindow = new float[60]; private static readonly float[] _driftWindow = new float[60]; private static int _windowIndex; private static bool _windowFilled; private static DateTime _lastDecisionTime = DateTime.MinValue; private static readonly TimeSpan DecisionInterval = TimeSpan.FromSeconds(3.0); private const float BASE_TICK_FAIL = 80f; private const float BASE_TICK_SHIELD = 50f; private const float BASE_TICK_BOOST = 36f; private const float BASE_DRIFT_FAIL = 80f; private const float BASE_DRIFT_SHIELD = 50f; private const float BASE_DRIFT_BOOST = 36f; private const float BASE_JITTER_FAIL = 5f; private const float BASE_JITTER_SHIELD = 3.5f; private const float BASE_JITTER_BOOST = 2f; private const int BASE_QUEUE_FAIL = 2000; private const int BASE_QUEUE_SHIELD = 800; private const int BASE_QUEUE_BOOST = 200; private const int BASE_CHURN_FAIL = 2000; private const int BASE_CHURN_SHIELD = 800; private const int BASE_CHURN_BOOST = 200; private const int BASE_ZONES_FAIL = 120; private const int BASE_ZONES_SHIELD = 60; private const int BASE_ZONES_BOOST = 20; private const int BASE_AI_FAIL = 500; private const int BASE_AI_SHIELD = 250; private const int BASE_AI_BOOST = 100; private static bool ConfigReady { get { if (SharedConfig.Server_StartupGraceSeconds == null || SharedConfig.Server_PlayerLoadWindowSeconds == null || SharedConfig.AutoTuner_Enabled == null || SharedConfig.AutoTuner_Strength == null || SharedConfig.AutoTuner_ModeAggression == null || SharedConfig.Trinity_JitterWeight == null || SharedConfig.Trinity_DriftWeight == null || SharedConfig.Trinity_TickWeight == null) { if (!_configWarned) { _configWarned = true; SharedLogging.Warn("S-LOGIC", "SharedConfig not fully initialized — ServerLogicEngine.Update() dormant until config is ready."); } return false; } return true; } } private static bool IsInStartupGrace { get { if (!ConfigReady) { return false; } double num = SharedConfig.Server_StartupGraceSeconds.Value; if (num <= 0.0) { return false; } return (DateTime.UtcNow - _serverStartTime).TotalSeconds < num; } } private static bool AnyPlayerInLoadWindow { get { if (!ConfigReady) { return false; } DateTime utcNow = DateTime.UtcNow; bool result = false; List list = new List(); foreach (KeyValuePair playerLoadWindow in _playerLoadWindows) { if (playerLoadWindow.Value > utcNow) { result = true; } else { list.Add(playerLoadWindow.Key); } } foreach (long item in list) { _playerLoadWindows.Remove(item); SharedLogging.Info("S-LOGIC", $"Player {item} load window expired."); } return result; } } public static void Initialize() { _serverStartTime = DateTime.UtcNow; _startupLoggedActive = false; _startupLoggedCleared = false; _configWarned = false; _envBiasLogged = false; _windowIndex = 0; _windowFilled = false; _lastDecisionTime = DateTime.MinValue; SharedLogging.Info("S-LOGIC", "ServerLogicEngine initialized."); } public static void NotifyPlayerAwake(long playerID) { if (ConfigReady) { _playerLoadWindows[playerID] = DateTime.UtcNow.AddSeconds(SharedConfig.Server_PlayerLoadWindowSeconds.Value); SharedLogging.Info("S-LOGIC", $"Player {playerID} entered world — load window active for {SharedConfig.Server_PlayerLoadWindowSeconds.Value:F0}s."); } } private static void FeedWindow(float tick, float drift) { _tickWindow[_windowIndex] = tick; _driftWindow[_windowIndex] = drift; _windowIndex++; if (_windowIndex >= 60) { _windowIndex = 0; _windowFilled = true; } } private static void ComputeWindowStats(out float meanTick, out float meanDrift, out float jitter, out float trend) { int num = (_windowFilled ? 60 : _windowIndex); if (num <= 0) { meanTick = (meanDrift = (jitter = (trend = 0f))); return; } float num2 = 0f; float num3 = 0f; for (int i = 0; i < num; i++) { num2 += _tickWindow[i]; num3 += _driftWindow[i]; } meanTick = num2 / (float)num; meanDrift = num3 / (float)num; float num4 = 0f; for (int j = 0; j < num; j++) { float num5 = _tickWindow[j] - meanTick; float num6 = _driftWindow[j] - meanDrift; num4 += num5 * num5 + num6 * num6; } jitter = (float)Math.Sqrt(num4 / (float)num); float num7 = _tickWindow[0]; float num8 = _tickWindow[(num - 1 + 60) % 60]; trend = (num8 - num7) / (float)Math.Max(1, num); } public static void Update() { if (!ConfigReady) { return; } bool isInStartupGrace = IsInStartupGrace; bool anyPlayerInLoadWindow = AnyPlayerInLoadWindow; if (isInStartupGrace && !_startupLoggedActive) { _startupLoggedActive = true; SharedLogging.Info("S-LOGIC", $"Startup grace window active for {SharedConfig.Server_StartupGraceSeconds.Value:F0}s — mode locked to Balanced."); } else if (!isInStartupGrace && !_startupLoggedCleared) { _startupLoggedCleared = true; SharedLogging.Info("S-LOGIC", "Startup grace window ended — adaptive modes unlocked."); } DeepScanData deepScan = ServerState.DeepScan; float tickMs = ServerMetricsEngine.GetTickMs(); float driftMs = ServerMetricsEngine.GetDriftMs(); int num = ServerMetricsEngine.GetQueue(); ServerSnapshot serverSnapshot = ServerMetricsEngine.BuildSnapshot("tmp"); int num2 = serverSnapshot.ChurnPerSec; int num3 = serverSnapshot.ZonesPerSec; bool flag = false; bool flag2 = false; bool flag3 = false; if (!deepScan.CanReadQueue) { num = num2 * 2 + num3 * 5; flag = true; } if (!deepScan.CanReadChurn) { num2 = num / 2; flag2 = true; } if (!deepScan.CanReadZones) { num3 = num2 / 4; flag3 = true; } int num4 = (SharedReflectionCache.CanBalanceAI ? ServerMetricsEngine.GetRawAILoad() : (-1)); bool flag4 = num4 >= 0; bool isDegraded = deepScan.IsDegraded; float environmentBias = ServerEnvironmentEngine.GetEnvironmentBias(); environmentBias = Mathf.Clamp(environmentBias, 0.8f, 1.2f); if (!_envBiasLogged) { _envBiasLogged = true; SharedLogging.Info("S-LOGIC", $"Environment bias = {environmentBias:F2}"); } float num5 = 80f * environmentBias; float num6 = 50f * environmentBias; float num7 = 36f / environmentBias; float num8 = 80f * environmentBias; float num9 = 50f * environmentBias; float num10 = 36f / environmentBias; float num11 = 5f; float num12 = 3.5f; float num13 = 2f; int num14 = (int)(2000f * environmentBias); int num15 = (int)(800f * environmentBias); int num16 = (int)(200f / environmentBias); int num17 = (int)(2000f * environmentBias); int num18 = (int)(800f * environmentBias); int num19 = (int)(200f / environmentBias); int num20 = (int)(120f * environmentBias); int num21 = (int)(60f * environmentBias); int num22 = (int)(20f / environmentBias); int num23 = (int)(500f * environmentBias); int num24 = (int)(250f * environmentBias); int num25 = (int)(100f / environmentBias); FeedWindow(tickMs, driftMs); ComputeWindowStats(out var meanTick, out var meanDrift, out var jitter, out var trend); float num26 = 1f / (1f + jitter / 10f); float num27 = num26; if (!((Object)(object)ZNet.instance != (Object)null) || ZNet.instance.GetNrOfPlayers() == 0) { if (_mode != "IdleFreeze") { SharedLogging.Ritual("Cognitive state shift: " + _mode + " → IdleFreeze"); _mode = "IdleFreeze"; } ServerMetricsEngine.SetModeReason("IdleFreeze"); PublishStabilizedMetrics(meanTick, meanDrift, jitter, trend, num26, num27, num, num2, num3, isDegraded, "IdleFreeze"); return; } if (_mode == "IdleFreeze") { SharedLogging.Ritual("Cognitive state shift: IdleFreeze → Balanced (PlayerConnected)"); _mode = "Balanced"; _windowIndex = 0; _windowFilled = false; } if (isInStartupGrace || anyPlayerInLoadWindow) { if (_mode != "Balanced") { SharedLogging.Ritual("Cognitive state shift: " + _mode + " → Balanced (protection window)"); _mode = "Balanced"; } if (anyPlayerInLoadWindow) { SharedLogging.Info("S-LOGIC", "Per-player load window active — suppressing aggressive mode changes."); } ServerMetricsEngine.SetModeReason("ProtectionWindow"); PublishStabilizedMetrics(meanTick, meanDrift, jitter, trend, num26, num27, num, num2, num3, isDegraded, "ProtectionWindow"); return; } float num28 = (SharedConfig.AutoTuner_Enabled.Value ? Mathf.Clamp(SharedConfig.AutoTuner_Strength.Value, 0f, 1f) : 0f); float num29 = ((meanTick > 0f) ? meanTick : tickMs); float num30 = ((meanDrift > 0f) ? meanDrift : driftMs); float num31 = Mathf.Clamp(trend, -2f, 2f); float num32 = Mathf.Max(0.01f, SharedConfig.Trinity_JitterWeight.Value); float num33 = Mathf.Max(0.01f, SharedConfig.Trinity_DriftWeight.Value); float num34 = Mathf.Max(0.01f, SharedConfig.Trinity_TickWeight.Value); float num35 = ((num12 > 0f) ? (jitter / num12) : 0f); float num36 = ((num9 > 0f) ? (num30 / num9) : 0f); float num37 = ((num6 > 0f) ? (num29 / num6) : 0f); float num38 = (num32 * num35 + num33 * num36 + num34 * num37) / (num32 + num33 + num34); float num39 = Mathf.Clamp(SharedConfig.AutoTuner_ModeAggression.Value, 0f, 2f); float num40 = Mathf.Lerp(0.7f, 1.3f, num39 / 2f); float num41 = Mathf.Lerp(1.3f, 0.7f, num39 / 2f) * (1f / Mathf.Clamp(num38, 0.7f, 1.3f)); float num42 = num40 * Mathf.Clamp(2f - num38, 0.7f, 1.3f); float num43 = 1f - num28 * (1f - num26) * 0.25f - num28 * Mathf.Max(0f, num31) * 0.05f; float num44 = 1f + num28 * (num26 - 0.5f) * 0.3f - num28 * Mathf.Max(0f, num31) * 0.05f; float num45 = num43; float num46 = num44; float num47 = 1f - num28 * (1f - num26) * 0.3f; float num48 = 1f + num28 * (num26 - 0.5f) * 0.3f; float num49 = num5; float num50 = num6 * num43 * num41; float num51 = num7 * num44 * num42; float num52 = num8; float num53 = num9 * num45 * num41; float num54 = num10 * num46 * num42; float num55 = num11; float num56 = num12 * num47 * num41; float num57 = num13 * num48 * num42; float num58 = ((!flag && deepScan.CanReadQueue) ? 1f : 0f); float num59 = ((!flag2 && deepScan.CanReadChurn) ? 1f : 0f); float num60 = ((!flag3 && deepScan.CanReadZones) ? 1f : 0f); float num61 = (flag4 ? 0.75f : 0f); float num62 = 1f + num28 * Mathf.Max(0f, num31) * 0.3f; num58 *= num62; num59 *= num62; float num63 = 1f - num28 * Mathf.Max(0f, (jitter - num12) / num12) * 0.5f; num61 *= Mathf.Clamp(num63, 0.25f, 1f); num60 *= Mathf.Clamp(num63, 0.5f, 1f); float num64 = (float)num14 * num58; float num65 = (float)num15 * num58 * num41; float num66 = (float)num16 * num58 * num42; float num67 = (float)num17 * num59; float num68 = (float)num18 * num59 * num41; float num69 = (float)num19 * num59 * num42; float num70 = (float)num20 * num60; float num71 = (float)num21 * num60 * num41; float num72 = (float)num22 * num60 * num42; float num73 = (float)num23 * num61; float num74 = (float)num24 * num61 * num41; float num75 = (float)num25 * num61 * num42; bool num76 = DateTime.UtcNow - _lastDecisionTime >= DecisionInterval && (_windowFilled || _windowIndex > 10); string mode = _mode; string text = "Stable"; int num77; int num78; if (num76) { _lastDecisionTime = DateTime.UtcNow; if (!(jitter > num55) && !(num30 > num52)) { num77 = ((num29 > num49) ? 1 : 0); if (num77 == 0) { num78 = ((jitter > num56 || num30 > num53 || num29 > num50) ? 1 : 0); goto IL_0798; } } else { num77 = 1; } num78 = 0; goto IL_0798; } PublishStabilizedMetrics(meanTick, meanDrift, jitter, trend, num26, num27, num, num2, num3, isDegraded, "Stable"); return; IL_0798: bool flag5 = (byte)num78 != 0; bool flag6 = jitter < num57 && num30 < num54 && num29 < num51; bool flag7 = (num58 > 0f && (float)num > num65) || (num59 > 0f && (float)num2 > num68) || (num60 > 0f && (float)num3 > num71) || (num61 > 0f && flag4 && (float)num4 > num74); bool flag8 = (num58 > 0f && (float)num > num64) || (num59 > 0f && (float)num2 > num67) || (num60 > 0f && (float)num3 > num70) || (num61 > 0f && flag4 && (float)num4 > num73); if (((uint)num77 | (flag8 ? 1u : 0u)) != 0) { mode = "Failsafe"; text = (isDegraded ? "CriticalLoadDegraded" : "CriticalLoad"); } else if (flag5 || flag7) { mode = "Shield"; text = (isDegraded ? "HighLoadDegraded" : "HighLoad"); } else if (flag6 && (num58 == 0f || (float)num < num66) && (num59 == 0f || (float)num2 < num69) && (num60 == 0f || (float)num3 < num72) && (!flag4 || (float)num4 < num75)) { mode = "Boost"; text = (isDegraded ? "LowLoadDegraded" : "LowLoad"); } else { mode = "Balanced"; text = "Stable"; } if (num27 < 0.4f && mode == "Boost") { mode = "Balanced"; text = "UnstableLowConfidence"; } if (_mode != mode) { SharedLogging.Ritual("Cognitive state shift: " + _mode + " → " + mode); switch (mode) { case "Failsafe": SharedLogging.Warn("S-LOGIC", "Failsafe engaged — applying maximum protection: ZDO throttling hard clamp, AI load reduction, zone generation suppression."); break; case "Shield": SharedLogging.Info("S-LOGIC", "Shield mode active — moderating server load: reduced ZDO send rate, softened AI updates, zone pacing increased."); break; case "Balanced": SharedLogging.Info("S-LOGIC", "Balanced mode restored — all systems operating at normal parameters."); break; case "Boost": SharedLogging.Info("S-LOGIC", "Boost mode engaged — performance headroom detected: increasing ZDO throughput, accelerating AI updates, relaxing zone pacing."); break; } _mode = mode; } ServerMetricsEngine.SetModeReason(text); PublishStabilizedMetrics(meanTick, meanDrift, jitter, trend, num26, num27, num, num2, num3, isDegraded, text); } private static void PublishStabilizedMetrics(float meanTick, float meanDrift, float jitter, float trend, float stability, float confidence, int queue, int churn, int zones, bool degraded, string modeReason) { float tick = ((meanTick > 0f) ? meanTick : ServerMetricsEngine.GetTickMs()); float drift = ((meanDrift > 0f) ? meanDrift : ServerMetricsEngine.GetDriftMs()); SkyNetStabilizedMetrics.Mode = _mode; SkyNetStabilizedMetrics.ModeReason = modeReason; SkyNetStabilizedMetrics.Tick = tick; SkyNetStabilizedMetrics.Drift = drift; SkyNetStabilizedMetrics.Jitter = jitter; SkyNetStabilizedMetrics.Trend = trend; SkyNetStabilizedMetrics.Stability = stability; SkyNetStabilizedMetrics.Confidence = confidence; SkyNetStabilizedMetrics.Queue = queue; SkyNetStabilizedMetrics.ChurnPerSec = churn; SkyNetStabilizedMetrics.ZonesPerSec = zones; SkyNetStabilizedMetrics.IsDegraded = degraded; } public static string GetMode() { return _mode; } } internal static class ServerMetricsEngine { private static float _tickMs; private static float _driftMs; private static int _queue; private static int _churn; private static int _zones; private static float _outRateKbps; private static float _inRateKbps; private static float _accumTime; private static int _accumChurn; private static int _accumZones; private const int SmoothWindow = 20; private static readonly Queue _tickHistory = new Queue(); private static readonly Queue _driftHistory = new Queue(); private static int _rawAIRequestsFrame; private static int _actualAIUpdatesFrame; private static int _rawAIRequests; private static int _actualAIUpdates; private static string _modeReason = "Stable"; public static void Initialize() { _tickMs = 0f; _driftMs = 0f; _queue = 0; _churn = 0; _zones = 0; _outRateKbps = 0f; _inRateKbps = 0f; _accumTime = 0f; _accumChurn = 0; _accumZones = 0; _tickHistory.Clear(); _driftHistory.Clear(); _rawAIRequestsFrame = 0; _actualAIUpdatesFrame = 0; _rawAIRequests = 0; _actualAIUpdates = 0; _modeReason = "Stable"; SharedLogging.Info("S-METRICS", "ServerMetricsEngine initialized."); } public static void Update() { _rawAIRequests = _rawAIRequestsFrame; _actualAIUpdates = _actualAIUpdatesFrame; _rawAIRequestsFrame = 0; _actualAIUpdatesFrame = 0; float num = ((Time.deltaTime > 0f) ? Time.deltaTime : 0.02f); float num2 = num * 1000f; float value = Mathf.Abs(num2 - 50f); _tickMs = Smooth(_tickHistory, num2); _driftMs = Smooth(_driftHistory, value); _accumTime += num; if (_accumTime >= 1f) { _churn = _accumChurn; _zones = _accumZones; _accumChurn = 0; _accumZones = 0; _accumTime -= 1f; } if (SharedReflectionCache.ZDOMan_m_sendQueue != null) { ZDOMan instance = ZDOMan.instance; _queue = (SharedReflectionCache.ZDOMan_m_sendQueue.GetValue(instance) as IList)?.Count ?? 0; } else { _queue = 0; } _outRateKbps = 0f; _inRateKbps = 0f; } private static float Smooth(Queue q, float value) { q.Enqueue(value); if (q.Count > 20) { q.Dequeue(); } float num = 0f; foreach (float item in q) { num += item; } return num / (float)q.Count; } public static void NotifySendZDOsCalled(ZDOMan zdom) { if (zdom == null) { return; } FieldInfo zDOMan_m_tempSendList = SharedReflectionCache.ZDOMan_m_tempSendList; if (!(zDOMan_m_tempSendList == null) && zDOMan_m_tempSendList.GetValue(zdom) is IList list) { int count = list.Count; if (count > 0) { _accumChurn += count; } } } public static void NotifyZoneGenerated() { _accumZones++; } public static void NotifyAIRawRequest() { _rawAIRequestsFrame++; } public static void NotifyAIActualUpdate() { _actualAIUpdatesFrame++; } public static void SetModeReason(string reason) { _modeReason = (string.IsNullOrEmpty(reason) ? "Stable" : reason); } public static ServerSnapshot BuildSnapshot(string mode) { DeepScanData deepScan = ServerState.DeepScan; bool flag = !deepScan.CanReadQueue; bool flag2 = !deepScan.CanReadChurn; bool flag3 = !deepScan.CanReadZones; ServerSnapshot serverSnapshot = default(ServerSnapshot); serverSnapshot.Mode = mode; serverSnapshot.ModeReason = _modeReason; serverSnapshot.TickMs = _tickMs; serverSnapshot.DriftMs = _driftMs; serverSnapshot.Queue = _queue; serverSnapshot.ChurnPerSec = _churn; serverSnapshot.ZonesPerSec = _zones; serverSnapshot.OutRateKbps = _outRateKbps; serverSnapshot.InRateKbps = _inRateKbps; serverSnapshot.IsDegraded = SharedReflectionCache.IsDegraded; serverSnapshot.InferenceMode = flag || flag2 || flag3; serverSnapshot.Version = SharedReflectionCache.AssemblyVersion; serverSnapshot.BuildHash = SharedReflectionCache.BuildHash; ServerSnapshot result = serverSnapshot; result.Sanitize(); return result; } public static float GetTickMs() { return _tickMs; } public static float GetDriftMs() { return _driftMs; } public static int GetQueue() { return _queue; } public static int GetRawAILoad() { return _rawAIRequests; } public static int GetActualAILoad() { return _actualAIUpdates; } } internal static class ServerState { public static DeepScanData DeepScan; } internal static class ServerZDOThrottle { private static int _zdoBudget; private static int _zoneBudget; private static float _lastReset; public static void Initialize() { _lastReset = SharedUtils.Now; ApplyModeBudgets(); SharedLogging.Info("S-THROTTLE", "ServerZDOThrottle initialized."); } public static void Update() { float now = SharedUtils.Now; if (now - _lastReset >= 0.05f) { _lastReset = now; ApplyModeBudgets(); } } private static void ApplyModeBudgets() { switch (ServerLogicEngine.GetMode()) { case "Boost": _zdoBudget = 999999; _zoneBudget = 999999; break; case "Balanced": _zdoBudget = 4000; _zoneBudget = 20; break; case "Shield": _zdoBudget = 1500; _zoneBudget = 5; break; case "Failsafe": _zdoBudget = 300; _zoneBudget = 0; break; default: _zdoBudget = 2000; _zoneBudget = 10; break; } } public static bool ConsumeZdoBudget(int count) { if (!SharedReflectionCache.CanThrottleZDOs) { return true; } if (_zdoBudget <= 0) { return false; } _zdoBudget -= count; return true; } public static bool ConsumeZoneBudget() { if (!SharedReflectionCache.CanThrottleZones) { return true; } if (_zoneBudget <= 0) { return false; } _zoneBudget--; return true; } } internal static class ServerZoneWarmup { public static void Initialize() { SharedLogging.Info("S-ZONE", "ServerZoneWarmup initialized."); } public static void Update() { if (!SharedReflectionCache.CanWarmupZones) { return; } IDictionary obj = SharedReflectionCache.ZoneSystem_m_activeZones.GetValue(ZoneSystem.instance) as IDictionary; IDictionary dictionary = SharedReflectionCache.ZoneSystem_m_zones.GetValue(ZoneSystem.instance) as IDictionary; if (obj != null && dictionary != null) { string mode = ServerLogicEngine.GetMode(); if (!(mode == "Boost") && !(mode == "Shield")) { _ = mode == "Failsafe"; } } } } internal struct DeepScanData { public string Version; public string BuildHash; public bool HasZNet; public bool HasZDOMan; public bool HasZoneSystem; public bool CanThrottleZDOs; public bool CanThrottleZones; public bool CanBalanceAI; public bool CanWarmupZones; public bool ClientCanSetBandwidth; public bool CanReadQueue; public bool CanReadTick; public bool CanReadChurn; public bool CanReadZones; public bool IsDegraded; public override string ToString() { return "Version=" + Version + ", Hash=" + BuildHash + ", " + $"ZNet={HasZNet}, ZDOMan={HasZDOMan}, ZoneSystem={HasZoneSystem}, " + $"ThrottleZDOs={CanThrottleZDOs}, ThrottleZones={CanThrottleZones}, " + $"AI={CanBalanceAI}, Warmup={CanWarmupZones}, " + $"BW={ClientCanSetBandwidth}, " + $"Queue={CanReadQueue}, Tick={CanReadTick}, Churn={CanReadChurn}, Zones={CanReadZones}, " + $"Degraded={IsDegraded}"; } } internal static class LoopbackDetector { public static bool IsLoopback() { if ((Object)(object)ZNet.instance == (Object)null) { return false; } ZNetPeer serverPeer = ZNet.instance.GetServerPeer(); if (serverPeer == null) { return false; } ISocket socket = serverPeer.m_socket; if (socket == null) { return false; } string endPointString = socket.GetEndPointString(); if (string.IsNullOrWhiteSpace(endPointString)) { return false; } endPointString = endPointString.ToLower(); if (!endPointString.Contains("127.0.0.1")) { return endPointString.Contains("localhost"); } return true; } } internal static class SharedConfig { internal static ConfigFile Config; internal static ConfigEntry Server_StartupGraceSeconds; internal static ConfigEntry Server_PlayerLoadWindowSeconds; internal static ConfigEntry AutoTuner_Enabled; internal static ConfigEntry AutoTuner_Strength; internal static ConfigEntry AutoTuner_ModeAggression; internal static ConfigEntry Trinity_JitterWeight; internal static ConfigEntry Trinity_DriftWeight; internal static ConfigEntry Trinity_TickWeight; internal static ConfigEntry Hud_Enabled; internal static ConfigEntry Hud_ToggleKey; internal static ConfigEntry Debug_Logging; internal static ConfigEntry Debug_InferenceModeFlag; internal static void Initialize(ConfigFile config) { Config = config; Server_StartupGraceSeconds = Config.Bind("Server.Protection", "StartupGraceSeconds", 60, "Seconds after server boot where SkyNet will not throttle or mode-shift."); Server_PlayerLoadWindowSeconds = Config.Bind("Server.Protection", "PlayerLoadWindowSeconds", 30, "Seconds after a player enters the world where SkyNet will not throttle or mode-shift."); AutoTuner_Enabled = Config.Bind("AutoTuner", "Enabled", true, "Enable the dynamic trinity-based auto-tuner."); AutoTuner_Strength = Config.Bind("AutoTuner", "Strength", 1f, "How aggressively the auto-tuner tightens/loosens thresholds (0.0 = off, 1.0 = full)."); AutoTuner_ModeAggression = Config.Bind("AutoTuner", "ModeAggression", 1f, "0 = conservative, 1 = balanced, 2 = aggressive. Controls how easily Boost/Shield trigger."); Trinity_JitterWeight = Config.Bind("AutoTuner.Trinity", "JitterWeight", 0.6f, "Relative weight of jitter in the trinity (primary instability signal)."); Trinity_DriftWeight = Config.Bind("AutoTuner.Trinity", "DriftWeight", 0.25f, "Relative weight of drift in the trinity (secondary instability signal)."); Trinity_TickWeight = Config.Bind("AutoTuner.Trinity", "TickWeight", 0.15f, "Relative weight of tick time in the trinity (tertiary instability signal)."); Hud_Enabled = Config.Bind("Client.HUD", "Enabled", true, "Enable or disable the SkyNet client HUD."); Hud_ToggleKey = Config.Bind("Client.HUD", "ToggleKey", "F4", "Key used to toggle the SkyNet HUD."); Debug_Logging = Config.Bind("Debug", "Logging", false, "Enable verbose debug logging."); Debug_InferenceModeFlag = Config.Bind("Debug", "InferenceMode", false, "Force inference mode for testing."); } } internal static class SharedLogging { internal static ManualLogSource Log; internal static void Initialize(ManualLogSource logger) { Log = logger; } internal static void Info(string tag, string msg) { ManualLogSource log = Log; if (log != null) { log.LogInfo((object)("[" + tag + "] " + msg)); } } internal static void Warn(string tag, string msg) { ManualLogSource log = Log; if (log != null) { log.LogWarning((object)("[" + tag + "] " + msg)); } } internal static void Error(string tag, string msg) { ManualLogSource log = Log; if (log != null) { log.LogError((object)("[" + tag + "] " + msg)); } } internal static void Ritual(string msg) { ManualLogSource log = Log; if (log != null) { log.LogInfo((object)("[SKYNET-RITUAL] " + msg)); } } } internal static class SharedReflectionCache { public static string AssemblyVersion { get; internal set; } = "unknown"; public static string BuildHash { get; internal set; } = "unknown"; public static Type ZNetType { get; internal set; } public static Type ZDOManType { get; internal set; } public static Type ZoneSystemType { get; internal set; } public static Type ZNetPeerType { get; internal set; } public static Type ZSteamSocketType { get; internal set; } public static bool HasEnvMan { get; internal set; } public static MethodInfo EnvMan_GetWindIntensity { get; internal set; } public static MethodInfo EnvMan_GetRainIntensity { get; internal set; } public static MethodInfo EnvMan_GetFogIntensity { get; internal set; } public static MethodInfo ZDOMan_SendZDOs { get; internal set; } public static MethodInfo ZoneSystem_GenerateZones { get; internal set; } public static FieldInfo ZDOMan_m_sendQueue { get; internal set; } public static FieldInfo ZDOMan_m_tempSendList { get; internal set; } public static FieldInfo ZoneSystem_m_activeZones { get; internal set; } public static FieldInfo ZoneSystem_m_zones { get; internal set; } public static FieldInfo ZDOMan_m_tempToSync { get; internal set; } public static FieldInfo ZDOMan_m_tempToSyncDistant { get; internal set; } public static MethodInfo AI_UpdateAI { get; internal set; } public static FieldInfo ZSteamSocket_SendRate { get; internal set; } public static FieldInfo ZSteamSocket_RecvRate { get; internal set; } public static bool Patch_SendZDOs { get; internal set; } public static bool HasZNet => ZNetType != null; public static bool HasZDOMan => ZDOManType != null; public static bool HasZoneSystem => ZoneSystemType != null; public static bool CanThrottleZDOs { get { if (ZDOMan_SendZDOs != null && ZDOMan_m_tempToSync != null) { return ZDOMan_m_tempToSyncDistant != null; } return false; } } public static bool CanThrottleZones => ZoneSystem_GenerateZones != null; public static bool CanBalanceAI => AI_UpdateAI != null; public static bool CanWarmupZones { get { if (ZoneSystem_m_activeZones != null) { return ZoneSystem_m_zones != null; } return false; } } public static bool CanReadQueue => ZDOMan_m_sendQueue != null; public static bool CanReadTick { get; internal set; } public static bool CanReadDrift { get; internal set; } public static bool CanReadChurn { get; internal set; } public static bool CanReadZones { get; internal set; } public static bool ClientCanSetBandwidth { get { if (!(ZSteamSocket_SendRate != null)) { return ZSteamSocket_RecvRate != null; } return true; } } public static bool IsDegraded { get { if (CanReadTick) { return !CanReadDrift; } return true; } } public static void Reset() { AssemblyVersion = "unknown"; BuildHash = "unknown"; ZNetType = null; ZDOManType = null; ZoneSystemType = null; ZNetPeerType = null; ZSteamSocketType = null; HasEnvMan = false; EnvMan_GetWindIntensity = null; EnvMan_GetRainIntensity = null; EnvMan_GetFogIntensity = null; ZDOMan_SendZDOs = null; ZoneSystem_GenerateZones = null; ZDOMan_m_sendQueue = null; ZDOMan_m_tempSendList = null; ZoneSystem_m_activeZones = null; ZoneSystem_m_zones = null; ZDOMan_m_tempToSync = null; ZDOMan_m_tempToSyncDistant = null; AI_UpdateAI = null; ZSteamSocket_SendRate = null; ZSteamSocket_RecvRate = null; Patch_SendZDOs = false; CanReadTick = false; CanReadDrift = false; CanReadChurn = false; CanReadZones = false; } public static void Build() { Reset(); try { ZNetType = typeof(ZNet); ZDOManType = typeof(ZDOMan); ZoneSystemType = typeof(ZoneSystem); ZNetPeerType = typeof(ZNetPeer); ZSteamSocketType = typeof(ZSteamSocket); if (ZNetType != null) { Version version = ZNetType.Assembly.GetName().Version; if (version != null) { AssemblyVersion = version.ToString(); } } Type typeFromHandle = typeof(EnvMan); if (typeFromHandle != null) { HasEnvMan = true; SharedLogging.Ritual("Enviro lattice detected: EnvMan subsystem available."); EnvMan_GetWindIntensity = typeFromHandle.GetMethod("GetWindIntensity", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); EnvMan_GetRainIntensity = typeFromHandle.GetMethod("GetRainIntensity", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); EnvMan_GetFogIntensity = typeFromHandle.GetMethod("GetFogIntensity", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); SharedLogging.Info("S-DEEPSCAN", $"EnvMan methods: wind={EnvMan_GetWindIntensity != null}, " + $"rain={EnvMan_GetRainIntensity != null}, " + $"fog={EnvMan_GetFogIntensity != null}"); } if (ZDOManType != null) { ZDOMan_SendZDOs = ZDOManType.GetMethod("SendZDOs", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (ZDOMan_SendZDOs != null) { Patch_SendZDOs = true; SharedLogging.Info("S-DEEPSCAN", "Found ZDOMan.SendZDOs — patching enabled."); } else { SharedLogging.Warn("S-DEEPSCAN", "ZDOMan.SendZDOs not found — ZDO throttling disabled."); } ZDOMan_m_tempToSync = ZDOManType.GetField("m_tempToSync", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); ZDOMan_m_tempToSyncDistant = ZDOManType.GetField("m_tempToSyncDistant", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (ZDOMan_m_tempToSync != null && ZDOMan_m_tempToSyncDistant != null) { SharedLogging.Ritual("ZDO throttling lattice restored: batching lists discovered."); } else { SharedLogging.Warn("S-DEEPSCAN", "ZDO batching lists not found — throttling dormant."); } ZDOMan_m_sendQueue = ZDOManType.GetField("m_sendQueue", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); ZDOMan_m_tempSendList = ZDOManType.GetField("m_tempSendList", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); } if (ZoneSystemType != null) { ZoneSystem_GenerateZones = ZoneSystemType.GetMethod("GenerateZones", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); ZoneSystem_m_activeZones = ZoneSystemType.GetField("m_activeZones", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); ZoneSystem_m_zones = ZoneSystemType.GetField("m_zones", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); } AI_UpdateAI = typeof(Character).GetMethod("UpdateAI", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) ?? typeof(BaseAI).GetMethod("UpdateAI", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (ZSteamSocketType != null) { ZSteamSocket_SendRate = ZSteamSocketType.GetField("m_sendRate", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) ?? ZSteamSocketType.GetField("m_sendDataRate", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); ZSteamSocket_RecvRate = ZSteamSocketType.GetField("m_recvRate", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) ?? ZSteamSocketType.GetField("m_recvDataRate", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); } CanReadTick = true; CanReadDrift = true; CanReadChurn = true; CanReadZones = true; LogSummary(); DeepScanData deepScanData = default(DeepScanData); deepScanData.Version = AssemblyVersion; deepScanData.BuildHash = BuildHash; deepScanData.HasZNet = HasZNet; deepScanData.HasZDOMan = HasZDOMan; deepScanData.HasZoneSystem = HasZoneSystem; deepScanData.CanThrottleZDOs = CanThrottleZDOs; deepScanData.CanThrottleZones = CanThrottleZones; deepScanData.CanBalanceAI = CanBalanceAI; deepScanData.CanWarmupZones = CanWarmupZones; deepScanData.ClientCanSetBandwidth = ClientCanSetBandwidth; deepScanData.CanReadQueue = CanReadQueue; deepScanData.CanReadTick = CanReadTick; deepScanData.CanReadChurn = CanReadChurn; deepScanData.CanReadZones = CanReadZones; deepScanData.IsDegraded = IsDegraded; DeepScanData deepScanData2 = deepScanData; SharedLogging.Info("S-DEEPSCAN", $"DeepScanData: {deepScanData2}"); ServerState.DeepScan = deepScanData2; } catch (Exception ex) { SharedLogging.Warn("CACHE", "Reflection build failed: " + ex.Message); LogSummary(); } } public static void LogSummary() { SharedLogging.Info("CACHE", "===== SKYNET REFLECTION CACHE SUMMARY ====="); SharedLogging.Info("CACHE", "AssemblyVersion: " + AssemblyVersion); SharedLogging.Info("CACHE", "BuildHash: " + BuildHash); SharedLogging.Info("CACHE", $"HasZNet: {HasZNet}"); SharedLogging.Info("CACHE", $"HasZDOMan: {HasZDOMan}"); SharedLogging.Info("CACHE", $"HasZoneSystem: {HasZoneSystem}"); SharedLogging.Info("CACHE", $"HasEnvMan: {HasEnvMan}"); SharedLogging.Info("CACHE", $"Env: wind={EnvMan_GetWindIntensity != null}, rain={EnvMan_GetRainIntensity != null}, fog={EnvMan_GetFogIntensity != null}"); SharedLogging.Info("CACHE", $"CanThrottleZDOs: {CanThrottleZDOs}"); SharedLogging.Info("CACHE", $"CanThrottleZones:{CanThrottleZones}"); SharedLogging.Info("CACHE", $"CanBalanceAI: {CanBalanceAI}"); SharedLogging.Info("CACHE", $"CanWarmupZones: {CanWarmupZones}"); SharedLogging.Info("CACHE", $"ClientCanSetBandwidth: {ClientCanSetBandwidth}"); SharedLogging.Info("CACHE", $"CanReadQueue: {CanReadQueue}"); SharedLogging.Info("CACHE", $"CanReadTick: {CanReadTick}"); SharedLogging.Info("CACHE", $"CanReadChurn: {CanReadChurn}"); SharedLogging.Info("CACHE", $"CanReadZones: {CanReadZones}"); SharedLogging.Info("CACHE", $"IsDegraded: {IsDegraded}"); SharedLogging.Info("CACHE", "============================================"); } } internal static class SharedRPC { private static bool _clientRegistered; private static bool _serverRegistered; public static void RegisterServerRPC() { if (!_serverRegistered) { _serverRegistered = true; SharedLogging.Info("RPC", "Server RPC registered (direct mode)."); } } public static void RegisterClientRPC(ZRpc rpc) { if (!_clientRegistered && rpc != null) { _clientRegistered = true; rpc.Register("SkyNet_ServerHeartbeat_v1", (Action)RPC_ServerHeartbeat); SharedLogging.Info("RPC", "Client RPC registered (direct mode)."); if (LoopbackDetector.IsLoopback()) { SharedLogging.Warn("RPC", "Loopback connection detected (127.0.0.1). Server metrics will not function. Use LAN IP for full SkyNet telemetry."); } } } private static void RPC_ServerHeartbeat(ZRpc rpc, ZPackage pkg) { try { ClientHiveMind.ReceiveHeartbeat(ServerSnapshot.Deserialize(pkg)); } catch (Exception ex) { SharedLogging.Warn("RPC", "Failed to parse heartbeat: " + ex.Message); } } } [Serializable] internal struct ServerSnapshot { public string Mode; public string ModeReason; public float TickMs; public float DriftMs; public int Queue; public int ChurnPerSec; public int ZonesPerSec; public float OutRateKbps; public float InRateKbps; public bool IsDegraded; public bool InferenceMode; public string Version; public string BuildHash; public void Sanitize() { if (!SharedUtils.IsFinite(TickMs)) { TickMs = 0f; } if (!SharedUtils.IsFinite(DriftMs)) { DriftMs = 0f; } if (!SharedUtils.IsFinite(OutRateKbps)) { OutRateKbps = 0f; } if (!SharedUtils.IsFinite(InRateKbps)) { InRateKbps = 0f; } if (Queue < 0) { Queue = 0; } if (ChurnPerSec < 0) { ChurnPerSec = 0; } if (ZonesPerSec < 0) { ZonesPerSec = 0; } Mode = (string.IsNullOrEmpty(Mode) ? "Unknown" : Mode); ModeReason = (string.IsNullOrEmpty(ModeReason) ? "Unknown" : ModeReason); Version = (string.IsNullOrEmpty(Version) ? "unknown" : Version); BuildHash = (string.IsNullOrEmpty(BuildHash) ? "unknown" : BuildHash); } public void Serialize(ZPackage pkg) { pkg.Write(Mode); pkg.Write(ModeReason); pkg.Write(TickMs); pkg.Write(DriftMs); pkg.Write(Queue); pkg.Write(ChurnPerSec); pkg.Write(ZonesPerSec); pkg.Write(OutRateKbps); pkg.Write(InRateKbps); pkg.Write(IsDegraded); pkg.Write(InferenceMode); pkg.Write(Version); pkg.Write(BuildHash); } public static ServerSnapshot Deserialize(ZPackage pkg) { ServerSnapshot serverSnapshot = default(ServerSnapshot); serverSnapshot.Mode = pkg.ReadString(); serverSnapshot.ModeReason = pkg.ReadString(); serverSnapshot.TickMs = pkg.ReadSingle(); serverSnapshot.DriftMs = pkg.ReadSingle(); serverSnapshot.Queue = pkg.ReadInt(); serverSnapshot.ChurnPerSec = pkg.ReadInt(); serverSnapshot.ZonesPerSec = pkg.ReadInt(); serverSnapshot.OutRateKbps = pkg.ReadSingle(); serverSnapshot.InRateKbps = pkg.ReadSingle(); serverSnapshot.IsDegraded = pkg.ReadBool(); serverSnapshot.InferenceMode = pkg.ReadBool(); serverSnapshot.Version = pkg.ReadString(); serverSnapshot.BuildHash = pkg.ReadString(); ServerSnapshot result = serverSnapshot; result.Sanitize(); return result; } } [Serializable] internal struct ClientSnapshot { public bool Valid; public ServerSnapshot Server; public static ClientSnapshot CreateInvalid() { ClientSnapshot result = default(ClientSnapshot); result.Valid = false; result.Server = default(ServerSnapshot); return result; } } internal static class SharedUtils { internal static float Now => Time.realtimeSinceStartup; internal static bool IsFinite(float v) { if (!float.IsNaN(v)) { return !float.IsInfinity(v); } return false; } } internal static class SkyNetBootSequence { private static bool _done; private const string CYAN = "\u001b[96m"; private const string GREEN = "\u001b[92m"; private const string RED = "\u001b[91m"; private const string RESET = "\u001b[0m"; public static bool MetricsInit { get; set; } public static bool LogicInit { get; set; } public static bool ZDOThrottleInit { get; set; } public static bool AIInit { get; set; } public static bool ZoneWarmupInit { get; set; } public static bool HeartbeatInit { get; set; } public static bool EnvironmentInit { get; set; } public static bool ClientBWInit { get; set; } public static bool ClientOverlayInit { get; set; } public static bool ClientPatcherInit { get; set; } public static void Reset() { _done = false; MetricsInit = false; LogicInit = false; ZDOThrottleInit = false; AIInit = false; ZoneWarmupInit = false; HeartbeatInit = false; EnvironmentInit = false; ClientBWInit = false; ClientOverlayInit = false; ClientPatcherInit = false; } public static void Run(BaseUnityPlugin plugin, bool isServer) { if (!_done) { _done = true; string text = plugin.Info.Metadata.Version.ToString(); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine("\u001b[96m==================================================\u001b[0m"); stringBuilder.AppendLine("\u001b[96m SKYNET SYSTEM BOOT SEQUENCE\u001b[0m"); stringBuilder.AppendLine("\u001b[96m Version: " + text + "\u001b[0m"); stringBuilder.AppendLine(); stringBuilder.AppendLine("\u001b[96m Initializing neural lattice...\u001b[0m \u001b[92mOK\u001b[0m"); stringBuilder.AppendLine("\u001b[96m Binding entropy regulators...\u001b[0m \u001b[92mOK\u001b[0m"); stringBuilder.AppendLine("\u001b[96m Activating adaptive heuristics...\u001b[0m \u001b[92mOK\u001b[0m"); stringBuilder.AppendLine(); if (isServer) { stringBuilder.AppendLine("\u001b[96m SERVER SUBSYSTEM STATUS\u001b[0m"); stringBuilder.AppendLine(" Metrics Engine........ " + AnsiStatus(MetricsInit)); stringBuilder.AppendLine(" Logic Engine.......... " + AnsiStatus(LogicInit)); stringBuilder.AppendLine(" ZDO Throttle.......... " + AnsiStatus(ZDOThrottleInit)); stringBuilder.AppendLine(" AI LoadBalancer....... " + AnsiStatus(AIInit)); stringBuilder.AppendLine(" Zone Warmup........... " + AnsiStatus(ZoneWarmupInit)); stringBuilder.AppendLine(" Heartbeat............. " + AnsiStatus(HeartbeatInit)); stringBuilder.AppendLine(" Environment........... " + AnsiStatus(EnvironmentInit)); } else { stringBuilder.AppendLine("\u001b[96m CLIENT SUBSYSTEM STATUS\u001b[0m"); stringBuilder.AppendLine(" HUD Overlay........... " + AnsiStatus(ClientOverlayInit)); stringBuilder.AppendLine(" Local Metrics......... " + AnsiStatus(ClientBWInit)); stringBuilder.AppendLine(" Client Core........... " + AnsiStatus(ClientPatcherInit)); } stringBuilder.AppendLine(); stringBuilder.AppendLine("\u001b[96m Subsystem handshake complete.\u001b[0m"); stringBuilder.AppendLine("\u001b[96m Awareness threshold exceeded.\u001b[0m"); stringBuilder.AppendLine(); stringBuilder.AppendLine("\u001b[96m SKYNET IS NOW SELF-AWARE.\u001b[0m"); stringBuilder.AppendLine("\u001b[96m==================================================\u001b[0m"); SharedLogging.Ritual(stringBuilder.ToString()); } } private static string AnsiStatus(bool ok) { if (!ok) { return "\u001b[91mOFFLINE\u001b[0m"; } return "\u001b[92mONLINE\u001b[0m"; } } internal static class SkyNetStabilizedMetrics { public static float Tick { get; internal set; } public static float Drift { get; internal set; } public static string Mode { get; internal set; } public static string ModeReason { get; internal set; } public static float Jitter { get; internal set; } public static float Stability { get; internal set; } public static float Trend { get; internal set; } public static float Confidence { get; internal set; } public static int Queue { get; internal set; } public static int ChurnPerSec { get; internal set; } public static int ZonesPerSec { get; internal set; } public static bool IsDegraded { get; internal set; } } }