Please disclose if any significant portion of your mod was created using AI tools by adding the 'AI Generated' category. Failing to do so may result in the mod being removed from Thunderstore.
Decompiled source of SteadyFrame v1.0.1
SteadyFrame.dll
Decompiled a day ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Text; using System.Threading; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using Microsoft.CodeAnalysis; using SteadyFrame.Core; using SteadyFrame.Diagnostics; using SteadyFrame.Housekeeping; using SteadyFrame.SceneStreaming; using SteadyFrame.Terrain; using SteadyFrame.Transitions; using Unity.Collections; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("SteadyFrame")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.1.0")] [assembly: AssemblyInformationalVersion("1.0.1+6965af1c9c6d33c80e1744df0459b6ff7f2e322e")] [assembly: AssemblyProduct("SteadyFrame")] [assembly: AssemblyTitle("SteadyFrame")] [assembly: AssemblyVersion("1.0.1.0")] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [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 SteadyFrame { [BepInPlugin("ru.ivest.steadyframe", "SteadyFrame", "1.0.1")] public class SteadyFramePlugin : BaseUnityPlugin { public const string Guid = "ru.ivest.steadyframe"; public const string Name = "SteadyFrame"; public const string Version = "1.0.1"; internal static ManualLogSource Log; internal static SteadySettings Cfg; internal static SteadyFrame.Core.Module Transitions; internal static SteadyFrame.Core.Module SceneStreaming; internal static SteadyFrame.Core.Module Terrain; internal static SteadyFrame.Core.Module Structures; internal static SteadyFrame.Core.Module Grass; internal static SteadyFrame.Core.Module Housekeeping; internal static SteadyFrame.Core.Module Diagnostics; private static readonly List<SteadyFrame.Core.Module> Modules = new List<SteadyFrame.Core.Module>(); private void Awake() { Log = ((BaseUnityPlugin)this).Logger; bool num = !File.Exists(((BaseUnityPlugin)this).Config.ConfigFilePath); Cfg = new SteadySettings(((BaseUnityPlugin)this).Config); if (num) { LegacyFastLoading.ImportSettings(Cfg); } Modules.Add(Transitions = new SteadyFrame.Core.Module("Transitions", "SteadyFrame.Transitions", Cfg.TransitionsModule)); Modules.Add(SceneStreaming = new SteadyFrame.Core.Module("Object streaming", "SteadyFrame.SceneStreaming", Cfg.SceneStreamingModule, "MidnightsFX.ValheimCommunityPatch", "dev.ontrigger.vpo", "com.Fire.FiresGhettoNetworkMod")); Modules.Add(Terrain = new SteadyFrame.Core.Module("Terrain", "SteadyFrame.Terrain", Cfg.TerrainModule, "MidnightsFX.ValheimCommunityPatch", "dev.ontrigger.vpo", "com.Skarif.ValheimPerformanceOverhaul_WATER")); Modules.Add(Structures = new SteadyFrame.Core.Module("Structures", "SteadyFrame.Structures", Cfg.StructuresModule)); Modules.Add(Grass = new SteadyFrame.Core.Module("Grass", "SteadyFrame.Vegetation", Cfg.GrassModule)); Modules.Add(Housekeeping = new SteadyFrame.Core.Module("Housekeeping", "SteadyFrame.Housekeeping", Cfg.HousekeepingModule, "MidnightsFX.ValheimCommunityPatch")); Modules.Add(Diagnostics = new SteadyFrame.Core.Module("Diagnostics", "SteadyFrame.Diagnostics", null)); } private void Start() { if (LegacyFastLoading.Installed) { Log.LogError((object)"FastLoading is installed as well. SteadyFrame contains it and stays off until BepInEx/plugins/FastLoading.dll is removed."); return; } foreach (SteadyFrame.Core.Module module in Modules) { module.Install(); } foreach (SteadyFrame.Core.Module module2 in Modules) { module2.CheckConflicts(); } } private void Update() { LoadMode.Tick(); LoadProbe.Tick(); if (InstantiateBench.Pending) { ((MonoBehaviour)this).StartCoroutine(InstantiateBench.Run()); } Verification.Tick(); SceneTiming.Tick(); if (Housekeeping.Installed) { CollisionCallbacks.Apply(); } if (Cfg == null || !Cfg.Enabled.Value) { return; } if (Terrain.Installed) { if (LoadMode.JustFinished) { TerrainRebuild.Flush(); TerrainRebuild.BeginCatchUp(); } TerrainRebuild.PumpCatchUp(); } if (Transitions.Installed) { ArrivalGround.Tick(); PortalInterest.Tick(); PortalInterest.ServerTick(); if (PortalWarm.HasTarget && (Object)(object)Player.m_localPlayer == (Object)null) { PortalWarm.Clear(); } } } private void OnDestroy() { Verification.Summary(); foreach (SteadyFrame.Core.Module module in Modules) { module.Harmony.UnpatchSelf(); } } } } namespace SteadyFrame.Vegetation { internal static class GrassRebuild { [HarmonyPatch(typeof(ClutterSystem), "UpdateGrass")] private static class Patch_UpdateGrass { private static void Prefix(ClutterSystem __instance, bool rebuildAll) { _inRebuild = rebuildAll && Active && !ScreenCovered; if (_inRebuild) { _patches = PatchesField.GetValue(__instance) as IDictionary; } _deferred = false; _updateStarted = Stopwatch.GetTimestamp(); } private static void Postfix(ClutterSystem __instance) { if (_deferred) { ForceRebuild.Invoke(__instance) = true; SplitUpdates++; } _inRebuild = (_deferred = false); _patches = null; } } [HarmonyPatch(typeof(ClutterSystem), "GeneratePatch")] private static class Patch_GeneratePatch { private static void Prefix(ClutterSystem __instance, Vector3 camPos, Vector2Int p, ref bool generated, ref bool rebuildAll) { //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Unknown result type (might be due to invalid IL or missing references) if (!_inRebuild || _patches == null || MenuHack.Invoke(__instance) || !generated || (double)(Stopwatch.GetTimestamp() - _updateStarted) * 1000.0 / (double)Stopwatch.Frequency < (double)SteadyFramePlugin.Cfg.GrassBudgetMs.Value || Utils.DistanceXZ(__instance.GetVegPatchCenter(p), camPos) > __instance.m_distance) { return; } object obj = _patches[p]; if (obj == null || Reset.Invoke(obj)) { rebuildAll = false; generated = true; if (obj != null) { Timer.Invoke(obj) = 0f; } _deferred = true; DeferredPatches++; } } } private static readonly FieldRef<ClutterSystem, bool> ForceRebuild = AccessTools.FieldRefAccess<ClutterSystem, bool>("m_forceRebuild"); private static readonly FieldRef<ClutterSystem, bool> MenuHack = AccessTools.FieldRefAccess<ClutterSystem, bool>("m_menuHack"); private static readonly FieldInfo PatchesField = AccessTools.Field(typeof(ClutterSystem), "m_patches"); private static IDictionary _patches; private static readonly Type PatchData = AccessTools.Inner(typeof(ClutterSystem), "PatchData"); private static readonly FieldRef<object, float> Timer = AccessTools.FieldRefAccess<float>(PatchData, "m_timer"); private static readonly FieldRef<object, bool> Reset = AccessTools.FieldRefAccess<bool>(PatchData, "m_reset"); private static long _updateStarted; private static bool _inRebuild; private static bool _deferred; internal static long SplitUpdates; internal static long DeferredPatches; private static bool Active { get { if (SteadyFramePlugin.Cfg != null && SteadyFramePlugin.Cfg.Enabled.Value) { return SteadyFramePlugin.Cfg.GrassBudgetMs.Value > 0f; } return false; } } private static bool ScreenCovered { get { CanvasGroup val = (((Object)(object)Hud.instance != (Object)null) ? Hud.instance.m_loadingScreen : null); if ((Object)(object)val != (Object)null && ((Component)val).gameObject.activeInHierarchy) { return val.alpha >= 0.99f; } return false; } } } } namespace SteadyFrame.Transitions { internal static class ArrivalFloor { private const float VanillaDeadline = 15f; private const float NearRadius = 8f; private static readonly List<ZDO> _temp = new List<ZDO>(); private static bool _armed; private static Vector3 _point; private static float _since; private static float _lastCall; private static float _nextCountAt; private static float _grewAt; private static int _known; private static int _knownAtStart; private static bool _waiting; internal static bool Applied { get; set; } public static int Holds { get; private set; } private static SteadySettings Cfg => SteadyFramePlugin.Cfg; private static bool Enabled { get { if (Cfg != null) { return Cfg.Enabled.Value; } return false; } } public static bool FloorReady(ZoneSystem zones, Vector3 point, out float height) { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_006d: 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_0053: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Unknown result type (might be due to invalid IL or missing references) //IL_00a9: Unknown result type (might be due to invalid IL or missing references) //IL_00fe: Unknown result type (might be due to invalid IL or missing references) height = 0f; if ((Object)(object)zones == (Object)null) { return false; } bool flag = zones.FindFloor(point, ref height); if (!Enabled || !LoadMode.ReadDistantNow()) { _armed = false; _waiting = false; return flag; } float realtimeSinceStartup = Time.realtimeSinceStartup; if (_armed && !(realtimeSinceStartup - _lastCall > 0.5f)) { Vector3 val = point - _point; if (!(((Vector3)(ref val)).sqrMagnitude > 0.01f)) { goto IL_0073; } } Begin(point); goto IL_0073; IL_0073: _lastCall = realtimeSinceStartup; if (!flag) { return false; } if (point.y - height <= Tuning.ArrivalMaxDrop) { Release(); return true; } if (realtimeSinceStartup >= _nextCountAt) { _nextCountAt = realtimeSinceStartup + 0.2f; int num = CountKnown(point); if (num > _known) { _known = num; _grewAt = realtimeSinceStartup; } } float num2 = ((_known > _knownAtStart) ? Tuning.ArrivalQuiet : Tuning.ArrivalFirstWait); if (!(realtimeSinceStartup - _grewAt < num2) && ((Object)(object)ZNetScene.instance == (Object)null || ZNetScene.instance.IsAreaReady(point))) { Release(); return true; } float num3 = Mathf.Clamp(Tuning.ArrivalFloorWait, 0f, 14f); float num4 = LoadMode.ReadTimerNow(Player.m_localPlayer); if (realtimeSinceStartup - _since > num3 || num4 > 14f) { Release(); return true; } _waiting = true; return false; } private static void Begin(Vector3 point) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) _armed = true; _waiting = false; _point = point; _since = Time.realtimeSinceStartup; _grewAt = _since; _nextCountAt = _since + 0.2f; _known = CountKnown(point); _knownAtStart = _known; } private static int CountKnown(Vector3 point) { //IL_0020: 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) //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_004b: 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) if (ZDOMan.instance == null || (Object)(object)ZoneSystem.instance == (Object)null) { return 0; } _temp.Clear(); SectorObjects.FindNeighbourhood(ZoneSystem.GetZone(point), _temp); int num = 0; foreach (ZDO item in _temp) { Vector3 val = item.GetPosition() - point; if (((Vector3)(ref val)).sqrMagnitude <= 64f) { num++; } } return num; } private static void Release() { _armed = false; if (_waiting) { _waiting = false; Holds++; } } } [HarmonyPatch(typeof(Player), "UpdateTeleport")] internal static class Patch_Player_UpdateTeleport_Floor { private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { List<CodeInstruction> list = new List<CodeInstruction>(instructions); MethodInfo methodInfo = AccessTools.Method(typeof(ZoneSystem), "FindFloor", new Type[2] { typeof(Vector3), typeof(float).MakeByRefType() }, (Type[])null); MethodInfo methodInfo2 = AccessTools.Method(typeof(ArrivalFloor), "FloorReady", (Type[])null, (Type[])null); if (methodInfo == null || methodInfo2 == null) { SteadyFramePlugin.Log.LogError((object)"[portal] ZoneSystem.FindFloor unavailable; arrival floor check disabled"); return list; } int num = 0; foreach (CodeInstruction item in list) { if ((item.opcode == OpCodes.Callvirt || item.opcode == OpCodes.Call) && item.operand as MethodInfo == methodInfo) { num++; } } if (num != 1) { SteadyFramePlugin.Log.LogError((object)$"[portal] expected one FindFloor call in UpdateTeleport, found {num}; arrival floor check disabled"); return list; } foreach (CodeInstruction item2 in list) { if ((!(item2.opcode != OpCodes.Callvirt) || !(item2.opcode != OpCodes.Call)) && !(item2.operand as MethodInfo != methodInfo)) { item2.opcode = OpCodes.Call; item2.operand = methodInfo2; break; } } ArrivalFloor.Applied = true; return list; } } internal static class ArrivalGround { private const float RiseMargin = 0.25f; private const float SinkMargin = 0.05f; private const float StrayRadius = 4f; private static FieldRef<Character, Rigidbody> _body; private static FieldRef<Character, float> _maxAir; private static bool _resolved; private static bool _armed; private static Vector3 _point; private static float _baseGround; private static float _until; public static int Lifts { get; private set; } private static SteadySettings Cfg => SteadyFramePlugin.Cfg; private static bool Enabled { get { if (Cfg != null) { return Cfg.Enabled.Value; } return false; } } public static void Tick() { //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_004f: 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_0063: Unknown result type (might be due to invalid IL or missing references) //IL_00a1: Unknown result type (might be due to invalid IL or missing references) //IL_00c3: Unknown result type (might be due to invalid IL or missing references) //IL_00ce: Unknown result type (might be due to invalid IL or missing references) if (!Enabled) { _armed = false; return; } if (LoadMode.JustFinished) { Arm(); } if (!_armed) { return; } Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer == (Object)null || Time.realtimeSinceStartup > _until) { _armed = false; return; } Vector3 position = ((Component)localPlayer).transform.position; Vector2 val = default(Vector2); ((Vector2)(ref val))..ctor(position.x - _point.x, position.z - _point.z); float num = default(float); float num2 = default(float); if (((Vector2)(ref val)).sqrMagnitude > 16f) { _armed = false; } else if (!((Object)(object)ZoneSystem.instance == (Object)null) && ZoneSystem.instance.GetGroundHeight(_point, ref num) && !(num < _baseGround + 0.25f) && ZoneSystem.instance.GetGroundHeight(position, ref num2)) { if (position.y >= num2 - 0.05f) { _armed = false; } else { Lift(localPlayer, num2); } } } private static void Arm() { //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) _armed = false; if (LoadMode.IsDistant && !((Object)(object)ZoneSystem.instance == (Object)null)) { _point = LoadMode.Target; if (ZoneSystem.instance.GetGroundHeight(_point, ref _baseGround)) { _armed = true; _until = Time.realtimeSinceStartup + Mathf.Max(0f, Tuning.ArrivalGroundWatch); } } } private static void Lift(Player player, float ground) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Unknown result type (might be due to invalid IL or missing references) _armed = false; Resolve(); Vector3 position = ((Component)player).transform.position; position.y = ground + 0.1f; ((Component)player).transform.position = position; if (_body != null) { Rigidbody val = _body.Invoke((Character)(object)player); if ((Object)(object)val != (Object)null) { val.linearVelocity = Vector3.zero; } } if (_maxAir != null) { _maxAir.Invoke((Character)(object)player) = position.y; } Lifts++; } private static void Resolve() { if (!_resolved) { _resolved = true; _body = TryField<Rigidbody>("m_body"); _maxAir = TryField<float>("m_maxAirAltitude"); } } private static FieldRef<Character, T> TryField<T>(string name) { try { return AccessTools.FieldRefAccess<Character, T>(name); } catch (Exception ex) { SteadyFramePlugin.Log.LogError((object)("[portal] Character." + name + " unavailable: " + ex.GetType().Name)); return null; } } } internal static class DungeonFade { private static float _fadeOutUntil; internal static float Seconds { get { SteadySettings cfg = SteadyFramePlugin.Cfg; if (cfg == null || !cfg.Enabled.Value) { return 0f; } return Mathf.Clamp(cfg.PortalDungeonFade.Value, 0f, 2f); } } internal static float? Duration(Player player) { float seconds = Seconds; if (seconds <= 0f || (Object)(object)player == (Object)null || ((Character)player).IsDead() || player.IsSleeping()) { return null; } if (((Character)player).IsTeleporting() && !LoadMode.ReadDistantNow()) { _fadeOutUntil = Time.time + seconds; return seconds * 0.8f; } if (!(Time.time < _fadeOutUntil)) { return null; } return seconds; } } [HarmonyPatch(typeof(Hud), "GetFadeDuration")] internal static class Patch_Hud_GetFadeDuration_Dungeon { private static void Postfix(Player player, ref float __result) { float? num = DungeonFade.Duration(player); if (num.HasValue) { __result = num.Value; } } } internal static class LoadMode { private static FieldRef<Player, Vector3> _targetPos; private static FieldRef<Player, Vector3> _fromPos; private static FieldRef<Player, bool> _distant; private static FieldRef<Player, float> _timer; private static bool _resolved; public static bool Teleporting { get; private set; } public static bool Active { get; private set; } public static bool IsDistant { get; private set; } public static Vector3 Target { get; private set; } public static Vector3 From { get; private set; } public static bool HasFrom { get; private set; } public static bool JustStarted { get; private set; } public static bool JustFinished { get; private set; } public static bool ReadDistantNow() { Player localPlayer = Player.m_localPlayer; if (_distant == null || (Object)(object)localPlayer == (Object)null) { return false; } return _distant.Invoke(localPlayer); } public static float ReadTimerNow(Player player) { if (_timer == null || (Object)(object)player == (Object)null) { return -1f; } return _timer.Invoke(player); } private static FieldRef<Player, T> TryField<T>(string name) { try { return AccessTools.FieldRefAccess<Player, T>(name); } catch (Exception ex) { SteadyFramePlugin.Log.LogError((object)("[portal] Player." + name + " unavailable: " + ex.GetType().Name)); return null; } } public static void Tick() { //IL_00ef: Unknown result type (might be due to invalid IL or missing references) //IL_0118: Unknown result type (might be due to invalid IL or missing references) //IL_015c: Unknown result type (might be due to invalid IL or missing references) //IL_014b: Unknown result type (might be due to invalid IL or missing references) if (!_resolved) { _resolved = true; _targetPos = TryField<Vector3>("m_teleportTargetPos"); _fromPos = TryField<Vector3>("m_teleportFromPos"); _distant = TryField<bool>("m_distantTeleport"); _timer = TryField<float>("m_teleportTimer"); if (_targetPos == null) { SteadyFramePlugin.Log.LogError((object)"[portal] Player.m_teleportTargetPos unavailable; portal acceleration disabled"); } if (_distant == null) { SteadyFramePlugin.Log.LogError((object)"[portal] Player.m_distantTeleport unavailable; floor grace applies to all teleports"); } } bool teleporting = Teleporting; Player localPlayer = Player.m_localPlayer; bool flag = (Object)(object)localPlayer != (Object)null && _targetPos != null && ((Character)localPlayer).IsTeleporting(); JustStarted = flag && !teleporting; JustFinished = teleporting && !flag; Teleporting = flag; Active = flag && SteadyFramePlugin.Cfg != null && SteadyFramePlugin.Cfg.Enabled.Value; if (flag) { Target = _targetPos.Invoke(localPlayer); HasFrom = _fromPos != null; if (HasFrom) { From = _fromPos.Invoke(localPlayer); } IsDistant = _distant != null && _distant.Invoke(localPlayer); if (JustStarted && Active) { TerrainPriority.Request(Target); } if (Active) { TerrainPriority.Prioritize(Target); } } } } internal static class PortalInterest { private const string RpcName = "VFB_PortalInterest"; private static readonly Dictionary<long, Vector3> _interest = new Dictionary<long, Vector3>(); private static readonly Dictionary<long, float> _heardAt = new Dictionary<long, float>(); private const float MinInterval = 0.5f; private static readonly List<ZDO> _temp = new List<ZDO>(); private static FieldInfo _peersField; private static FieldInfo _forceSendField; private static FieldInfo _peerRefField; private static bool _resolved; private static ZRoutedRpc _registeredOn; private static Vector3 _lastSent; private static float _nextSendAt; public static int Served { get; private set; } public static int Queued { get; private set; } private static void EnsureRegistered() { //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) ZRoutedRpc instance = ZRoutedRpc.instance; if (instance != null && instance != _registeredOn) { _registeredOn = instance; _lastSent = Vector3.zero; _heardAt.Clear(); instance.Register<Vector3>("VFB_PortalInterest", (Action<long, Vector3>)RPC_Interest); } } public static void Tick() { //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Unknown result type (might be due to invalid IL or missing references) //IL_0095: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_00ad: Unknown result type (might be due to invalid IL or missing references) if (SteadyFramePlugin.Cfg == null || !SteadyFramePlugin.Cfg.Enabled.Value || !SteadyFramePlugin.Cfg.PortalInterestEnabled.Value) { return; } EnsureRegistered(); if (!((Object)(object)ZNet.instance == (Object)null) && !ZNet.instance.IsServer() && ZRoutedRpc.instance != null && PortalWarm.HasTarget && !(Time.realtimeSinceStartup < _nextSendAt)) { Vector3 lastTarget = PortalWarm.LastTarget; Vector3 val = lastTarget - _lastSent; if (!(((Vector3)(ref val)).sqrMagnitude < 1f)) { _nextSendAt = Time.realtimeSinceStartup + 1f; _lastSent = lastTarget; ZRoutedRpc.instance.InvokeRoutedRPC("VFB_PortalInterest", new object[1] { lastTarget }); } } } private static void RPC_Interest(long sender, Vector3 target) { //IL_004c: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)ZNet.instance == (Object)null) && ZNet.instance.IsServer()) { float realtimeSinceStartup = Time.realtimeSinceStartup; if (!_heardAt.TryGetValue(sender, out var value) || !(realtimeSinceStartup - value < 0.5f)) { _heardAt[sender] = realtimeSinceStartup; _interest[sender] = target; } } } private static bool Resolve() { if (_resolved) { return _peersField != null; } _resolved = true; _peersField = AccessTools.Field(typeof(ZDOMan), "m_peers"); Type type = AccessTools.Inner(typeof(ZDOMan), "ZDOPeer"); _forceSendField = ((type != null) ? AccessTools.Field(type, "m_forceSend") : null); _peerRefField = ((type != null) ? AccessTools.Field(type, "m_peer") : null); if (_peersField == null || _forceSendField == null || _peerRefField == null) { SteadyFramePlugin.Log.LogError((object)"[portal] ZDOMan.ZDOPeer layout not recognized; multiplayer destination prefetch disabled"); _peersField = null; return false; } return true; } public static void ServerTick() { //IL_00e2: Unknown result type (might be due to invalid IL or missing references) //IL_00e4: Unknown result type (might be due to invalid IL or missing references) //IL_010e: Unknown result type (might be due to invalid IL or missing references) if (SteadyFramePlugin.Cfg == null || !SteadyFramePlugin.Cfg.Enabled.Value || !SteadyFramePlugin.Cfg.PortalInterestEnabled.Value || _interest.Count == 0 || (Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsServer() || ZDOMan.instance == null || !Resolve()) { return; } if (!(_peersField.GetValue(ZDOMan.instance) is IList list)) { _interest.Clear(); return; } foreach (object item in list) { object? value = _peerRefField.GetValue(item); ZNetPeer val = (ZNetPeer)((value is ZNetPeer) ? value : null); if (val == null || !_interest.TryGetValue(val.m_uid, out var value2) || !(_forceSendField.GetValue(item) is HashSet<ZDOID> hashSet)) { continue; } _temp.Clear(); SectorObjects.FindNeighbourhood(ZoneSystem.GetZone(value2), _temp); foreach (ZDO item2 in _temp) { if (hashSet.Add(item2.m_uid)) { Queued++; } } Served++; SendBoost.Open(val.m_uid); } _interest.Clear(); } } [HarmonyPatch(typeof(Hud), "UpdateBlackScreen")] internal static class Patch_Hud_UpdateBlackScreen_Portal { private static void Postfix(Hud __instance, Player player) { SteadySettings cfg = SteadyFramePlugin.Cfg; if (cfg != null && cfg.Enabled.Value && !((Object)(object)player == (Object)null) && player.ShowTeleportAnimation() && !((Object)(object)__instance.m_loadingScreen == (Object)null)) { __instance.m_loadingScreen.alpha = 1f; } } } internal static class PortalWarm { private static FieldRef<TeleportWorld, ZNetView> _nview; private static bool _resolved; private static TeleportWorld _chosen; private static float _chosenDist; private const float SwitchMargin = 0.8f; private static readonly Dictionary<TeleportWorld, Vector3> _targets = new Dictionary<TeleportWorld, Vector3>(); private static readonly List<TeleportWorld> _stale = new List<TeleportWorld>(); public static Vector3 LastTarget { get; private set; } public static bool HasTarget { get; private set; } public static int Warms { get; private set; } private static void PruneStale() { _stale.Clear(); foreach (TeleportWorld key in _targets.Keys) { if ((Object)(object)key == (Object)null || !Object.op_Implicit((Object)(object)key)) { _stale.Add(key); } } foreach (TeleportWorld item in _stale) { _targets.Remove(item); } } public static void Consider(TeleportWorld portal) { //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0108: Unknown result type (might be due to invalid IL or missing references) //IL_010d: Unknown result type (might be due to invalid IL or missing references) //IL_010f: Unknown result type (might be due to invalid IL or missing references) //IL_0111: Unknown result type (might be due to invalid IL or missing references) //IL_0123: Unknown result type (might be due to invalid IL or missing references) //IL_013f: Unknown result type (might be due to invalid IL or missing references) //IL_0144: Unknown result type (might be due to invalid IL or missing references) //IL_015a: Unknown result type (might be due to invalid IL or missing references) //IL_0135: Unknown result type (might be due to invalid IL or missing references) //IL_0163: Unknown result type (might be due to invalid IL or missing references) //IL_01bf: Unknown result type (might be due to invalid IL or missing references) if (SteadyFramePlugin.Cfg == null || !SteadyFramePlugin.Cfg.Enabled.Value) { return; } Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer == (Object)null || (Object)(object)portal == (Object)null) { return; } PruneStale(); float warmRadius = Tuning.WarmRadius; float num = Vector3.Distance(((Component)localPlayer).transform.position, ((Component)portal).transform.position); if (num > warmRadius) { _targets.Remove(portal); if ((Object)(object)_chosen == (Object)(object)portal) { _chosen = null; HasTarget = false; } return; } if (!_resolved) { _resolved = true; try { _nview = AccessTools.FieldRefAccess<TeleportWorld, ZNetView>("m_nview"); } catch (Exception ex) { SteadyFramePlugin.Log.LogError((object)("[portal] TeleportWorld.m_nview unavailable (" + ex.GetType().Name + "); destination warming disabled")); _nview = null; } } if (_nview == null || ZDOMan.instance == null) { return; } ZNetView val = _nview.Invoke(portal); ZDO val2 = (((Object)(object)val != (Object)null) ? val.GetZDO() : null); if (val2 == null) { return; } ZDOID connectionZDOID = val2.GetConnectionZDOID((ConnectionType)1); if (connectionZDOID == ZDOID.None) { return; } ZDO zDO = ZDOMan.instance.GetZDO(connectionZDOID); if (zDO == null) { ZDOMan.instance.RequestZDO(connectionZDOID); return; } Vector3 position = zDO.GetPosition(); bool num2 = !_targets.ContainsKey(portal); _targets[portal] = position; if (num2) { TerrainPriority.Request(position); Warms++; } if ((Object)(object)_chosen == (Object)(object)portal) { _chosenDist = num; } else { if ((Object)(object)_chosen != (Object)null && Object.op_Implicit((Object)(object)_chosen) && num >= _chosenDist * 0.8f) { return; } _chosen = portal; _chosenDist = num; } LastTarget = position; HasTarget = true; } public static void Clear() { HasTarget = false; _chosen = null; _targets.Clear(); } } [HarmonyPatch(typeof(TeleportWorld), "UpdatePortal")] internal static class Patch_TeleportWorld_UpdatePortal { private static void Postfix(TeleportWorld __instance) { PortalWarm.Consider(__instance); } } internal static class SendBoost { internal const int Vanilla = 10240; private const int MaxFactor = 16; private const int Ceiling = 262144; private static readonly Dictionary<long, float> _until = new Dictionary<long, float>(); internal static readonly FieldRef<object, ZNetPeer> PeerOf = ResolvePeer(); internal static bool Applied { get; set; } private static FieldRef<object, ZNetPeer> ResolvePeer() { Type type = AccessTools.Inner(typeof(ZDOMan), "ZDOPeer"); try { return (type != null) ? AccessTools.FieldRefAccess<ZNetPeer>(type, "m_peer") : null; } catch (Exception) { return null; } } public static void Open(long uid) { if (SteadyFramePlugin.Cfg != null) { _until[uid] = Time.realtimeSinceStartup + Mathf.Max(0f, Tuning.SendBoostSeconds); } } public static int Budget(int window, object peer) { if (window <= 0 || _until.Count == 0 || peer == null || PeerOf == null || SteadyFramePlugin.Cfg == null || !SteadyFramePlugin.Cfg.Enabled.Value || !SteadyFramePlugin.Cfg.PortalSendBoost.Value) { return window; } ZNetPeer val = PeerOf.Invoke(peer); if (val == null || !_until.TryGetValue(val.m_uid, out var value)) { return window; } if (Time.realtimeSinceStartup > value) { _until.Remove(val.m_uid); return window; } return (int)Math.Min((long)window * (long)Mathf.Clamp(Tuning.SendBoostFactor, 1, 16), Math.Max(window, 262144)); } } [HarmonyPatch(typeof(ZDOMan), "SendZDOs")] internal static class Patch_ZDOMan_SendZDOs_Boost { private static readonly OpCode[] Small = new OpCode[9] { OpCodes.Ldc_I4_0, OpCodes.Ldc_I4_1, OpCodes.Ldc_I4_2, OpCodes.Ldc_I4_3, OpCodes.Ldc_I4_4, OpCodes.Ldc_I4_5, OpCodes.Ldc_I4_6, OpCodes.Ldc_I4_7, OpCodes.Ldc_I4_8 }; private static readonly OpCode[] Compares = new OpCode[20] { OpCodes.Ble, OpCodes.Ble_S, OpCodes.Ble_Un, OpCodes.Ble_Un_S, OpCodes.Bgt, OpCodes.Bgt_S, OpCodes.Bgt_Un, OpCodes.Bgt_Un_S, OpCodes.Bge, OpCodes.Bge_S, OpCodes.Bge_Un, OpCodes.Bge_Un_S, OpCodes.Blt, OpCodes.Blt_S, OpCodes.Blt_Un, OpCodes.Blt_Un_S, OpCodes.Cgt, OpCodes.Cgt_Un, OpCodes.Clt, OpCodes.Clt_Un }; private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions, MethodBase original) { //IL_00e3: Unknown result type (might be due to invalid IL or missing references) //IL_00e9: Expected O, but got Unknown List<CodeInstruction> list = new List<CodeInstruction>(instructions); MethodInfo methodInfo = AccessTools.Method(typeof(SendBoost), "Budget", (Type[])null, (Type[])null); int num = PeerArgument(original); if (methodInfo == null || SendBoost.PeerOf == null || num < 0) { SteadyFramePlugin.Log.LogError((object)"[portal] SendZDOs peer or send budget hook unavailable; send boost disabled"); return list; } int num2 = QueueLocal(list); int num3 = BudgetSite(list, num2); if (num3 < 0) { SteadyFramePlugin.Log.LogError((object)"[portal] the round budget in SendZDOs is not a plain value minus the send queue size; another mod has rewritten the method; send boost disabled"); return list; } int num4 = ((num2 < 0) ? (-1) : GateSite(list, num2)); string text = Describe(list[num3]); List<int> list2 = new List<int> { num3 }; if (num4 >= 0) { list2.Add(num4); } list2.Sort(); for (int num5 = list2.Count - 1; num5 >= 0; num5--) { list.InsertRange(list2[num5] + 1, (IEnumerable<CodeInstruction>)(object)new CodeInstruction[2] { LoadArgument(num), new CodeInstruction(OpCodes.Call, (object)methodInfo) }); } if (num4 < 0) { SteadyFramePlugin.Log.LogWarning((object)("[portal] send boost raises the round budget of " + text + " only: the round threshold in SendZDOs is not a comparison against a plain value; another mod has changed it")); } else if (text != 10240.ToString()) { SteadyFramePlugin.Log.LogInfo((object)($"[portal] send window is {text}, not the vanilla {10240}; " + "send boost multiplies what is there")); } SendBoost.Applied = true; return list; } private static int QueueLocal(List<CodeInstruction> code) { for (int i = 0; i + 1 < code.Count; i++) { if (!(code[i].opcode != OpCodes.Callvirt) || !(code[i].opcode != OpCodes.Call)) { MethodInfo methodInfo = code[i].operand as MethodInfo; if (!(methodInfo == null) && !(methodInfo.Name != "GetSendQueueSize") && TryStore(code[i + 1], out var local)) { return local; } } } return -1; } private static int BudgetSite(List<CodeInstruction> code, int queue) { int num = -1; int num2 = 0; for (int i = 0; i + 2 < code.Count; i++) { if (IsWindow(code[i]) && TryLoad(code[i + 1], out var local) && (queue < 0 || local == queue) && (!(code[i + 2].opcode != OpCodes.Sub) || !(code[i + 2].opcode != OpCodes.Sub_Ovf))) { num2++; if (num < 0) { num = i; } } } if (queue >= 0 || num2 == 1) { return num; } return -1; } private static int GateSite(List<CodeInstruction> code, int queue) { for (int i = 0; i + 2 < code.Count; i++) { if (!TryLoad(code[i], out var local) || local != queue || !IsWindow(code[i + 1])) { continue; } OpCode[] compares = Compares; foreach (OpCode opCode in compares) { if (code[i + 2].opcode == opCode) { return i + 1; } } } return -1; } private static int PeerArgument(MethodBase method) { Type type = AccessTools.Inner(typeof(ZDOMan), "ZDOPeer"); if (method == null || type == null) { return -1; } ParameterInfo[] parameters = method.GetParameters(); foreach (ParameterInfo parameterInfo in parameters) { if (parameterInfo.ParameterType == type) { return parameterInfo.Position + ((!method.IsStatic) ? 1 : 0); } } return -1; } private static CodeInstruction LoadArgument(int index) { //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Expected O, but got Unknown //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Expected O, but got Unknown //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Expected O, but got Unknown //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Expected O, but got Unknown //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Expected O, but got Unknown return (CodeInstruction)(index switch { 0 => (object)new CodeInstruction(OpCodes.Ldarg_0, (object)null), 1 => (object)new CodeInstruction(OpCodes.Ldarg_1, (object)null), 2 => (object)new CodeInstruction(OpCodes.Ldarg_2, (object)null), 3 => (object)new CodeInstruction(OpCodes.Ldarg_3, (object)null), _ => (object)new CodeInstruction(OpCodes.Ldarg_S, (object)(byte)index), }); } private static bool IsWindow(CodeInstruction ins) { if (TryConst(ins, out var _)) { return true; } if (ins.opcode == OpCodes.Ldsfld) { return (ins.operand as FieldInfo)?.FieldType == typeof(int); } if (ins.opcode == OpCodes.Call && ins.operand is MethodInfo methodInfo) { if (methodInfo.IsStatic && methodInfo.ReturnType == typeof(int)) { return methodInfo.GetParameters().Length == 0; } return false; } return false; } private static string Describe(CodeInstruction ins) { if (TryConst(ins, out var value)) { return value.ToString(); } if (ins.operand is MemberInfo memberInfo) { return memberInfo.DeclaringType?.Name + "." + memberInfo.Name; } return ins.opcode.Name; } private static bool TryConst(CodeInstruction ins, out int value) { value = 0; if (ins.opcode == OpCodes.Ldc_I4 || ins.opcode == OpCodes.Ldc_I4_S) { if (ins.operand == null) { return false; } value = Convert.ToInt32(ins.operand); return true; } for (int i = 0; i < Small.Length; i++) { if (ins.opcode == Small[i]) { value = i; return true; } } if (ins.opcode == OpCodes.Ldc_I4_M1) { value = -1; return true; } return false; } private static bool TryLoad(CodeInstruction ins, out int local) { return Local(ins, out local, OpCodes.Ldloc, OpCodes.Ldloc_S, OpCodes.Ldloc_0, OpCodes.Ldloc_1, OpCodes.Ldloc_2, OpCodes.Ldloc_3); } private static bool TryStore(CodeInstruction ins, out int local) { return Local(ins, out local, OpCodes.Stloc, OpCodes.Stloc_S, OpCodes.Stloc_0, OpCodes.Stloc_1, OpCodes.Stloc_2, OpCodes.Stloc_3); } private static bool Local(CodeInstruction ins, out int local, OpCode full, OpCode compact, OpCode zero, OpCode one, OpCode two, OpCode three) { local = -1; if (ins.opcode == zero) { local = 0; } else if (ins.opcode == one) { local = 1; } else if (ins.opcode == two) { local = 2; } else if (ins.opcode == three) { local = 3; } else if (ins.opcode == full || ins.opcode == compact) { local = Index(ins.operand); } return local >= 0; } private static int Index(object operand) { if (operand is LocalVariableInfo localVariableInfo) { return localVariableInfo.LocalIndex; } if (operand is int) { return (int)operand; } if (operand is short) { return (short)operand; } if (operand is byte) { return (byte)operand; } return -1; } } internal static class TeleportCooldown { private const float Vanilla = 2f; internal static bool Applied { get; set; } public static float Seconds() { if (SteadyFramePlugin.Cfg == null || !SteadyFramePlugin.Cfg.Enabled.Value) { return 2f; } return Mathf.Clamp(SteadyFramePlugin.Cfg.PortalCooldown.Value, 0.1f, 2f); } } [HarmonyPatch(typeof(Player), "TeleportTo")] internal static class Patch_Player_TeleportTo_Cooldown { private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { List<CodeInstruction> list = new List<CodeInstruction>(instructions); FieldInfo fieldInfo = AccessTools.Field(typeof(Player), "m_teleportCooldown"); MethodInfo methodInfo = AccessTools.Method(typeof(TeleportCooldown), "Seconds", (Type[])null, (Type[])null); if (fieldInfo == null || methodInfo == null) { SteadyFramePlugin.Log.LogError((object)"[portal] Player.m_teleportCooldown unavailable; cooldown unchanged"); return list; } int num = 0; for (int i = 0; i < list.Count - 1; i++) { if (!(list[i].opcode != OpCodes.Ldfld) && !(list[i].operand as FieldInfo != fieldInfo)) { CodeInstruction val = list[i + 1]; if (!(val.opcode != OpCodes.Ldc_R4) && val.operand is float num2 && Mathf.Approximately(num2, 2f)) { val.opcode = OpCodes.Call; val.operand = methodInfo; num++; } } } if (num != 1) { SteadyFramePlugin.Log.LogError((object)$"[portal] expected one cooldown comparison in TeleportTo, found {num}; cooldown may be unchanged"); return list; } TeleportCooldown.Applied = true; return list; } } internal static class TeleportGates { private const float VanillaFloorGate = 2f; private const float VanillaDistantGate = 8f; private static bool Enabled { get { if (SteadyFramePlugin.Cfg != null) { return SteadyFramePlugin.Cfg.Enabled.Value; } return false; } } internal static bool AbortGuarded { get; set; } public static float FloorGrace() { if (!Enabled) { return 2f; } if (LoadMode.ReadDistantNow()) { return 0f; } return Mathf.Max(DungeonFade.Seconds, AbortGuarded ? 0f : Tuning.FloorGrace); } public static bool KeepWaiting(Player player) { bool flag = LoadMode.ReadDistantNow(); if (flag || !Enabled) { return flag; } float num = LoadMode.ReadTimerNow(player); if (num < 0f) { return false; } return num <= Tuning.FloorGrace + DungeonFade.Seconds; } public static float DistantGate() { if (!Enabled || !ArrivalFloor.Applied) { return 8f; } return 0f; } internal static int Count(List<CodeInstruction> code, float value) { int num = 0; foreach (CodeInstruction item in code) { if (item.opcode == OpCodes.Ldc_R4 && item.operand is float num2 && num2 == value) { num++; } } return num; } internal static bool Replace(List<CodeInstruction> code, float value, string hookName) { MethodInfo methodInfo = AccessTools.Method(typeof(TeleportGates), hookName, (Type[])null, (Type[])null); if (methodInfo == null) { return false; } foreach (CodeInstruction item in code) { if (!(item.opcode != OpCodes.Ldc_R4) && item.operand is float num && num == value) { item.opcode = OpCodes.Call; item.operand = methodInfo; return true; } } return false; } } [HarmonyPatch(typeof(Player), "UpdateTeleport")] internal static class Patch_Player_UpdateTeleport { private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { List<CodeInstruction> list = new List<CodeInstruction>(instructions); int num = TeleportGates.Count(list, 2f); int num2 = TeleportGates.Count(list, 8f); if (num != 1 || num2 != 1) { SteadyFramePlugin.Log.LogError((object)$"[portal] expected one 2f and one 8f gate in UpdateTeleport, found {num} and {num2}; gates unchanged"); return list; } TeleportGates.Replace(list, 2f, "FloorGrace"); TeleportGates.Replace(list, 8f, "DistantGate"); TeleportGates.AbortGuarded = GuardAbortBranch(list); return list; } private static bool GuardAbortBranch(List<CodeInstruction> code) { FieldInfo fieldInfo = AccessTools.Field(typeof(Player), "m_distantTeleport"); MethodInfo methodInfo = AccessTools.Method(typeof(TeleportGates), "KeepWaiting", (Type[])null, (Type[])null); if (fieldInfo == null || methodInfo == null) { return false; } int num = -1; for (int i = 0; i < code.Count; i++) { if (code[i].opcode == OpCodes.Ldc_R4 && code[i].operand is float num2 && num2 == 15f) { num = i; break; } } if (num < 0) { SteadyFramePlugin.Log.LogError((object)"[portal] 15f timeout missing from UpdateTeleport; rollback guard unavailable"); return false; } for (int j = num; j < code.Count; j++) { if (!(code[j].opcode != OpCodes.Ldfld) && code[j].operand == fieldInfo) { code[j].opcode = OpCodes.Call; code[j].operand = methodInfo; return true; } } SteadyFramePlugin.Log.LogError((object)"[portal] m_distantTeleport read after 15f not found; rollback guard unavailable"); return false; } } } namespace SteadyFrame.Terrain { internal static class GhostZones { public static int Held { get; private set; } private static bool Enabled { get { if (SteadyFramePlugin.Cfg != null) { return SteadyFramePlugin.Cfg.Enabled.Value; } return false; } } public static bool Allow(Vector3 refPoint) { //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) if (!Enabled || !LoadMode.Active || (Object)(object)ZNet.instance == (Object)null) { return true; } Vector2s zone = ZoneSystem.GetZone(ZNet.instance.GetReferencePosition()); if (ZoneSystem.GetZone(refPoint) != zone) { return true; } Held++; return false; } } [HarmonyPatch(typeof(ZoneSystem), "CreateGhostZones")] internal static class Patch_ZoneSystem_CreateGhostZones { private static bool Prefix(Vector3 refPoint, ref bool __result) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) if (GhostZones.Allow(refPoint)) { return true; } __result = false; return false; } } internal static class TerrainCache { private readonly struct Key { private readonly int _x; private readonly int _z; private readonly int _width; private readonly float _scale; private readonly bool _lod; public Key(Vector3 center, int width, float scale, bool lod) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) _x = Mathf.RoundToInt(center.x); _z = Mathf.RoundToInt(center.z); _width = width; _scale = scale; _lod = lod; } public override int GetHashCode() { return (((((((_x * 397) ^ _z) * 397) ^ _width) * 397) ^ _scale.GetHashCode()) * 397) ^ (_lod ? 1 : 0); } public override bool Equals(object obj) { if (obj is Key key && key._x == _x && key._z == _z && key._width == _width && key._scale == _scale) { return key._lod == _lod; } return false; } } private struct Entry { public HMBuildData Data; public long Stamp; } private static readonly Dictionary<Key, Entry> _entries = new Dictionary<Key, Entry>(); private static readonly List<Key> _victims = new List<Key>(); private static long _clock; private static WorldGenerator _worldGen; public static int Hits { get; private set; } public static int Misses { get; private set; } public static int Count => _entries.Count; private static bool Enabled { get { if (SteadyFramePlugin.Cfg != null) { return SteadyFramePlugin.Cfg.Enabled.Value; } return false; } } internal static int Limit => AutoLimit(SystemInfo.systemMemorySize); internal static int AutoLimit(int memoryMB) { if (memoryMB < 30000) { if (memoryMB < 15000) { if (memoryMB < 11000) { return 256; } return 512; } return 1024; } return 2048; } public static void Clear() { _entries.Clear(); _worldGen = null; } private static bool Usable(WorldGenerator worldGen) { if (!Enabled || worldGen == null) { return false; } if (_worldGen != worldGen) { Clear(); _worldGen = worldGen; } return true; } public static bool TryGet(Vector3 center, int width, float scale, bool lod, WorldGenerator worldGen, out HMBuildData data) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) data = null; if (!Usable(worldGen)) { return false; } Key key = new Key(center, width, scale, lod); if (!_entries.TryGetValue(key, out var value)) { Misses++; return false; } value.Stamp = ++_clock; _entries[key] = value; data = value.Data; Hits++; return true; } public static void Store(Vector3 center, int width, float scale, bool lod, WorldGenerator worldGen, HMBuildData data) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) if (data != null && Usable(worldGen)) { Key key = new Key(center, width, scale, lod); _entries[key] = new Entry { Data = data, Stamp = ++_clock }; int num = Mathf.Max(16, Limit); if (_entries.Count > num) { Evict(_entries.Count - num * 3 / 4); } } } private static void Evict(int count) { if (count > 0) { _victims.Clear(); _victims.AddRange(_entries.Keys); _victims.Sort((Key a, Key b) => _entries[a].Stamp.CompareTo(_entries[b].Stamp)); for (int num = 0; num < count && num < _victims.Count; num++) { _entries.Remove(_victims[num]); } _victims.Clear(); } } } [HarmonyPatch(typeof(HeightmapBuilder), "RequestTerrain")] internal static class Patch_HeightmapBuilder_RequestTerrain_Cache { private static bool Prefix(Vector3 center, int width, float scale, bool distantLod, WorldGenerator worldGen, ref HMBuildData __result) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) if (!TerrainCache.TryGet(center, width, scale, distantLod, worldGen, out var data)) { return true; } __result = data; return false; } private static void Postfix(Vector3 center, int width, float scale, bool distantLod, WorldGenerator worldGen, HMBuildData __result) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) TerrainCache.Store(center, width, scale, distantLod, worldGen, __result); } } [HarmonyPatch(typeof(HeightmapBuilder), "IsTerrainReady")] internal static class Patch_HeightmapBuilder_IsTerrainReady_Cache { private static bool Prefix(Vector3 center, int width, float scale, bool distantLod, WorldGenerator worldGen, ref bool __result) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) if (!TerrainCache.TryGet(center, width, scale, distantLod, worldGen, out var _)) { return true; } __result = true; return false; } } [HarmonyPatch(typeof(ZoneSystem), "OnDestroy")] internal static class Patch_ZoneSystem_OnDestroy_Cache { private static void Postfix() { TerrainCache.Clear(); } } [HarmonyPatch(typeof(TerrainModifier), "PokeHeightmaps")] internal static class Patch_TerrainModifier_PaintOnly { private static readonly FieldInfo TriggerOnPlaced = AccessTools.Field(typeof(TerrainModifier), "m_triggerOnPlaced"); private static bool Enabled { get { if (SteadyFramePlugin.Cfg != null) { return SteadyFramePlugin.Cfg.Enabled.Value; } return false; } } private static bool Prepare() { return TriggerOnPlaced != null; } private static bool Prefix(TerrainModifier __instance, bool forcedDelay) { //IL_0094: Unknown result type (might be due to invalid IL or missing references) if (!Enabled || __instance.m_level || __instance.m_smooth || !__instance.m_paintCleared) { return true; } bool flag = !(bool)TriggerOnPlaced.GetValue(null) || forcedDelay; foreach (Heightmap allHeightmap in Heightmap.GetAllHeightmaps()) { if (allHeightmap.TerrainVSModifier(__instance)) { allHeightmap.Poke(flag ? 2 : 0, true); } } if ((Object)(object)ClutterSystem.instance != (Object)null) { ClutterSystem.instance.ResetGrass(((Component)__instance).transform.position, __instance.GetRadius()); } return false; } } [HarmonyPatch(typeof(Heightmap), "CustomLateUpdate")] internal static class Patch_Heightmap_CoalescePaint { private const float Interval = 0.5f; private const float NearDistance = 32f; private static readonly FieldInfo Request = AccessTools.Field(typeof(Heightmap), "m_regenRequest"); private static readonly Dictionary<Heightmap, float> LastRebuild = new Dictionary<Heightmap, float>(); private static readonly List<Heightmap> Dead = new List<Heightmap>(); private static bool Enabled { get { if (SteadyFramePlugin.Cfg != null) { return SteadyFramePlugin.Cfg.Enabled.Value; } return false; } } private static bool Prepare() { return Request != null; } private static bool Prefix(Heightmap __instance) { if (__instance.m_doLateUpdate != 2 || !Enabled || Convert.ToInt32(Request.GetValue(__instance)) != 0) { return true; } float unscaledTime = Time.unscaledTime; if (!LastRebuild.TryGetValue(__instance, out var value) || unscaledTime - value >= 0.5f || Near(__instance)) { Remember(__instance, unscaledTime); return true; } return false; } private static bool Near(Heightmap heightmap) { //IL_0017: 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_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_0061: 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) Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer == (Object)null) { return true; } Vector3 position = ((Component)localPlayer).transform.position; Vector3 position2 = ((Component)heightmap).transform.position; float num = (float)heightmap.m_width * heightmap.m_scale * 0.5f; float num2 = Mathf.Max(0f, Mathf.Abs(position.x - position2.x) - num); float num3 = Mathf.Max(0f, Mathf.Abs(position.z - position2.z) - num); return num2 * num2 + num3 * num3 < 1024f; } private static void Remember(Heightmap heightmap, float now) { LastRebuild[heightmap] = now; if (LastRebuild.Count < 256) { return; } Dead.Clear(); foreach (KeyValuePair<Heightmap, float> item in LastRebuild) { if ((Object)(object)item.Key == (Object)null || now - item.Value > 60f) { Dead.Add(item.Key); } } foreach (Heightmap item2 in Dead) { LastRebuild.Remove(item2); } } } internal static class TerrainPriority { private const int VanillaSleepMs = 10; private static FieldInfo _toBuildField; private static FieldInfo _lockField; private static bool _resolved; private static int _width; private static float _scale; private static bool _distantLod; private static bool _zoneParamsKnown; public static int Requested { get; private set; } public static int Promoted { get; private set; } public static int QueueDepth { get { if (!Resolve() || HeightmapBuilder.instance == null) { return -1; } object value = _lockField.GetValue(HeightmapBuilder.instance); if (!(_toBuildField.GetValue(HeightmapBuilder.instance) is ICollection collection) || value == null) { return -1; } lock (value) { return collection.Count; } } } public static int SleepMs() { if (!LoadMode.Active) { return 10; } if (QueueDepth <= 0) { return 10; } return 0; } private static bool ResolveZoneParams() { if (_zoneParamsKnown) { return true; } ZoneSystem instance = ZoneSystem.instance; if ((Object)(object)instance == (Object)null || (Object)(object)instance.m_zonePrefab == (Object)null) { return false; } Heightmap componentInChildren = instance.m_zonePrefab.GetComponentInChildren<Heightmap>(); if ((Object)(object)componentInChildren == (Object)null) { return false; } _width = componentInChildren.m_width; _scale = componentInChildren.m_scale; _distantLod = componentInChildren.IsDistantLod; _zoneParamsKnown = true; return true; } public static void Request(Vector3 center) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0017: 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_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Unknown result type (might be due to invalid IL or missing references) //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) //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) if (!ResolveZoneParams() || WorldGenerator.instance == null || HeightmapBuilder.instance == null) { return; } Vector2s zone = ZoneSystem.GetZone(center); for (int i = zone.y - 1; i <= zone.y + 1; i++) { for (int j = zone.x - 1; j <= zone.x + 1; j++) { Vector3 zonePos = ZoneSystem.GetZonePos(new Vector2s(j, i)); HeightmapBuilder.instance.IsTerrainReady(zonePos, _width, _scale, _distantLod, WorldGenerator.instance); Requested++; } } } private static bool Resolve() { if (_resolved) { if (_toBuildField != null) { return _lockField != null; } return false; } _resolved = true; _toBuildField = AccessTools.Field(typeof(HeightmapBuilder), "m_toBuild"); _lockField = AccessTools.Field(typeof(HeightmapBuilder), "m_lock"); if (_toBuildField == null || _lockField == null) { SteadyFramePlugin.Log.LogError((object)"[portal] HeightmapBuilder fields unavailable; terrain queue priority disabled"); _toBuildField = null; return false; } return true; } public static void Prioritize(Vector3 center) { //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_0065: 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_006e: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Unknown result type (might be due to invalid IL or missing references) if (!Resolve() || HeightmapBuilder.instance == null) { return; } object value = _lockField.GetValue(HeightmapBuilder.instance); IList<HMBuildData> list = _toBuildField.GetValue(HeightmapBuilder.instance) as IList<HMBuildData>; if (value == null || list == null) { return; } Vector2s zone = ZoneSystem.GetZone(center); Monitor.Enter(value); try { int num = 0; for (int i = 0; i < list.Count; i++) { HMBuildData val = list[i]; Vector2s zone2 = ZoneSystem.GetZone(val.m_center); if (Math.Abs(zone2.x - zone.x) <= 1 && Math.Abs(zone2.y - zone.y) <= 1) { if (i == num) { num++; continue; } list.RemoveAt(i); list.Insert(num, val); num++; Promoted++; } } } finally { Monitor.Exit(value); } } } [HarmonyPatch(typeof(HeightmapBuilder), "BuildThread")] internal static class Patch_HeightmapBuilder_BuildThread { private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { List<CodeInstruction> list = new List<CodeInstruction>(instructions); MethodInfo operand = AccessTools.Method(typeof(TerrainPriority), "SleepMs", (Type[])null, (Type[])null); int num = 0; foreach (CodeInstruction item in list) { if ((item.opcode == OpCodes.Ldc_I4 || item.opcode == OpCodes.Ldc_I4_S) && item.operand != null && Convert.ToInt32(item.operand) == 10) { num++; } } if (num != 1) { SteadyFramePlugin.Log.LogError((object)$"[portal] expected one sleep constant of 10 in BuildThread, found {num}; sleep unchanged"); return list; } foreach (CodeInstruction item2 in list) { if ((!(item2.opcode != OpCodes.Ldc_I4) || !(item2.opcode != OpCodes.Ldc_I4_S)) && item2.operand != null && Convert.ToInt32(item2.operand) == 10) { item2.opcode = OpCodes.Call; item2.operand = operand; break; } } return list; } } internal static class TerrainRebuild { private static readonly HashSet<Heightmap> _rebuilt = new HashSet<Heightmap>(); private static bool _flushing; private static float _catchUpUntil; private static int _frame; private static int _thisFrame; internal static bool CatchingUp => Time.realtimeSinceStartup <= _catchUpUntil; public static int Deferred { get; private set; } public static int Flushed { get; private set; } public static int DeferredNow { get; private set; } public static int AllowedNow { get; private set; } public static int TouchedNow => _rebuilt.Count; public static bool Skipped { get; private set; } private static bool Enabled { get { if (SteadyFramePlugin.Cfg != null && SteadyFramePlugin.Cfg.Enabled.Value) { return Tuning.DeferTerrainRebuilds; } return false; } } public static void BeginCatchUp() { if (SteadyFramePlugin.Cfg != null) { _catchUpUntil = Time.realtimeSinceStartup + Mathf.Max(0f, Tuning.CatchUpSeconds); } } public static void ResetRun() { DeferredNow = 0; AllowedNow = 0; _rebuilt.Clear(); } public static bool Allow(Heightmap hmap) { Skipped = false; if (_flushing || (Object)(object)hmap == (Object)null || SteadyFramePlugin.Cfg == null || !SteadyFramePlugin.Cfg.Enabled.Value) { return true; } if (!LoadMode.Active) { return AllowCatchUp(hmap); } if (!Tuning.DeferTerrainRebuilds) { return true; } if (_rebuilt.Add(hmap)) { AllowedNow++; return true; } Skipped = true; DeferredNow++; MarkPending(hmap); Deferred++; return false; } private static void MarkPending(Heightmap hmap) { hmap.m_doLateUpdate = 2; } public static void PumpCatchUp() { if (SteadyFramePlugin.Cfg == null || _flushing || Time.realtimeSinceStartup > _catchUpUntil) { return; } int catchUpRebuilds = Tuning.CatchUpRebuilds; if (catchUpRebuilds <= 0) { return; } List<IMonoUpdater> instances = Heightmap.Instances; if (instances == null) { return; } _flushing = true; try { int num = 0; for (int i = 0; i < instances.Count; i++) { if (num >= catchUpRebuilds) { break; } IMonoUpdater obj = instances[i]; Heightmap val = (Heightmap)(object)((obj is Heightmap) ? obj : null); if (!((Object)(object)val == (Object)null) && Object.op_Implicit((Object)(object)val) && val.m_doLateUpdate != 0) { val.Regenerate(); num++; Flushed++; } } } finally { _flushing = false; } } private static bool AllowCatchUp(Heightmap hmap) { if (Tuning.CatchUpRebuilds <= 0 || Time.realtimeSinceStartup > _catchUpUntil) { return true; } Skipped = true; MarkPending(hmap); DeferredNow++; Deferred++; return false; } public static void Flush() { _rebuilt.Clear(); if (_flushing) { return; } List<IMonoUpdater> instances = Heightmap.Instances; if (instances == null) { return; } _flushing = true; try { for (int i = 0; i < instances.Count; i++) { IMonoUpdater obj = instances[i]; Heightmap val = (Heightmap)(object)((obj is Heightmap) ? obj : null); if (!((Object)(object)val == (Object)null) && Object.op_Implicit((Object)(object)val) && val.m_doLateUpdate != 0) { val.Regenerate(); Flushed++; } } } finally { _flushing = false; } } } [HarmonyPatch(typeof(Heightmap), "Regenerate")] internal static class Patch_Heightmap_Regenerate_Defer { private static bool Prefix(Heightmap __instance) { return TerrainRebuild.Allow(__instance); } } [HarmonyPatch(typeof(ZNetScene), "IsAreaReady")] internal static class Patch_ZNetScene_IsAreaReady_Flush { private static void Postfix(bool __result) { if (__result && LoadMode.Active) { TerrainRebuild.Flush(); } } } internal static class UnchangedMeshes { private sealed class Built { public float[] Heights; public Vector3 Position; public bool RenderCurrent; } [HarmonyPatch(typeof(Heightmap), "RebuildCollisionMesh")] private static class Patch_Collision { private static bool Prefix(Heightmap __instance, out bool __state) { //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Unknown result type (might be due to invalid IL or missing references) __state = false; _skippedCollision = null; if (!Active || !Memo.TryGetValue(__instance, out var value)) { return true; } Mesh val = CollisionMesh.Invoke(__instance); MeshCollider val2 = Collider.Invoke(__instance); bool flag = !Object.op_Implicit((Object)(object)val2) || (Object)(object)val2.sharedMesh == (Object)(object)val; if ((Object)(object)val == (Object)null || !flag || !SamePlace(value.Position, ((Component)__instance).transform.position) || !SameHeights(value.Heights, Heights.Invoke(__instance))) { return true; } if (SteadyFramePlugin.Cfg.VerifyUnchangedMeshes.On) { _verifyBefore = val.vertices; __state = true; return true; } _skippedCollision = __instance; Skipped++; return false; } private static void Postfix(Heightmap __instance, bool __runOriginal, bool __state) { //IL_014a: Unknown result type (might be due to invalid IL or missing references) //IL_014f: Unknown result type (might be due to invalid IL or missing references) //IL_00db: Unknown result type (might be due to invalid IL or missing references) if (!__runOriginal) { return; } if (__state) { Vector3[] vertices = CollisionMesh.Invoke(__instance).vertices; bool flag = _verifyBefore.Length == vertices.Length; int num = 0; while (flag && num < vertices.Length) { flag = vertices[num].x.Equals(_verifyBefore[num].x) && vertices[num].y.Equals(_verifyBefore[num].y) && vertices[num].z.Equals(_verifyBefore[num].z); num++; } if (flag) { SteadyFramePlugin.Cfg.VerifyUnchangedMeshes.Agreed(); } else { SteadyFramePlugin.Cfg.VerifyUnchangedMeshes.Diverged($"heightmap at {((Component)__instance).transform.position}: same heights, different collision mesh"); } _verifyBefore = null; } Built orCreateValue = Memo.GetOrCreateValue(__instance); List<float> list = Heights.Invoke(__instance); if (orCreateValue.Heights == null || orCreateValue.Heights.Length != list.Count) { orCreateValue.Heights = new float[list.Count]; } list.CopyTo(orCreateValue.Heights); orCreateValue.Position = ((Component)__instance).transform.position; orCreateValue.RenderCurrent = false; } } [HarmonyPatch(typeof(Heightmap), "RebuildRenderMesh")] private static class Patch_Render { private static bool Prefix(Heightmap __instance) { Built value; bool num = (Object)(object)_skippedCollision == (Object)(object)__instance && Memo.TryGetValue(__instance, out value) && value.RenderCurrent && (Object)(object)RenderMesh.Invoke(__instance) != (Object)null && Object.op_Implicit((Object)(object)Filter.Invoke(__instance)) && (Object)(object)Filter.Invoke(__instance).sharedMesh == (Object)(object)RenderMesh.Invoke(__instance); _skippedCollision = null; return !num; } private static void Postfix(Heightmap __instance, bool __runOriginal) { if (__runOriginal && Memo.TryGetValue(__instance, out var value)) { value.RenderCurrent = true; } } } private static readonly ConditionalWeakTable<Heightmap, Built> Memo = new ConditionalWeakTable<Heightmap, Built>(); private static readonly FieldRef<Heightmap, List<float>> Heights = AccessTools.FieldRefAccess<Heightmap, List<float>>("m_heights"); private static readonly FieldRef<Heightmap, Mesh> CollisionMesh = AccessTools.FieldRefAccess<Heightmap, Mesh>("m_collisionMesh"); private static readonly FieldRef<Heightmap, Mesh> RenderMesh = AccessTools.FieldRefAccess<Heightmap, Mesh>("m_renderMesh"); private static readonly FieldRef<Heightmap, MeshCollider> Collider = AccessTools.FieldRefAccess<Heightmap, MeshCollider>("m_collider"); private static readonly FieldRef<Heightmap, MeshFilter> Filter = AccessTools.FieldRefAccess<Heightmap, MeshFilter>("m_meshFilter"); private static Heightmap _skippedCollision; private static Vector3[] _verifyBefore; internal static long Skipped; private static bool Active { get { if (SteadyFramePlugin.Cfg != null && SteadyFramePlugin.Cfg.Enabled.Value) { return SteadyFramePlugin.Cfg.KeepUnchangedMeshes.Value; } return false; } } private static bool SameHeights(float[] built, List<float> now) { if (built == null || built.Length != now.Count) { return false; } for (int i = 0; i < built.Length; i++) { if (BitConverter.SingleToInt32Bits(built[i]) != BitConverter.SingleToInt32Bits(now[i])) { return false; } } return true; } private static bool SamePlace(Vector3 a, Vector3 b) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) if (a.x.Equals(b.x) && a.y.Equals(b.y)) { return a.z.Equals(b.z); } return false; } } internal static class ZoneRush { private static Func<ZoneSystem, Vector3, bool> _createLocalZones; private static bool _resolved; public static int ZonesCreated { get; private set; } public static string Summary => $"{ZonesCreated} zones created in batches"; private static bool Resolve() { if (_resolved) { return _createLocalZones != null; } _resolved = true; try { MethodInfo methodInfo = AccessTools.Method(typeof(ZoneSystem), "CreateLocalZones", (Type[])null, (Type[])null); if (methodInfo == null) { SteadyFramePlugin.Log.LogError((object)"[portal] ZoneSystem.CreateLocalZones unavailable; zone acceleration disabled"); return false; } _createLocalZones = AccessTools.MethodDelegate<Func<ZoneSystem, Vector3, bool>>(methodInfo, (object)null, true); } catch (Exception ex) { SteadyFramePlugin.Log.LogError((object)("[portal] ZoneSystem.CreateLocalZones binding failed: " + ex.GetType().Name + ": " + ex.Message + "; zone acceleration disabled")); _createLocalZones = null; } return _createLocalZones != null; } public static void Rush(ZoneSystem zones) { //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Unknown result type (might be due to invalid IL or missing references) if (LoadMode.Active && !((Object)(object)zones == (Object)null) && !((Object)(object)ZNet.instance == (Object)null) && Resolve()) { double num = Math.Max(1f, Tuning.LoadBudgetMs); Stopwatch stopwatch = Stopwatch.StartNew(); Vector3 referencePosition = ZNet.instance.GetReferencePosition(); while (stopwatch.Elapsed.TotalMilliseconds < num && _createLocalZones(zones, referencePosition)) { ZonesCreated++; } } } } [HarmonyPatch(typeof(ZoneSystem), "Update")] internal static class Patch_ZoneSystem_Update { private static void Postfix(ZoneSystem __instance) { ZoneRush.Rush(__instance); } } } namespace SteadyFrame.Structures { internal static class StructureGuard { private static readonly FieldRef<WearNTear, float> CreateTime = Field<WearNTear, float>("m_createTime"); private static readonly FieldRef<ZNetScene, List<ZDO>> Pending = Field<ZNetScene, List<ZDO>>("m_tempCurrentObjects2"); private static readonly HashSet<int> PendingSectors = new HashSet<int>(); private const float MaxHold = 120f; private static int _collectedFrame = -1; internal static bool Available { get { if (CreateTime != null) { return Pending != null; } return false; } } public static int Held { get; private set; } private static FieldRef<TObject, TField> Field<TObject, TField>(string name) { try { return AccessTools.FieldRefAccess<TObject, TField>(name); } catch (Exception) { return null; } } internal static bool MayCheck(WearNTear piece, float time) { //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_0083: Unknown result type (might be due to invalid IL or missing references) if (SteadyFramePlugin.Cfg == null || !SteadyFramePlugin.Cfg.Enabled.Value || (Object)(object)ZNetScene.instance == (Object)null) { return true; } float num = CreateTime.Invoke(piece); if (num < 0f) { return true; } if (time - num > 120f) { return true; } Collect(); if (PendingSectors.Count == 0) { return true; } Vector2s zone = ZoneSystem.GetZone(((Component)piece).transform.position); for (int i = -1; i <= 1; i++) { for (int j = -1; j <= 1; j++) { if (PendingSectors.Contains(Key(zone.x + i, zone.y + j))) { Held++; return false; } } } return true; } private static int Key(int x, int y) { return (x << 16) ^ (y & 0xFFFF); } private static void Collect() { //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_006e: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Unknown result type (might be due to invalid IL or missing references) if (_collectedFrame == Time.frameCount) { return; } _collectedFrame = Time.frameCount; PendingSectors.Clear(); ZNetScene instance = ZNetScene.instance; List<ZDO> list = Pending.Invoke(instance); if (list == null) { return; } foreach (ZDO item in list) { if (item != null && !item.Created && (Object)(object)instance.GetPrefab(item.GetPrefab()) != (Object)null) { Vector2s sector = item.GetSector(); PendingSectors.Add(Key(sector.x, sector.y)); } } } } [HarmonyPatch(typeof(WearNTear), "ShouldUpdate")] internal static class Patch_WearNTear_ShouldUpdate_Guard { private static bool Prepare() { if (!StructureGuard.Available) { SteadyFramePlugin.Log.LogError((object)"[portal] WearNTear.m_createTime or ZNetScene.m_tempCurrentObjects2 unavailable; structure guard disabled"); } return StructureGuard.Available; } private static void Postfix(WearNTear __instance, float __0, ref bool __result) { if (__result && !StructureGuard.MayCheck(__instance, __0)) { __result = false; } } } internal static class SupportLookups { private sealed class Owner { public WearNTear Value; } [HarmonyPatch(typeof(WearNTear), "UpdateSupport")] private static class Patch_UpdateSupport { private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { List<CodeInstruction> list = new List<CodeInstruction>(instructions); MethodInfo methodInfo = AccessTools.Method(typeof(Component), "GetComponentInParent", new Type[0], (Type[])null)?.MakeGenericMethod(typeof(WearNTear)); MethodInfo methodInfo2 = typeof(Enumerable).GetMethods().FirstOrDefault((MethodInfo m) => m.Name == "Contains" && m.GetParameters().Length == 2)?.MakeGenericMethod(typeof(Collider)); MethodInfo operand = AccessTools.Method(typeof(SupportLookups), "OwnerOf", (Type[])null, (Type[])null); MethodInfo operand2 = AccessTools.Method(typeof(SupportLookups), "IsOwn", (Type[])null, (Type[])null); int num = 0; int num2 = 0; foreach (CodeInstruction item in list) { if (item.operand is MethodInfo methodInfo3) { if (methodInfo != null && methodInfo3 == methodInfo) { num++; } else if (methodInfo2 != null && methodInfo3 == methodInfo2) { num2++; } } } if (num != 3 || num2 != 2) { SteadyFramePlugin.Log.LogError((object)($"[structures] UpdateSupport has {num} owner lookups and {num2} Contains " + "(expected 3 and 2); support lookups unchanged")); return list; } foreach (CodeInstruction item2 in list) { if (item2.operand is MethodInfo methodInfo4) { if (methodInfo4 == methodInfo) { item2.opcode = OpCodes.Call; item2.operand = operand; } else if (methodInfo4 == methodInfo2) { item2.opcode = OpCodes.Call; item2.operand = operand2; } } } return list; } } private static readonly ConditionalWeakTable<Collider, Owner> Owners = new ConditionalWeakTable<Collider, Owner>(); private static readonly ConditionalWeakTable<Collider[], HashSet<Collider>> OwnColliders = new ConditionalWeakTable<Collider[], HashSet<Collider>>(); private static bool Active { get { if (SteadyFramePlugin.Cfg != null && SteadyFramePlugin.Cfg.Enabled.Value) { return SteadyFramePlugin.Cfg.SupportLookups.Value; } return false; } } public static WearNTear OwnerOf(Component collider) { if (Active) { Collider val = (Collider)(object)((collider is Collider) ? collider : null); if (val != null && !((Object)(object)val == (Object)null) && ((Component)val).gameObject.activeInHierarchy) { if (!Owners.TryGetValue(val, out var value)) { value = new Owner { Value = ((Component)val).GetComponentInParent<WearNTear>() }; Owners.Add(val, value); } Verification verifySupportLookups = SteadyFramePlugin.Cfg.VerifySupportLookups; if (verifySupportLookups.On) { WearNTear componentInParent = ((Component)val).GetComponentInParent<WearNTear>(); if ((Object)(object)componentInParent == (Object)(object)value.Value) { verifySupportLookups.Agreed(); } else { verifySupportLookups.Diverged("owner of collider " + ((Object)val).name + ": cached " + (Object.op_Implicit((Object)(object)value.Value) ? ((Object)value.Value).name : "none") + ", game " + (Object.op_Implicit((Object)(object)componentInParent) ? ((Object)componentInParent).name : "none")); } return componentInParent; } return value.Value; } } return collider.GetComponentInParent<WearNTear>(); } public static bool IsOwn(IEnumerable<Collider> colliders, Collider collider) { if (!Active || !(colliders is Collider[] array)) { return colliders.Contains(collider); } if (!OwnColliders.TryGetValue(array, out var value)) { value = new HashSet<Collider>(array); OwnColliders.Add(array, value); } Verification verifySupportLookups = SteadyFramePlugin.Cfg.VerifySupportLookups; if (verifySupportLookups.On) { bool flag = colliders.Contains(collider); if (flag == value.Contains(collider)) { verifySupportLookups.Agreed(); } else { verifySupportLookups.Diverged(string.Format("own collider {0}: set {1}, array {2}", Object.op_Implicit((Object)(object)collider) ? ((Object)collider).name : "null", value.Contains(collider), flag)); } return flag; } return value.Contains(collider); } } } namespace SteadyFrame.SceneStreaming { internal static class IdlePass { [HarmonyPatch(typeof(ZDOMan), "AddToSector")] private static class Patch_AddToSector { private static void Postfix(SectorIndex sectorIndex) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) Touched(sectorIndex); } } [HarmonyPatch(typeof(ZDOMan), "RemoveFromSector")] private static class Patch_RemoveFromSector { private static void Postfix(SectorIndex sectorIndex) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) Touched(sectorIndex); } } [HarmonyPatch(/*Could not decode attribute arguments.*/)] private static class Patch_Created { private static void Postfix() { _createdVersion++; } } [HarmonyPatch(/*Could not decode attribute arguments.*/)] private static class Patch_Portals { private static void Postfix() { _portalVersion++; } } [HarmonyPatch(typeof(ZNetScene), "CreateDestroyObjects")] private static class Patch_Pass { private static bool Prefix(ZNetScene __instance) { //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_004b: 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) //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_00fe: Unknown result type (might be due to invalid IL or missing references) //IL_010c: Unknown result type (might be due to invalid IL or missing references) //IL_011a: Unknown result type (might be due to invalid IL or missing references) //IL_0128: Unknown result type (might be due to invalid IL or missing references) //IL_0142: Unknown result type (might be due to invalid IL or missing references) //IL_0143: Unknown result type (might be due to invalid IL or missing references) //IL_0148: Unknown result type (might be due to invalid IL or missing references) //IL_0149: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) long timestamp = Stopwatch.GetTimestamp(); SceneTiming.CollectTicksThisPass = 0L; _ran = false; if (!Active || (Object)(object)ZNet.instance == (Object)null || (Object)(object)ZoneSystem.instance == (Object)null) { _idle = false; return true; } Vector2s zone = ZoneSystem.GetZone(ZNet.instance.GetReferencePosition()); SimulationDistance distance = LoadRange.Effective(ZNet.instance); bool active = LoadMode.Active; bool flag = _idle && __instance == _scene && zone == _zone && ((SimulationDistance)(ref distance)).Equals(_distance) && active == _transition && _areaVersion == _areaAt && _createdVersion == _createdAt && _portalVersion == _portalAt && _skips < 30; Verification verifyIdlePass = SteadyFramePlugin.Cfg.VerifyIdlePass; if (flag && !verifyIdlePass.On) { _skips++; Skipped++; return false; } int totalSimulationDistance = ((SimulationDistance)(ref distance)).TotalSimulationDistance; _minX = zone.x - totalSimulationDistance; _maxX = zone.x + totalSimulationDistance; _minY = zone.y - totalSimulationDistance; _maxY = zone.y + totalSimulationDistance; _areaKnown = true; _scene = __instance; _zone = zone; _distance = distance; _transition = active; _areaAt = _areaVersion; _createdAt = _createdVersion; _portalAt = _portalVersion; _skips = 0; _ran = true; _predicted = flag; _idle = false; _instancesBefore = Instances.Invoke(__instance).Count; if (verifyIdlePass.On) { _prefixEnd = Stopwatch.GetTimestamp(); SceneTiming.OverheadTicks += _prefixEnd - timestamp; } return true; } private static void Postfix(ZNetScene __instance) { if (!_ran) { return; } _ran = false; long timestamp = Stopwatch.GetTimestamp(); bool flag = _prefixEnd != 0; bool flag2 = _areaVersion != _areaAt || _createdVersion != _createdAt || _portalVersion != _portalAt || Instances.Invoke(__instance).Count != _instancesBefore; bool flag3 = Pending(__instance, NearList.Invoke(__instance)) || Pending(__instance, DistantList.Invoke(__instance)); if (_predicted) { Verification verifyIdlePass = SteadyFramePlugin.Cfg.VerifyIdlePass; if (flag2 || flag3) { verifyIdlePass.Diverged($"pass predicted idle did work (changed {flag2}, pending {flag3}) at zone {_zone.x},{_zone.y}"); } else { verifyIdlePass.Agreed(); } } _idle = !flag2 && !flag3 && !ZoneUnload.Backlog && ZoneSystem.instance.IsActiveAreaLoaded(); _areaAt = _areaVersion; _createdAt = _createdVersion; _portalAt = _portalVersion; if (flag) { SceneTiming.Passes++; if (_predicted) { SceneTiming.PredictedIdle++; SceneTiming.IdlePassTicks += timestamp - _prefixEnd - SceneTiming.CollectTicksThisPass; } SceneTiming.OverheadTicks += Stopwatch.GetTimestamp() - timestamp; _prefixEnd = 0L; } } } private const int SafetyEvery = 30; private static readonly FieldRef<ZNetScene, List<ZDO>> NearList = AccessTools.FieldRefAccess<ZNetScene, List<ZDO>>("m_tempCurrentObjects"); private static readonly FieldRef<ZNetScene, List<ZDO>> DistantList = AccessTools.FieldRefAccess<ZNetScene, List<ZDO>>("m_tempCurrentDistantObjects"); private static readonly FieldRef<ZNetScene, Dictionary<ZDO, ZNetView>> Instances = AccessTools.FieldRefAccess<ZNetScene, Dictionary<ZDO, ZNetView>>("m_instances"); private static long _areaVersion; private static long _createdVersion; private static long _portalVersion; private static bool _areaKnown; private static int _minX; private static int _maxX; private static int _minY; private static int _maxY; private static bool _idle; private static ZNetScene _scene; private static Vector2s _zone; private static SimulationDistance _distance; private static bool _transition; private static long _areaAt; private static long _createdAt; private static long _portalAt; private static int _skips; private static bool _ran; private static bool _predicted; private static int _instancesBefore; private static long _prefixEnd; internal static long Skipped { get; private set; } private static bool Active { get { if (SteadyFramePlugin.Cfg != null && SteadyFramePlugin.Cfg.Enabled.Value) { return SteadyFramePlugin.Cfg.SkipIdlePasses.Value; } return false; } } private static void Touched(SectorIndex sectorIndex) { //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0020: 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) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Unknown result type (might be due to invalid IL or missing references) if (!_areaKnown) { _areaVersion++; return; } Vector2s val = ZoneSystem.IndexToSector(sectorIndex.Sector); if (val.x >= _minX && val.x <= _maxX && val.y >= _minY && val.y <= _maxY) { _areaVersion++; } } private static bool Pending(ZNetScene scene, List<ZDO> listed) { for (int i = 0; i < listed.Count; i++) { ZDO val = listed[i]; if (!val.Created && (Object)(object)scene.GetPrefab(val.GetPrefab()) != (Object)null) { return true; } } return false; } } internal static class InstanceIndex { [HarmonyPatch(typeof(ZNetScene), "AddInstance")] private static class Patch_AddInstance { private static void Postfix(ZDO zdo) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) if (zdo != null) { File(zdo, ZoneOfZdo(zdo)); if (_inCreatePass && zdo != _creating) { AddedDuringPass.Add(zdo); } } } } [HarmonyPatch(typeof(ZNetScene), "CreateObjects")] private static class Patch_CreateObjects { private static void Prefix() { AddedDuringPass.Clear(); _inCreatePass = true; } private static void Finalizer() { _inCreatePass = false; } } [HarmonyPatch(typeof(ZNetScene), "CreateObject")] private static class Patch_CreateObject { private static void Prefix(ZDO zdo, out ZDO __state) { __state = _creating; _creating = zdo; } private static void Finalizer(ZDO __state) { _creating = __state; } } [HarmonyPatch(typeof(ZDOMan), "AddToSector")] private static class Patch_AddToSector { private static void Postfix(ZDO zdo, SectorIndex sectorIndex) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) if (zdo != null && ZoneOf.ContainsKey(zdo)) { File(zdo, ZoneSystem.IndexToSector(sectorIndex.Sector)); } } } [HarmonyPatch(typeof(ZNetScene), "Shutdown")] private static class Patch_Shutdown { private static void Postfix() { Clear(); } } private static readonly Dictionary<Vector2s, HashSet<ZDO>> ByZone = new Dictionary<Vector2s, HashSet<ZDO>>(); private static readonly Dictionary<ZDO, Vector2s> ZoneOf = new Dictionary<ZDO, Vector2s>(ReferenceComparer<ZDO>.Instance); private static readonly Stack<HashSet<ZDO>> Pool = new Stack<HashSet<ZDO>>(); private static readonly Func<ZDO, bool> OutsideZones = AccessTools.MethodDelegate<Func<ZDO, bool>>(AccessTools.PropertyGetter(typeof(ZDO), "OutsideZones"), (object)null, true); internal static readonly List<ZDO> AddedDuringPass = new List<ZDO>(); private static bool _inCreatePass; private static ZDO _creating; internal static int Count => ZoneOf.Count; internal static Dictionary<Vector2s, HashSet<ZDO>>.Enumerator Zones() { return ByZone.GetEnumerator(); } internal static bool TryGetFiled(ZDO zdo, out Vector2s zone) { return ZoneOf.TryGetValue(zdo, out zone); } internal static Vector2s ZoneOfZdo(ZDO zdo) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) return ZoneSystem.IndexToSector(OutsideZones(zdo) ? ZoneSystem.SectorZero.Sector : zdo.GetSectorIndex().Sector); } private static void File(ZDO zdo, Vector2s zone) { //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_006d: 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) //IL_0058: Unknown result type (might be due to invalid IL or missing references) if (ZoneOf.TryGetValue(zdo, out var value)) { if (value == zone) { return; } Unfile(zdo, value); } if (!ByZone.TryGetValue(zone, out var value2)) { value2 = ((Pool.Count > 0) ? Pool.Pop() : new HashSet<ZDO>(ReferenceComparer<ZDO>.Instance)); ByZone.Add(zone, value2); } value2.Add(zdo); ZoneOf[zdo] = zone; } private static void Unfile(ZDO zdo, Vector2s zone) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) ZoneOf.Remove(zdo); if (ByZone.TryGetValue(zone, out var value) && value.Remove(zdo) && value.Count == 0) { ByZone.Remove(zone); Pool.Push(value); } } internal static void Remove(ZDO zdo) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) if (ZoneOf.TryGetValue(zdo, out var value)) { Unfile(zdo, value); } } internal static void Clear() { foreach (HashSet<ZDO> value in ByZone.Values) { value.Clear(); Pool.Push(value); } ByZone.Clear(); ZoneOf.Clear(); AddedDuringPass.Clear(); } internal static int Reconcile(Dictionary<ZDO, ZNetView> instances) { //IL_0027: Unknown result type (might be due to invalid IL or missing references) int num = 0; foreach (ZDO key in instances.Keys) { if (!ZoneOf.ContainsKey(key)) { File(key, ZoneOfZdo(key)); num++; } } return num; } } internal static class LoadRange { public static int Narrowed { get; private set; } public static int Skipped { get; private set; } internal static bool Applied { get; set; } private static bool Enabled { get { if (SteadyFramePlugin.Cfg != null && SteadyFramePlugin.Cfg.Enabled.Value) { return SteadyFramePlugin.Cfg.PortalNarrowRange.Value; } return false; } } private static bool AlreadyLoaded(SimulationDistance actual) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Unknown result type (might be due to invalid IL or missing references) if (!LoadMode.HasFrom) { return false; } Vector2s zone = ZoneSystem.GetZone(LoadMode.From); Vector2s zone2 = ZoneSystem.GetZone(LoadMode.Target); int num = ((SimulationDistance)(ref actual)).NearSimulationDistance - 1; if (num < 0) { return false; } if (Math.Abs(zone2.x - zone.x) <= num) { return Math.Abs(zone2.y - zone.y) <= num; } return false; } public static SimulationDistance ForStreaming(ZNet net) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) bool narrowed; bool skipped; SimulationDistance result = Effective(net, out narrowed, out skipped); if (narrowed) { Narrowed++; } if (skipped) { Skipped++; } return result; } public static SimulationDistance Effective(ZNet net) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) bool narrowed; bool skipped; return Effective(net, out narrowed, out skipped); } private static SimulationDistance Effective(ZNet net, out bool narrowed, out bool skipped) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0024: 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_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Unknown result type (might be due to invalid IL or missing references) narrowed = (skipped = false); SimulationDistance syncedSimulationDistance = net.GetSyncedSimulationD