using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Core.Logging.Interpolation;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using HarmonyLib;
using Il2CppInterop.Runtime.Injection;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppSystem.Collections.Generic;
using Microsoft.CodeAnalysis;
using UnityEngine;
[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("BigCityPerformance")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+874a80fa93844dd71e8199e5614fc6a83dfde0cc")]
[assembly: AssemblyProduct("BigCityPerformance")]
[assembly: AssemblyTitle("BigCityPerformance")]
[assembly: AssemblyVersion("1.0.0.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 PerfFix
{
internal static class AutoTune
{
internal static bool LargeCity;
internal static int Rooms = -1;
private static int _loggedMode = -1;
internal static void OnWorldUnloaded()
{
LargeCity = false;
Rooms = -1;
_loggedMode = -1;
}
internal static void Recompute()
{
ConfigEntry<bool> autoTune = PerfFixConfig.AutoTune;
if (autoTune != null && !autoTune.Value)
{
LargeCity = false;
return;
}
int num = -1;
try
{
CityData instance = CityData.Instance;
if ((Object)(object)instance != (Object)null)
{
List<NewRoom> roomDirectory = instance.roomDirectory;
if (roomDirectory != null)
{
num = roomDirectory.Count;
}
}
}
catch
{
num = -1;
}
Rooms = num;
int num2 = Math.Max(1, PerfFixConfig.AutoLargeCityRooms?.Value ?? 9000);
LargeCity = num >= num2;
int num3 = (LargeCity ? 1 : 0);
if (num > 0 && num3 != _loggedMode)
{
_loggedMode = num3;
Plugin.Log2.LogWarning((object)(LargeCity ? $"[PerfFix] auto: rooms={num} (>= {num2}) -> large-city mode: prompt interior loading off for streaming smoothness" : $"[PerfFix] auto: rooms={num} (< {num2}) -> standard mode: all features on"));
}
}
}
internal static class NativeGC
{
private const string Lib = "GameAssembly";
private static bool _probed;
internal static bool Available { get; private set; }
internal static bool Incremental { get; private set; }
internal static long OrigSliceNs { get; private set; } = -1L;
[DllImport("GameAssembly", CallingConvention = CallingConvention.Cdecl)]
private static extern void il2cpp_gc_set_max_time_slice_ns(long maxTimeSlice);
[DllImport("GameAssembly", CallingConvention = CallingConvention.Cdecl)]
private static extern long il2cpp_gc_get_max_time_slice_ns();
[DllImport("GameAssembly", CallingConvention = CallingConvention.Cdecl)]
private static extern int il2cpp_gc_collect_a_little();
[DllImport("GameAssembly", CallingConvention = CallingConvention.Cdecl)]
private static extern void il2cpp_gc_collect(int maxGenerations);
[DllImport("GameAssembly", CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
private static extern bool il2cpp_gc_is_incremental();
[DllImport("GameAssembly", CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
private static extern bool il2cpp_gc_is_disabled();
[DllImport("GameAssembly", CallingConvention = CallingConvention.Cdecl)]
private static extern long il2cpp_gc_get_used_size();
[DllImport("GameAssembly", CallingConvention = CallingConvention.Cdecl)]
private static extern long il2cpp_gc_get_heap_size();
internal static void EnsureProbed()
{
//IL_0034: Unknown result type (might be due to invalid IL or missing references)
//IL_003a: Expected O, but got Unknown
if (_probed)
{
return;
}
_probed = true;
try
{
long num = (OrigSliceNs = il2cpp_gc_get_max_time_slice_ns());
Incremental = il2cpp_gc_is_incremental();
Available = true;
ManualLogSource log = Plugin.Log2;
bool flag = default(bool);
BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(73, 4, ref flag);
if (flag)
{
((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[PerfFix] native il2cpp GC API OK — incremental=");
((BepInExLogInterpolatedStringHandler)val).AppendFormatted<bool>(Incremental);
((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" sliceNs=");
((BepInExLogInterpolatedStringHandler)val).AppendFormatted<long>(num);
((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" ");
((BepInExLogInterpolatedStringHandler)val).AppendLiteral("used=");
((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>((float)Used() / 1048576f, "F0");
((BepInExLogInterpolatedStringHandler)val).AppendLiteral("MB heap=");
((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>((float)HeapSize() / 1048576f, "F0");
((BepInExLogInterpolatedStringHandler)val).AppendLiteral("MB");
}
log.LogWarning(val);
}
catch (Exception ex)
{
Available = false;
Plugin.Log2.LogError((object)($"[PerfFix] native il2cpp GC API UNAVAILABLE ({ex.GetType().Name}: {ex.Message}) — " + "GC tuning disabled, vanilla GC left untouched."));
}
}
internal static long Used()
{
try
{
return il2cpp_gc_get_used_size();
}
catch
{
return -1L;
}
}
internal static long HeapSize()
{
try
{
return il2cpp_gc_get_heap_size();
}
catch
{
return -1L;
}
}
internal static long GetSliceNs()
{
try
{
return il2cpp_gc_get_max_time_slice_ns();
}
catch
{
return -1L;
}
}
internal static bool IsDisabled()
{
if (!Available)
{
return true;
}
try
{
return il2cpp_gc_is_disabled();
}
catch
{
return true;
}
}
internal static void SetSliceNs(long ns)
{
if (!Available)
{
return;
}
try
{
il2cpp_gc_set_max_time_slice_ns(ns);
}
catch
{
Available = false;
}
}
internal static bool CollectALittle()
{
if (!Available)
{
return false;
}
try
{
return il2cpp_gc_collect_a_little() != 0;
}
catch
{
Available = false;
return false;
}
}
internal static void CollectFull()
{
if (!Available)
{
return;
}
try
{
il2cpp_gc_collect(2);
}
catch
{
Available = false;
}
}
}
internal static class PathSpread
{
private static readonly double TicksToMs = 1000.0 / (double)Stopwatch.Frequency;
private static int _frame;
private static double _msThisFrame;
internal static bool ForceThrough;
internal static readonly Queue<NewAIAction> Queue = new Queue<NewAIAction>();
internal static readonly HashSet<IntPtr> Queued = new HashSet<IntPtr>();
internal static double MsThisFrame
{
get
{
EnsureFrame();
return _msThisFrame;
}
}
private static void EnsureFrame()
{
int frameCount = Time.frameCount;
if (frameCount != _frame)
{
_frame = frameCount;
_msThisFrame = 0.0;
}
}
internal static void AddCost(long ticks)
{
EnsureFrame();
_msThisFrame += (double)ticks * TicksToMs;
}
internal static void Clear()
{
Queue.Clear();
Queued.Clear();
}
}
[HarmonyPatch(typeof(PathFinder), "GetPath")]
internal static class P_GetPathTimer
{
private static void Prefix(out long __state)
{
ConfigEntry<bool> spreadPathRequests = PerfFixConfig.SpreadPathRequests;
__state = ((spreadPathRequests != null && spreadPathRequests.Value) ? Stopwatch.GetTimestamp() : 0);
}
private static void Postfix(long __state)
{
if (__state != 0L)
{
PathSpread.AddCost(Stopwatch.GetTimestamp() - __state);
}
}
}
[HarmonyPatch(typeof(NewAIAction), "SetupPath")]
internal static class P_SetupPath
{
private static bool Prefix(NewAIAction __instance)
{
if (Plugin.PatchesOk)
{
ConfigEntry<bool> spreadPathRequests = PerfFixConfig.SpreadPathRequests;
if (spreadPathRequests != null && spreadPathRequests.Value)
{
if (PathSpread.ForceThrough)
{
return true;
}
try
{
SessionData instance = SessionData.Instance;
if ((Object)(object)instance == (Object)null || !instance.startedGame)
{
return true;
}
CityConstructor instance2 = CityConstructor.Instance;
if ((Object)(object)instance2 != (Object)null && instance2.preSimActive)
{
return true;
}
NewAIGoal goal = __instance.goal;
object obj;
if (goal == null)
{
obj = null;
}
else
{
NewAIController aiController = goal.aiController;
obj = ((aiController != null) ? aiController.human : null);
}
Human val = (Human)obj;
if ((Object)(object)val == (Object)null)
{
return true;
}
if (((Actor)val).visible)
{
return true;
}
if (__instance.AllowImmediateTeleportation())
{
return true;
}
double num = Mathf.Max(1f, PerfFixConfig.PathBudgetMs?.Value ?? 6f);
if (PathSpread.MsThisFrame >= num)
{
if (PathSpread.Queued.Add(((Il2CppObjectBase)__instance).Pointer))
{
PathSpread.Queue.Enqueue(__instance);
}
return false;
}
}
catch
{
return true;
}
return true;
}
}
return true;
}
}
public class PerfFixBehaviour : MonoBehaviour
{
private static readonly double TicksToMs = 1000.0 / (double)Stopwatch.Frequency;
private float _nextReconcile;
private bool _streetLogged;
private bool _cacheLogged;
private bool _gcSliceLogged;
private bool _gcSliceRaised;
private bool _clampLogged;
private bool _streamLogged;
private int _reconcileErrs;
private int _slicerErrs;
private int _pathErrs;
private int _gcErrs;
private bool _wasHidden;
private float _collectDueAt = -1f;
private float _lastHiddenCollect = -999f;
private IntPtr _roomPtr = IntPtr.Zero;
private bool _armed;
private bool _furnDone;
private int _framesArmed;
private int _roomPriErrs;
private float _lastRangeTimer;
private int _cursor;
private int _counter = 1;
private float _quotaAcc;
private long _passStart;
private int _passes;
private int _slowPasses;
private double _maxPassMs;
private float _nextStat;
public PerfFixBehaviour(IntPtr ptr)
: base(ptr)
{
}
private void Update()
{
//IL_0053: Unknown result type (might be due to invalid IL or missing references)
//IL_0059: Expected O, but got Unknown
PathSpreadPump();
GcPerFrame();
try
{
if (!(Time.unscaledTime < _nextReconcile))
{
_nextReconcile = Time.unscaledTime + 1f;
Reconcile();
}
}
catch (Exception ex)
{
if (_reconcileErrs++ < 3)
{
ManualLogSource log = Plugin.Log2;
bool flag = default(bool);
BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(27, 1, ref flag);
if (flag)
{
((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[PerfFix] reconcile error: ");
((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ex.Message);
}
log.LogWarning(val);
}
}
}
private static bool IsPlaying()
{
SessionData instance = SessionData.Instance;
if ((Object)(object)instance != (Object)null)
{
return instance.play;
}
return false;
}
private static bool IsHidden()
{
try
{
MainMenuController instance = MainMenuController.Instance;
if ((Object)(object)instance != (Object)null && instance.mainMenuActive)
{
return true;
}
CityConstructor instance2 = CityConstructor.Instance;
if ((Object)(object)instance2 != (Object)null && instance2.loadingOperationActive)
{
return true;
}
}
catch
{
}
return false;
}
private void GcPerFrame()
{
//IL_0236: Unknown result type (might be due to invalid IL or missing references)
//IL_023c: Expected O, but got Unknown
//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
//IL_00e6: Expected O, but got Unknown
ConfigEntry<bool> tuneGC = PerfFixConfig.TuneGC;
if (tuneGC == null || !tuneGC.Value || !NativeGC.Available)
{
_wasHidden = IsHidden();
return;
}
bool flag2 = default(bool);
try
{
bool flag = IsHidden();
ConfigEntry<bool> gcHiddenCollect = PerfFixConfig.GcHiddenCollect;
if (gcHiddenCollect != null && gcHiddenCollect.Value)
{
if (flag && !_wasHidden)
{
_collectDueAt = Time.unscaledTime + 0.5f;
}
if (_collectDueAt > 0f && Time.unscaledTime >= _collectDueAt)
{
_collectDueAt = -1f;
if (flag && Time.unscaledTime - _lastHiddenCollect > 20f && !NativeGC.IsDisabled())
{
_lastHiddenCollect = Time.unscaledTime;
long num = NativeGC.Used();
NativeGC.CollectFull();
long num2 = NativeGC.Used();
if (num > 0 && num2 > 0)
{
ManualLogSource log = Plugin.Log2;
BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(36, 2, ref flag2);
if (flag2)
{
((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[PerfFix] hidden-moment GC: ");
((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>((float)num / 1048576f, "F0");
((BepInExLogInterpolatedStringHandler)val).AppendLiteral("MB -> ");
((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>((float)num2 / 1048576f, "F0");
((BepInExLogInterpolatedStringHandler)val).AppendLiteral("MB");
}
log.LogWarning(val);
}
}
}
}
_wasHidden = flag;
ConfigEntry<bool> gcPump = PerfFixConfig.GcPump;
if (gcPump == null || !gcPump.Value || !NativeGC.Incremental || !IsPlaying() || NativeGC.IsDisabled())
{
return;
}
float num3 = Time.unscaledDeltaTime * 1000f;
if (!(num3 > 0f) || !(num3 < (PerfFixConfig.GcPumpIdleUnderMs?.Value ?? 14f)))
{
return;
}
int num4 = Mathf.Max(1, PerfFixConfig.GcPumpMaxSteps?.Value ?? 3);
double num5 = Mathf.Max(0.25f, PerfFixConfig.GcPumpBudgetMs?.Value ?? 2f);
long timestamp = Stopwatch.GetTimestamp();
for (int i = 0; i < num4; i++)
{
if ((double)(Stopwatch.GetTimestamp() - timestamp) * TicksToMs >= num5)
{
break;
}
if (!NativeGC.CollectALittle())
{
break;
}
}
}
catch (Exception ex)
{
if (_gcErrs++ < 3)
{
ManualLogSource log2 = Plugin.Log2;
BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(30, 1, ref flag2);
if (flag2)
{
((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[PerfFix] gc per-frame error: ");
((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ex.Message);
}
log2.LogWarning(val);
}
}
}
private void Reconcile()
{
//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
//IL_00cb: Expected O, but got Unknown
//IL_047f: Unknown result type (might be due to invalid IL or missing references)
//IL_0486: Expected O, but got Unknown
//IL_03b5: Unknown result type (might be due to invalid IL or missing references)
//IL_03bc: Expected O, but got Unknown
//IL_02f1: Unknown result type (might be due to invalid IL or missing references)
//IL_02f8: Expected O, but got Unknown
//IL_01fb: Unknown result type (might be due to invalid IL or missing references)
//IL_0202: Expected O, but got Unknown
SessionData instance = SessionData.Instance;
if ((Object)(object)instance == (Object)null || !instance.startedGame)
{
PathSpread.Clear();
AutoTune.OnWorldUnloaded();
return;
}
AutoTune.Recompute();
ConfigEntry<bool> offThreadStreetPaths = PerfFixConfig.OffThreadStreetPaths;
if (offThreadStreetPaths != null && offThreadStreetPaths.Value)
{
Game instance2 = Game.Instance;
if ((Object)(object)instance2 != (Object)null && instance2.forceStreetPathsOnMainThread)
{
instance2.forceStreetPathsOnMainThread = false;
if (!_streetLogged)
{
_streetLogged = true;
Plugin.Log2.LogWarning((object)"[PerfFix] street pathfinding -> OFF main thread (parallelized)");
}
}
}
int num = PerfFixConfig.MaxRoomCache?.Value ?? 0;
bool flag = default(bool);
if (num > 0)
{
ObjectPoolingController instance3 = ObjectPoolingController.Instance;
if ((Object)(object)instance3 != (Object)null && instance3.maxRoomCache != num)
{
instance3.maxRoomCache = num;
if (!_cacheLogged)
{
_cacheLogged = true;
ManualLogSource log = Plugin.Log2;
BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(26, 1, ref flag);
if (flag)
{
((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[PerfFix] maxRoomCache -> ");
((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(num);
}
log.LogWarning(val);
}
}
}
ConfigEntry<bool> streamingBudgetOverride = PerfFixConfig.StreamingBudgetOverride;
if (streamingBudgetOverride != null && streamingBudgetOverride.Value)
{
ConfigEntry<bool> adaptiveStreaming = PerfFixConfig.AdaptiveStreaming;
if (adaptiveStreaming == null || !adaptiveStreaming.Value)
{
ObjectPoolingController instance4 = ObjectPoolingController.Instance;
if ((Object)(object)instance4 != (Object)null)
{
int num2 = Mathf.Max(1, PerfFixConfig.PooledSpawnsPerFrame?.Value ?? 5);
int num3 = Mathf.Max(1, PerfFixConfig.NewSpawnsPerFrame?.Value ?? 1);
int num4 = Mathf.Max(1, PerfFixConfig.FurnitureChecksPerFrame?.Value ?? 50);
int num5 = Mathf.Max(1, PerfFixConfig.RoomsLoadedPerFrame?.Value ?? 1);
if (instance4.loadPooledObjectPerFrame != num2 || instance4.loadNewObjectPerFrame != num3 || instance4.maximumRangeCheckingPerFrame != num4 || instance4.roomsLoadedPerFrame != num5)
{
instance4.loadPooledObjectPerFrame = num2;
instance4.loadNewObjectPerFrame = num3;
instance4.maximumRangeCheckingPerFrame = num4;
instance4.roomsLoadedPerFrame = num5;
if (!_streamLogged)
{
_streamLogged = true;
ManualLogSource log2 = Plugin.Log2;
BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(55, 4, ref flag);
if (flag)
{
((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[PerfFix] streaming budget -> pooled=");
((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(num2);
((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" new=");
((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(num3);
((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" furn=");
((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(num4);
((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" rooms=");
((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(num5);
}
log2.LogWarning(val);
}
}
}
}
}
NativeGC.EnsureProbed();
if (NativeGC.Available)
{
bool flag2 = PerfFixConfig.TuneGC?.Value ?? false;
int num6 = PerfFixConfig.GcTimeSliceMs?.Value ?? 0;
if (flag2 && num6 > 0 && NativeGC.Incremental)
{
long num7 = (long)num6 * 1000000L;
if (NativeGC.GetSliceNs() != num7)
{
NativeGC.SetSliceNs(num7);
_gcSliceRaised = true;
if (!_gcSliceLogged)
{
_gcSliceLogged = true;
ManualLogSource log3 = Plugin.Log2;
BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(43, 2, ref flag);
if (flag)
{
((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[PerfFix] GC max time-slice -> ");
((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(num6);
((BepInExLogInterpolatedStringHandler)val).AppendLiteral("ms (was ~");
((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>((float)NativeGC.OrigSliceNs / 1000000f, "F0");
((BepInExLogInterpolatedStringHandler)val).AppendLiteral("ms)");
}
log3.LogWarning(val);
}
}
}
else if (flag2 && num6 > 0 && !NativeGC.Incremental && !_gcSliceLogged)
{
_gcSliceLogged = true;
Plugin.Log2.LogWarning((object)"[PerfFix] GC time-slice raise skipped — incremental GC is OFF on this build.");
}
else if (_gcSliceRaised && NativeGC.OrigSliceNs > 0 && NativeGC.GetSliceNs() != NativeGC.OrigSliceNs)
{
NativeGC.SetSliceNs(NativeGC.OrigSliceNs);
_gcSliceRaised = false;
ManualLogSource log4 = Plugin.Log2;
BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(38, 1, ref flag);
if (flag)
{
((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[PerfFix] GC time-slice restored to ");
((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>((float)NativeGC.OrigSliceNs / 1000000f, "F0");
((BepInExLogInterpolatedStringHandler)val).AppendLiteral("ms");
}
log4.LogWarning(val);
}
}
ConfigEntry<bool> clampMaxDeltaTime = PerfFixConfig.ClampMaxDeltaTime;
if (clampMaxDeltaTime == null || !clampMaxDeltaTime.Value)
{
return;
}
float num8 = Mathf.Clamp(PerfFixConfig.MaxDeltaTimeSec?.Value ?? 0.15f, 0.05f, 1.05f);
float num9 = ((instance.currentTimeMultiplier >= 2f) ? 1.05f : num8);
if (!(Mathf.Abs(Time.maximumDeltaTime - num9) > 0.0001f))
{
return;
}
Time.maximumDeltaTime = num9;
if (!_clampLogged)
{
_clampLogged = true;
ManualLogSource log5 = Plugin.Log2;
BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(65, 2, ref flag);
if (flag)
{
((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[PerfFix] Time.maximumDeltaTime -> ");
((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>(num9, "F2");
((BepInExLogInterpolatedStringHandler)val).AppendLiteral("s (was 1.05; fixedDeltaTime=");
((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>(Time.fixedDeltaTime, "F3");
((BepInExLogInterpolatedStringHandler)val).AppendLiteral("s)");
}
log5.LogWarning(val);
}
}
private void PathSpreadPump()
{
//IL_0100: Unknown result type (might be due to invalid IL or missing references)
//IL_0107: Expected O, but got Unknown
if (!Plugin.PatchesOk || PathSpread.Queue.Count == 0)
{
return;
}
SessionData instance = SessionData.Instance;
if ((Object)(object)instance == (Object)null || !instance.startedGame)
{
PathSpread.Clear();
return;
}
try
{
double num = Mathf.Max(1f, PerfFixConfig.PathBudgetMs?.Value ?? 6f);
long timestamp = Stopwatch.GetTimestamp();
int num2 = 0;
int num3 = 0;
while (PathSpread.Queue.Count > 0 && num3++ < 256 && (num2 < 1 || !((double)(Stopwatch.GetTimestamp() - timestamp) * TicksToMs >= num)))
{
NewAIAction val = PathSpread.Queue.Dequeue();
if (val != null)
{
PathSpread.Queued.Remove(((Il2CppObjectBase)val).Pointer);
}
if (val != null && ReplayValid(val))
{
try
{
PathSpread.ForceThrough = true;
val.SetupPath(true);
num2++;
}
finally
{
PathSpread.ForceThrough = false;
}
}
}
}
catch (Exception ex)
{
if (_pathErrs++ < 3)
{
ManualLogSource log = Plugin.Log2;
bool flag = default(bool);
BepInExWarningLogInterpolatedStringHandler val2 = new BepInExWarningLogInterpolatedStringHandler(28, 1, ref flag);
if (flag)
{
((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("[PerfFix] pathspread error: ");
((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(ex.Message);
}
log.LogWarning(val2);
}
}
}
private static bool ReplayValid(NewAIAction a)
{
try
{
if (!a.isActive)
{
return false;
}
NewAIGoal goal = a.goal;
NewAIController val = ((goal != null) ? goal.aiController : null);
if ((Object)(object)val == (Object)null)
{
return false;
}
NewAIAction currentAction = val.currentAction;
if (currentAction == null || ((Il2CppObjectBase)currentAction).Pointer != ((Il2CppObjectBase)a).Pointer)
{
return false;
}
if (a.isAtLocation)
{
return false;
}
if (a.path != null)
{
return false;
}
return true;
}
catch
{
return false;
}
}
private void RoomPriorityPass()
{
//IL_02c4: Unknown result type (might be due to invalid IL or missing references)
//IL_02cb: Expected O, but got Unknown
if (!Plugin.PatchesOk)
{
return;
}
ConfigEntry<bool> currentRoomPriority = PerfFixConfig.CurrentRoomPriority;
if (currentRoomPriority != null && !currentRoomPriority.Value)
{
return;
}
if (AutoTune.LargeCity)
{
_roomPtr = IntPtr.Zero;
_armed = false;
return;
}
try
{
SessionData instance = SessionData.Instance;
if ((Object)(object)instance == (Object)null || !instance.startedGame)
{
_roomPtr = IntPtr.Zero;
_armed = false;
return;
}
Player instance2 = Player.Instance;
if ((Object)(object)instance2 == (Object)null)
{
return;
}
ObjectPoolingController instance3 = ObjectPoolingController.Instance;
if ((Object)(object)instance3 == (Object)null)
{
return;
}
NewRoom currentRoom = ((Actor)instance2).currentRoom;
IntPtr intPtr = (((Object)(object)currentRoom != (Object)null && !currentRoom.IsOutside()) ? ((Il2CppObjectBase)currentRoom).Pointer : IntPtr.Zero);
if (intPtr != _roomPtr)
{
_roomPtr = intPtr;
if (intPtr != IntPtr.Zero)
{
_armed = true;
_framesArmed = 0;
_furnDone = false;
}
}
if (intPtr == IntPtr.Zero)
{
_armed = false;
return;
}
float updateObjectRangesTimer = instance3.updateObjectRangesTimer;
if (updateObjectRangesTimer < _lastRangeTimer)
{
_armed = true;
_furnDone = false;
}
_lastRangeTimer = updateObjectRangesTimer;
if (!_armed)
{
return;
}
if (instance3.roomStuffQueuedToLoad != null && instance3.roomStuffQueuedToLoad.Contains(currentRoom))
{
if (++_framesArmed > 600)
{
_armed = false;
}
return;
}
int num = 0;
HashSet<NewNode> nodes = currentRoom.nodes;
if (nodes != null)
{
Enumerator<NewNode> enumerator = nodes.GetEnumerator();
while (enumerator.MoveNext())
{
NewNode current = enumerator.Current;
if (current == null)
{
continue;
}
List<Interactable> interactables = current.interactables;
if (interactables != null)
{
for (int i = 0; i < interactables.Count; i++)
{
num += Prioritize(instance3, interactables[i]);
}
}
}
}
List<Interactable> lightswitchInteractables = currentRoom.lightswitchInteractables;
if (lightswitchInteractables != null)
{
for (int j = 0; j < lightswitchInteractables.Count; j++)
{
num += Prioritize(instance3, lightswitchInteractables[j]);
}
}
if (!_furnDone)
{
_furnDone = true;
List<FurnitureClusterLocation> furniture = currentRoom.furniture;
if (furniture != null)
{
for (int k = 0; k < furniture.Count; k++)
{
FurnitureClusterLocation val = furniture[k];
if (val != null && val.loadedGeometry)
{
try
{
val.LoadFurnitureToWorld(true);
num++;
}
catch
{
}
}
}
}
}
_framesArmed++;
if (num == 0 || _framesArmed > 600)
{
_armed = false;
}
}
catch (Exception ex)
{
_armed = false;
if (_roomPriErrs++ < 3)
{
ManualLogSource log = Plugin.Log2;
bool flag = default(bool);
BepInExWarningLogInterpolatedStringHandler val2 = new BepInExWarningLogInterpolatedStringHandler(31, 1, ref flag);
if (flag)
{
((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("[PerfFix] room-priority error: ");
((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(ex.Message);
}
log.LogWarning(val2);
}
if (_roomPriErrs == 3)
{
Plugin.Log2.LogWarning((object)"[PerfFix] room-priority silenced after repeated errors.");
}
}
}
private static int Prioritize(ObjectPoolingController opc, Interactable it)
{
if (it == null || (SoCustomComparison)(object)it.preset == (SoCustomComparison)null || (Object)(object)it.inInventory != (Object)null)
{
return 0;
}
InteractableController controller = it.controller;
if ((Object)(object)controller != (Object)null && controller.isVisible)
{
return 0;
}
if (it.loadedGeometry)
{
if ((Object)(object)controller != (Object)null)
{
controller.SetVisible(true, false);
return 1;
}
return 0;
}
InteractablePreset preset = it.preset;
if (!preset.spawnable || (Object)(object)preset.prefab == (Object)null)
{
return 0;
}
if (it.furnitureParent != null && (Object)(object)it.furnitureParent.spawnedObject == (Object)null)
{
return 0;
}
HashSet<Interactable> interactableLoadList = opc.interactableLoadList;
if (interactableLoadList != null && !interactableLoadList.Contains(it))
{
interactableLoadList.Add(it);
opc.interactableRangeToLoadList?.Remove(it);
((Behaviour)opc).enabled = true;
return 1;
}
return 0;
}
private void LateUpdate()
{
//IL_0362: Unknown result type (might be due to invalid IL or missing references)
//IL_0369: Expected O, but got Unknown
//IL_01e8: Unknown result type (might be due to invalid IL or missing references)
//IL_01ed: Unknown result type (might be due to invalid IL or missing references)
//IL_01ef: Unknown result type (might be due to invalid IL or missing references)
//IL_01f2: Invalid comparison between Unknown and I4
//IL_02a1: Unknown result type (might be due to invalid IL or missing references)
//IL_02a8: Expected O, but got Unknown
//IL_01f4: Unknown result type (might be due to invalid IL or missing references)
//IL_01f7: Invalid comparison between Unknown and I4
//IL_0203: Unknown result type (might be due to invalid IL or missing references)
//IL_0206: Invalid comparison between Unknown and I4
//IL_0212: Unknown result type (might be due to invalid IL or missing references)
//IL_0215: Invalid comparison between Unknown and I4
//IL_0222: Unknown result type (might be due to invalid IL or missing references)
RoomPriorityPass();
if (!Plugin.SweepArmed)
{
return;
}
ConfigEntry<bool> timeSliceSweep = PerfFixConfig.TimeSliceSweep;
if (timeSliceSweep == null || !timeSliceSweep.Value)
{
return;
}
bool flag = default(bool);
try
{
SessionData instance = SessionData.Instance;
if ((Object)(object)instance == (Object)null || !instance.startedGame)
{
return;
}
CityData instance2 = CityData.Instance;
if ((Object)(object)instance2 == (Object)null)
{
return;
}
List<Citizen> citizenDirectory = instance2.citizenDirectory;
if (citizenDirectory == null)
{
return;
}
int count = citizenDirectory.Count;
if (count <= 0)
{
return;
}
float num = Time.deltaTime * Mathf.Clamp(instance.currentTimeMultiplier, 1f, 1.5f);
_quotaAcc += (float)count * num / 0.2f;
int num2 = (int)_quotaAcc;
_quotaAcc -= num2;
if (num2 <= 0)
{
return;
}
double num3 = Mathf.Max(0.5f, PerfFixConfig.SliceBudgetMs?.Value ?? 4f);
long timestamp = Stopwatch.GetTimestamp();
int num4 = 0;
while (num4 < num2)
{
if (_cursor >= count)
{
if (_passStart != 0L)
{
double num5 = (double)(Stopwatch.GetTimestamp() - _passStart) * TicksToMs;
if (num5 > _maxPassMs)
{
_maxPassMs = num5;
}
if (num5 > 350.0)
{
_slowPasses++;
}
}
_passStart = Stopwatch.GetTimestamp();
_passes++;
_cursor = 0;
_counter++;
if (_counter > 1500)
{
_counter = 1;
}
}
Citizen val = citizenDirectory[_cursor];
_cursor++;
num4++;
if ((Object)(object)val != (Object)null)
{
NewAIController ai = ((Actor)val).ai;
if ((Object)(object)ai != (Object)null && ((Behaviour)ai).enabled && !((Actor)val).visible)
{
AITickRate tickRate = ai.tickRate;
if ((int)tickRate == 4 || ((int)tickRate == 3 && _counter % 2 == 0) || ((int)tickRate == 2 && _counter % 5 == 0) || ((int)tickRate == 1 && _counter % 11 == 0) || ((int)tickRate == 0 && _counter % 17 == 0))
{
ai.FrequentUpdate();
}
}
}
if ((double)(Stopwatch.GetTimestamp() - timestamp) * TicksToMs >= num3)
{
break;
}
}
_slicerErrs = 0;
ConfigEntry<bool> verboseLogging = PerfFixConfig.VerboseLogging;
if (verboseLogging == null || !verboseLogging.Value || !(Time.unscaledTime >= _nextStat))
{
return;
}
if (_nextStat > 0f)
{
ManualLogSource log = Plugin.Log2;
BepInExMessageLogInterpolatedStringHandler val2 = new BepInExMessageLogInterpolatedStringHandler(66, 3, ref flag);
if (flag)
{
((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("[PerfFix] slicer: ");
((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<float>((float)_passes / 10f, "F1");
((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(" passes/s (target ~5) maxPass=");
((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<double>(_maxPassMs, "F0");
((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("ms slow(>350ms)=");
((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<int>(_slowPasses);
}
log.LogMessage(val2);
}
_nextStat = Time.unscaledTime + 10f;
_passes = 0;
_slowPasses = 0;
_maxPassMs = 0.0;
}
catch (Exception ex)
{
if (_slicerErrs++ < 3)
{
ManualLogSource log2 = Plugin.Log2;
BepInExWarningLogInterpolatedStringHandler val3 = new BepInExWarningLogInterpolatedStringHandler(24, 1, ref flag);
if (flag)
{
((BepInExLogInterpolatedStringHandler)val3).AppendLiteral("[PerfFix] slicer error: ");
((BepInExLogInterpolatedStringHandler)val3).AppendFormatted<string>(ex.Message);
}
log2.LogWarning(val3);
}
if (_slicerErrs >= 30)
{
Plugin.SweepArmed = false;
Plugin.Log2.LogError((object)"[PerfFix] slicer DISARMED after repeated errors — vanilla sweep restored.");
}
}
}
}
internal static class PerfFixConfig
{
internal static ConfigEntry<bool> AutoTune;
internal static ConfigEntry<int> AutoLargeCityRooms;
internal static ConfigEntry<bool> OffThreadStreetPaths;
internal static ConfigEntry<bool> TimeSliceSweep;
internal static ConfigEntry<float> SliceBudgetMs;
internal static ConfigEntry<bool> SpreadPathRequests;
internal static ConfigEntry<float> PathBudgetMs;
internal static ConfigEntry<int> MaxRoomCache;
internal static ConfigEntry<bool> TuneGC;
internal static ConfigEntry<int> GcTimeSliceMs;
internal static ConfigEntry<bool> GcHiddenCollect;
internal static ConfigEntry<bool> GcPump;
internal static ConfigEntry<float> GcPumpBudgetMs;
internal static ConfigEntry<int> GcPumpMaxSteps;
internal static ConfigEntry<float> GcPumpIdleUnderMs;
internal static ConfigEntry<bool> ClampMaxDeltaTime;
internal static ConfigEntry<float> MaxDeltaTimeSec;
internal static ConfigEntry<bool> StreamingBudgetOverride;
internal static ConfigEntry<int> PooledSpawnsPerFrame;
internal static ConfigEntry<int> NewSpawnsPerFrame;
internal static ConfigEntry<int> FurnitureChecksPerFrame;
internal static ConfigEntry<int> RoomsLoadedPerFrame;
internal static ConfigEntry<bool> AdaptiveStreaming;
internal static ConfigEntry<int> AdaptiveMinPooled;
internal static ConfigEntry<int> AdaptiveMinFurn;
internal static ConfigEntry<float> AdaptiveHeadroomMs;
internal static ConfigEntry<float> AdaptiveHeavyMs;
internal static ConfigEntry<bool> AdaptiveInteriorKick;
internal static ConfigEntry<bool> CurrentRoomPriority;
internal static ConfigEntry<bool> VerboseLogging;
internal static void Init(ConfigFile cfg)
{
AutoTune = cfg.Bind<bool>("0-Auto", "AutoTune", true, "Adapt automatically to very large cities. On a city at or above the room count below, the two prompt interior-loading behaviors (see sections 7 and 8) are turned off, because at extreme city sizes they add small streaming hitches while you walk that outweigh the benefit, and they cannot help the large freezes that dominate at that scale. Everything else stays on, so streets stay as smooth as vanilla or better. Standard and normal large cities are not affected at all. If the city cannot be read, prompt interior loading stays on.");
AutoLargeCityRooms = cfg.Bind<int>("0-Auto", "AutoLargeCityRooms", 9000, "A loaded city with at least this many rooms is treated as very large by AutoTune. Standard cities and normal large cities have fewer rooms than this, so they are unaffected; only extreme custom cities cross it. Raise it to never trigger, or lower it if a big custom city still feels hitchy while walking.");
OffThreadStreetPaths = cfg.Bind<bool>("1-StreetPaths", "OffThreadStreetPaths", true, "Run cross-city street pathfinding on background worker threads instead of the main thread. This is the biggest win: in a large city it turns the quarter-second-plus pathfinding freezes into short hitches and roughly halves garbage-collection pauses. No visual change. Citizens may occasionally take a slightly different route, which you will not notice.");
TimeSliceSweep = cfg.Bind<bool>("2-LateUpdate", "TimeSliceSweep", true, "Spread the game's offscreen-citizen update (which normally runs in one burst several times a second) out across frames. Removes the recurring 40 to 90 ms hiccups that grow with city size. Only offscreen citizens are affected and all their timing is preserved, so there is no visible difference.");
SliceBudgetMs = cfg.Bind<float>("2-LateUpdate", "SliceBudgetMs", 6f, "Milliseconds per frame the spread-out update may use. Lower is smoother but offscreen citizens update a touch less often. Around 4 to 8 works well.");
SpreadPathRequests = cfg.Bind<bool>("3-Pathfinding", "SpreadPathRequests", true, "When a crowd of offscreen citizens all ask for a new route in the same frame, spread those requests across a few frames so they do not stack into one long freeze. The game already lets a citizen wait briefly for a path, so there is no visible difference, and visible citizens always path instantly.");
PathBudgetMs = cfg.Bind<float>("3-Pathfinding", "PathBudgetMs", 6f, "Milliseconds per frame of path computation before extra offscreen requests wait for the next frame. Around 4 to 10 works well.");
MaxRoomCache = cfg.Bind<int>("4-RoomCache", "MaxRoomCache", 250, "How many rooms of interior geometry to keep loaded (the game default is 100). Large-city streets can show more than 100 rooms at once, so the game keeps unloading and reloading room meshes as you move, which causes hitches. Raising this trades memory for smoothness (very roughly half a gigabyte at 250). Set to 0 to leave the game default. Around 150 to 400.");
TuneGC = cfg.Bind<bool>("5-GarbageCollector", "TuneGC", false, "Tune the game's garbage collector to cut the long collection pauses (the multi-hundred-millisecond freezes that get worse the longer you play a big city). This does NOT turn the collector off; it only changes how it paces itself, and it is visual-neutral. If a game update ever removes the collector controls this feature quietly does nothing.");
GcTimeSliceMs = cfg.Bind<int>("5-GarbageCollector", "GcTimeSliceMs", 8, "How many milliseconds the collector may spend per step while you play (the game default is 3). A slightly larger step lets it keep pace with a busy city so it rarely has to stop everything for one long pause. This is a trade: the game's own once-per-frame collection step can now take up to this long during a busy stretch, so high-refresh players (120Hz and up) may prefer 5 to 8, and 60Hz players 8 to 12. Set to 0 to leave the game default. Only has an effect when the game's incremental collector is on (it is, by default).");
GcHiddenCollect = cfg.Bind<bool>("5-GarbageCollector", "GcHiddenCollect", true, "Run one full collection at genuinely hidden moments (the pause menu overlay is up, or a save is loading) so memory is tidied when you cannot feel it instead of mid-play. It does not run for the case board, conversations, the map, or other windows that leave the world on screen.");
GcPump = cfg.Bind<bool>("5-GarbageCollector", "GcPump", false, "EXPERIMENTAL: on frames that already have time to spare, nudge the collector along a little so it keeps pace with a busy city. Off by default; turn it on only to test whether it helps on your machine. It runs only on fast frames, but a single nudge is bounded by the step length above (not by the budget below), so on rare occasions it can still land a longer step on a spare frame. Leave it off unless testing shows a clear win.");
GcPumpBudgetMs = cfg.Bind<float>("5-GarbageCollector", "GcPumpBudgetMs", 2f, "Most milliseconds per frame the experimental collector nudge may use.");
GcPumpMaxSteps = cfg.Bind<int>("5-GarbageCollector", "GcPumpMaxSteps", 3, "Most collector nudges per frame for the experimental pump.");
GcPumpIdleUnderMs = cfg.Bind<float>("5-GarbageCollector", "GcPumpIdleUnderMs", 14f, "Only nudge the collector when the previous frame was faster than this many milliseconds, i.e. there is spare time. 14ms is about 70fps.");
StreamingBudgetOverride = cfg.Bind<bool>("7-StreamingBudget", "StreamingBudgetOverride", false, "EXPERIMENTAL / diagnostic: override how much object and furniture geometry the game streams in per frame (the ObjectPoolingController pools). Lowering these spreads the streaming work over more frames, which can cut the frequent small hitches as you move, at the cost of objects and furniture appearing a touch later. Off by default. Use it to find and tune the streaming cost.");
PooledSpawnsPerFrame = cfg.Bind<int>("7-StreamingBudget", "PooledSpawnsPerFrame", 5, "Reused (pooled) object spawns allowed per frame. Game default 5. Held at 1 or more.");
NewSpawnsPerFrame = cfg.Bind<int>("7-StreamingBudget", "NewSpawnsPerFrame", 1, "Brand-new (uncached) object spawns allowed per frame. Game default 1. Held at 1 or more.");
FurnitureChecksPerFrame = cfg.Bind<int>("7-StreamingBudget", "FurnitureChecksPerFrame", 50, "Furniture visibility range-checks allowed per frame. Game default 50. Held at 1 or more.");
RoomsLoadedPerFrame = cfg.Bind<int>("7-StreamingBudget", "RoomsLoadedPerFrame", 1, "Room-interior stuff loads allowed per frame. Game default 1. Held at 1 or more.");
AdaptiveStreaming = cfg.Bind<bool>("7-StreamingBudget", "AdaptiveStreaming", true, "Smoothly throttle object and furniture streaming ONLY on frames that are already running slow, and stream at full (game-default) speed the rest of the time. This targets the frequent small hitches as you move WITHOUT the constant pop-in of a fixed low budget, because it only defers streaming on a frame that is already hitching (where the delay is masked). Recommended over the fixed override above. Takes precedence over it when both are on.");
AdaptiveMinPooled = cfg.Bind<int>("7-StreamingBudget", "AdaptiveMinPooled", 2, "The fewest reused (pooled) spawns per frame on the slowest frames (game default full-speed is 5). Held at 1 or more.");
AdaptiveMinFurn = cfg.Bind<int>("7-StreamingBudget", "AdaptiveMinFurn", 25, "The fewest furniture range-checks per frame on the slowest frames (game default full-speed is 50). Held at 1 or more.");
AdaptiveHeadroomMs = cfg.Bind<float>("7-StreamingBudget", "AdaptiveHeadroomMs", 14f, "Frames faster than this (in ms) stream at full speed. 14ms is about 70fps.");
AdaptiveHeavyMs = cfg.Bind<float>("7-StreamingBudget", "AdaptiveHeavyMs", 28f, "Frames slower than this (in ms) throttle to the minimums above; in between it scales smoothly. 28ms is about 36fps.");
AdaptiveInteriorKick = cfg.Bind<bool>("7-StreamingBudget", "AdaptiveInteriorKick", true, "Fixes a base-game quirk (made more visible by adaptive streaming and a large room cache): after you enter a room and stand still, its furniture can take several seconds to appear because the game only refreshes furniture visibility when you cross a room boundary or on a slow timer. This nudges that refresh while a room is loading, so furniture appears promptly instead. Only active while adaptive streaming is on.");
CurrentRoomPriority = cfg.Bind<bool>("8-RoomPriority", "CurrentRoomPriority", true, "Make sure everything in the room you are standing in appears promptly, even in large rooms, instead of some objects trickling in over several seconds. Spawning is still spread across frames so it does not cause a hitch, and it only affects the room you are currently inside (not the street).");
ClampMaxDeltaTime = cfg.Bind<bool>("6-FrameCatchup", "ClampMaxDeltaTime", false, "After a big freeze, stop the game trying to fast-forward the entire lost time in the very next frame. That fast-forward causes a visible lurch and a second stutter (the physics has to take dozens of catch-up steps at once). This only affects the one recovery frame after a hitch, never normal play, and is visual-neutral.");
MaxDeltaTimeSec = cfg.Bind<float>("6-FrameCatchup", "MaxDeltaTimeSec", 0.15f, "The most simulated time, in seconds, a single recovery frame may advance. The game default is 1.05. Lower means a gentler recovery after a hitch. Around 0.1 to 0.2 works well. Held between 0.05 and 1.05.");
VerboseLogging = cfg.Bind<bool>("9-Debug", "VerboseLogging", false, "Log extra diagnostic detail. Off by default.");
}
}
[BepInPlugin("Kropath.BigCityPerformance", "Big City Performance", "1.2.0")]
public class Plugin : BasePlugin
{
internal static ManualLogSource Log2;
internal static Harmony HarmonyInstance;
internal static bool SweepArmed;
internal static bool PatchesOk;
public override void Load()
{
//IL_0020: Unknown result type (might be due to invalid IL or missing references)
//IL_0026: Expected O, but got Unknown
//IL_0083: Unknown result type (might be due to invalid IL or missing references)
//IL_008a: Expected O, but got Unknown
//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
//IL_00f1: Expected O, but got Unknown
//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
//IL_00c1: Expected O, but got Unknown
//IL_0159: Unknown result type (might be due to invalid IL or missing references)
//IL_015f: Expected O, but got Unknown
Log2 = ((BasePlugin)this).Log;
PerfFixConfig.Init(((BasePlugin)this).Config);
ManualLogSource log = Log2;
bool flag = default(bool);
BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(57, 2, ref flag);
if (flag)
{
((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[PerfFix] loading — OffThreadStreetPaths=");
((BepInExLogInterpolatedStringHandler)val).AppendFormatted<bool>(PerfFixConfig.OffThreadStreetPaths.Value);
((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" TimeSliceSweep=");
((BepInExLogInterpolatedStringHandler)val).AppendFormatted<bool>(PerfFixConfig.TimeSliceSweep.Value);
}
log.LogWarning(val);
bool flag2 = false;
try
{
ClassInjector.RegisterTypeInIl2Cpp<PerfFixBehaviour>();
((BasePlugin)this).AddComponent<PerfFixBehaviour>();
flag2 = true;
}
catch (Exception ex)
{
ManualLogSource log2 = Log2;
BepInExErrorLogInterpolatedStringHandler val2 = new BepInExErrorLogInterpolatedStringHandler(36, 1, ref flag);
if (flag)
{
((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("[PerfFix] runtime injection FAILED: ");
((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(ex.Message);
}
log2.LogError(val2);
}
bool flag3 = false;
HarmonyInstance = new Harmony("Kropath.BigCityPerformance");
try
{
HarmonyInstance.PatchAll(typeof(Plugin).Assembly);
flag3 = true;
}
catch (Exception ex2)
{
ManualLogSource log3 = Log2;
BepInExErrorLogInterpolatedStringHandler val2 = new BepInExErrorLogInterpolatedStringHandler(32, 1, ref flag);
if (flag)
{
((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("[PerfFix] Harmony patch FAILED: ");
((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(ex2.Message);
}
log3.LogError(val2);
}
PatchesOk = flag2 && flag3;
SweepArmed = PatchesOk;
if (PerfFixConfig.TimeSliceSweep.Value && !SweepArmed)
{
Log2.LogError((object)"[PerfFix] TimeSliceSweep setup incomplete — DISARMED; vanilla sweep left intact.");
}
ManualLogSource log4 = Log2;
val = new BepInExWarningLogInterpolatedStringHandler(145, 13, ref flag);
if (flag)
{
((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[PerfFix] loaded (patchesOk=");
((BepInExLogInterpolatedStringHandler)val).AppendFormatted<bool>(PatchesOk);
((BepInExLogInterpolatedStringHandler)val).AppendLiteral("). StreetPaths=");
((BepInExLogInterpolatedStringHandler)val).AppendFormatted<bool>(PerfFixConfig.OffThreadStreetPaths.Value);
((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" Slicer=");
((BepInExLogInterpolatedStringHandler)val).AppendFormatted<bool>(PerfFixConfig.TimeSliceSweep.Value);
((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" PathSpread=");
((BepInExLogInterpolatedStringHandler)val).AppendFormatted<bool>(PerfFixConfig.SpreadPathRequests.Value);
((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" MaxRoomCache=");
((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(PerfFixConfig.MaxRoomCache.Value);
((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" TuneGC=");
((BepInExLogInterpolatedStringHandler)val).AppendFormatted<bool>(PerfFixConfig.TuneGC.Value);
((BepInExLogInterpolatedStringHandler)val).AppendLiteral("(slice=");
((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(PerfFixConfig.GcTimeSliceMs.Value);
((BepInExLogInterpolatedStringHandler)val).AppendLiteral("ms,hidden=");
((BepInExLogInterpolatedStringHandler)val).AppendFormatted<bool>(PerfFixConfig.GcHiddenCollect.Value);
((BepInExLogInterpolatedStringHandler)val).AppendLiteral(",pump=");
((BepInExLogInterpolatedStringHandler)val).AppendFormatted<bool>(PerfFixConfig.GcPump.Value);
((BepInExLogInterpolatedStringHandler)val).AppendLiteral(") ClampDelta=");
((BepInExLogInterpolatedStringHandler)val).AppendFormatted<bool>(PerfFixConfig.ClampMaxDeltaTime.Value);
((BepInExLogInterpolatedStringHandler)val).AppendLiteral("(");
((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>(PerfFixConfig.MaxDeltaTimeSec.Value);
((BepInExLogInterpolatedStringHandler)val).AppendLiteral("s) AutoTune=");
((BepInExLogInterpolatedStringHandler)val).AppendFormatted<bool>(PerfFixConfig.AutoTune.Value);
((BepInExLogInterpolatedStringHandler)val).AppendLiteral("(>= ");
((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(PerfFixConfig.AutoLargeCityRooms.Value);
((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" rooms)");
}
log4.LogWarning(val);
}
}
[HarmonyPatch(typeof(ObjectPoolingController), "LateUpdate")]
internal static class StreamingBudgetPatch
{
private const int FullPooled = 5;
private const int FullFurn = 50;
private const float ClearFrames = 15f;
private static int _errs;
private static bool _logged;
private static bool _wrote;
private static void Prefix(ObjectPoolingController __instance)
{
//IL_0257: Unknown result type (might be due to invalid IL or missing references)
//IL_025e: Expected O, but got Unknown
//IL_0194: Unknown result type (might be due to invalid IL or missing references)
//IL_019b: Expected O, but got Unknown
if (Plugin.PatchesOk)
{
ConfigEntry<bool> adaptiveStreaming = PerfFixConfig.AdaptiveStreaming;
if (adaptiveStreaming != null && adaptiveStreaming.Value)
{
bool flag = default(bool);
try
{
ConfigEntry<bool> adaptiveInteriorKick = PerfFixConfig.AdaptiveInteriorKick;
if ((adaptiveInteriorKick == null || adaptiveInteriorKick.Value) && !AutoTune.LargeCity)
{
HashSet<NewRoom> roomStuffQueuedToLoad = __instance.roomStuffQueuedToLoad;
if (roomStuffQueuedToLoad != null && roomStuffQueuedToLoad.Count > 0)
{
__instance.UpdateObjectRanges();
}
}
float num = Time.unscaledDeltaTime * 1000f;
float num2 = Mathf.Max(1f, PerfFixConfig.AdaptiveHeadroomMs?.Value ?? 14f);
float num3 = Mathf.Max(num2 + 1f, PerfFixConfig.AdaptiveHeavyMs?.Value ?? 28f);
float num4 = Mathf.Clamp01((num - num2) / (num3 - num2));
int num5 = Mathf.Clamp(PerfFixConfig.AdaptiveMinPooled?.Value ?? 2, 1, 5);
int num6 = Mathf.Clamp(PerfFixConfig.AdaptiveMinFurn?.Value ?? 25, 1, 50);
int num7 = Mathf.RoundToInt(Mathf.Lerp(5f, (float)num5, num4));
int maximumRangeCheckingPerFrame = Mathf.RoundToInt(Mathf.Lerp(50f, (float)num6, num4));
int num8 = 0;
try
{
HashSet<Interactable> interactableLoadList = __instance.interactableLoadList;
if (interactableLoadList != null)
{
num8 = interactableLoadList.Count;
}
}
catch
{
}
int num9 = Mathf.Min(5, Mathf.CeilToInt((float)num8 / 15f));
__instance.loadPooledObjectPerFrame = Mathf.Max(num7, num9);
__instance.maximumRangeCheckingPerFrame = maximumRangeCheckingPerFrame;
_wrote = true;
if (!_logged)
{
_logged = true;
ManualLogSource log = Plugin.Log2;
BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(77, 6, ref flag);
if (flag)
{
((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[PerfFix] adaptive streaming engaged (pooled ");
((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(5);
((BepInExLogInterpolatedStringHandler)val).AppendLiteral("->");
((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(num5);
((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" +backlog-floor, furn ");
((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(50);
((BepInExLogInterpolatedStringHandler)val).AppendLiteral("->");
((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(num6);
((BepInExLogInterpolatedStringHandler)val).AppendLiteral(", ");
((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>(num2, "F0");
((BepInExLogInterpolatedStringHandler)val).AppendLiteral("-");
((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>(num3, "F0");
((BepInExLogInterpolatedStringHandler)val).AppendLiteral("ms)");
}
log.LogWarning(val);
}
return;
}
catch (Exception ex)
{
if (_errs++ < 3)
{
ManualLogSource log2 = Plugin.Log2;
BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(36, 1, ref flag);
if (flag)
{
((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[PerfFix] adaptive streaming error: ");
((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ex.Message);
}
log2.LogWarning(val);
}
return;
}
}
}
if (_wrote)
{
try
{
__instance.loadPooledObjectPerFrame = 5;
__instance.maximumRangeCheckingPerFrame = 50;
}
catch
{
}
_wrote = false;
}
}
}
[HarmonyPatch(typeof(CitizenBehaviour), "LateUpdate")]
internal static class SweepSuppressPatch
{
private static void Prefix(CitizenBehaviour __instance)
{
bool flag = Plugin.SweepArmed && (PerfFixConfig.TimeSliceSweep?.Value ?? false);
try
{
if (flag)
{
__instance.frequentTick5FPS = -1E+09f;
}
else if (__instance.frequentTick5FPS < 0f)
{
__instance.frequentTick5FPS = 0f;
}
}
catch
{
}
}
}
}