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 FiresFixes v0.1.206
plugins/FiresFixes/FiresFixes.dll
Decompiled 2 hours 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.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Security.Cryptography; using System.Security.Permissions; using System.Text; using System.Threading; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using FiresFixes.Api; using FiresFixes.Fixes; using FiresFixes.Moved; using FiresFixes.Terrain; using HarmonyLib; using Microsoft.CodeAnalysis; using SoftReferenceableAssets; using Splatform; using TMPro; using Unity.Collections; using Unity.Profiling; using UnityEngine; using UnityEngine.AI; using UnityEngine.LowLevel; using UnityEngine.Profiling; using UnityEngine.Rendering; using UnityEngine.Scripting; using UnityEngine.UI; using Valheim.SettingsGui; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("0.0.0.0")] [module: UnverifiableCode] [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 FiresFixes { [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInPlugin("com.Fire.FiresFixes", "FiresFixes", "0.1.206")] public class Plugin : BaseUnityPlugin { public const string PluginGuid = "com.Fire.FiresFixes"; public const string PluginName = "FiresFixes"; public const string PluginVersion = "0.1.206"; internal static ManualLogSource Log; internal static ConfigEntry<bool> LoadingWait; internal static ConfigEntry<bool> TerrainCrease; internal static ConfigEntry<bool> FastBorderTangents; internal static ConfigEntry<bool> TamedForgetSpawnPoint; internal static ConfigEntry<bool> TerrainEditBorders; internal static ConfigEntry<bool> GrassRebuildSpread; internal static ConfigEntry<bool> DeferAssetCleanup; internal static ConfigEntry<bool> EquipModifierNoBox; internal static Plugin Instance; private static bool s_dropped; private void Awake() { Log = ((BaseUnityPlugin)this).Logger; Instance = this; StartupConfigSaves.Bind(((BaseUnityPlugin)this).Config); StartupPatchBatch.Bind(((BaseUnityPlugin)this).Config); StartupLanguageReuse.Bind(((BaseUnityPlugin)this).Config); StartupBundleCache.Bind(((BaseUnityPlugin)this).Config); StartupConfigSaves.BeginOwn(((BaseUnityPlugin)this).Config); try { AwakeBody(); } finally { StartupConfigSaves.EndOwn(((BaseUnityPlugin)this).Config); } StartupConfigSaves.OpenWindow(); } private void AwakeBody() { //IL_00b5: Unknown result type (might be due to invalid IL or missing references) //IL_00bf: Expected O, but got Unknown //IL_069b: Unknown result type (might be due to invalid IL or missing references) //IL_06a5: Expected O, but got Unknown //IL_076d: Unknown result type (might be due to invalid IL or missing references) //IL_0786: Expected O, but got Unknown LoadingWait = ((BaseUnityPlugin)this).Config.Bind<bool>("Loading", "End Loading When The Area Is Ready", true, "Spawn as soon as the area around you has loaded instead of always waiting 8 seconds."); DropOrphan("Terrain", "Smooth the 64 m terrain crease"); TerrainCrease = ((BaseUnityPlugin)this).Config.Bind<bool>("Terrain", "Smooth Terrain Tile Borders", true, "Removes the lighting lines you can see on slopes where terrain tiles meet."); TerrainSeamNormals.Enabled = () => TerrainCrease.Value; DropOrphan("Terrain", "Fast Border Tangents"); FastBorderTangents = ((BaseUnityPlugin)this).Config.Bind<bool>("Terrain", "Fast Tile Border Tangents", true, new ConfigDescription("Faster terrain loading by only fixing tile edges (experimental).", (AcceptableValueBase)null, new object[1] { new ConfigurationManagerAttributes { IsAdvanced = true } })); TerrainSeamNormals.FastEdgeTangents = () => FastBorderTangents.Value; TamedForgetSpawnPoint = ((BaseUnityPlugin)this).Config.Bind<bool>("Creatures", "Tamed Creatures Forget Their Spawner", true, "Tamed creatures stop wandering back to where they spawned."); TerrainSeamNormals.LogDebug = delegate(string m) { Log.LogDebug((object)m); }; TerrainEditBorders = ((BaseUnityPlugin)this).Config.Bind<bool>("Terrain", "Finish Terrain Edits At Tile Borders", true, "A hoe, pickaxe or terrain edit near a tile border also reaches the tile next to it, even if that tile loads later."); TerrainPaintSeams.Enabled = () => TerrainEditBorders.Value; TerrainPaintSeams.LogDebug = delegate(string m) { Log.LogDebug((object)m); }; VisEquipSkip.Bind(((BaseUnityPlugin)this).Config); GroundCheckReuse.Bind(((BaseUnityPlugin)this).Config); _ = FfLog.DebugOn; AsyncDiskLog.Bind(((BaseUnityPlugin)this).Config); AsyncDiskLog.Install(); TerrainCollisionSkip.Bind(((BaseUnityPlugin)this).Config); SleepingCreatureTicks.Bind(((BaseUnityPlugin)this).Config); VisColourSkip.Bind(((BaseUnityPlugin)this).Config); VisEquipProbe.Bind(((BaseUnityPlugin)this).Config); ArmorStandCapes.Bind(((BaseUnityPlugin)this).Config); ConsoleSpawnGuard.Bind(((BaseUnityPlugin)this).Config); EffectAreaStaleCharacters.Bind(((BaseUnityPlugin)this).Config); ClientChangesSaved.Bind(((BaseUnityPlugin)this).Config); StaleInstanceUnregister.Bind(((BaseUnityPlugin)this).Config); LovePotionSpawns.Bind(((BaseUnityPlugin)this).Config); FishWorldEdge.Bind(((BaseUnityPlugin)this).Config); GameplayFixes0101.Bind(((BaseUnityPlugin)this).Config); StationOverfillGuard.Bind(((BaseUnityPlugin)this).Config); SettingsWindowUnsubscribe.Bind(((BaseUnityPlugin)this).Config); LoopingSoundRestart.Bind(((BaseUnityPlugin)this).Config); TerrainSaveBatch.Bind(((BaseUnityPlugin)this).Config); TerrainSaveBatch.BindSnow(((BaseUnityPlugin)this).Config); IdleCreatureTicks.Bind(((BaseUnityPlugin)this).Config); TerrainColliderBake.Bind(((BaseUnityPlugin)this).Config); HeightmapQueueJump.Bind(((BaseUnityPlugin)this).Config); HeightmapQueueJump.BindReadyCap(((BaseUnityPlugin)this).Config); ZoneSpawnTransaction.Bind(((BaseUnityPlugin)this).Config); VegetationDuplicateEntries.Bind(((BaseUnityPlugin)this).Config); VppParityA.Bind(((BaseUnityPlugin)this).Config); PathLinkCap.Bind(((BaseUnityPlugin)this).Config); VppParitySmall.Bind(((BaseUnityPlugin)this).Config); AzuEpiPreviewOwnGear.Bind(((BaseUnityPlugin)this).Config); AzuEpiVanityCacheCap.Bind(((BaseUnityPlugin)this).Config); MultiUserChestBlockTrim.Bind(((BaseUnityPlugin)this).Config); DistantSectorSkip.Bind(((BaseUnityPlugin)this).Config); SmallFixes0159.Bind(((BaseUnityPlugin)this).Config); WearNTearVanilla0163.Bind(((BaseUnityPlugin)this).Config); WearNTearVanilla0164.Bind(((BaseUnityPlugin)this).Config); GrassEdgeUpdate.Bind(((BaseUnityPlugin)this).Config); FiresFixes.Fixes.GrassRebuildSpread.Bind(((BaseUnityPlugin)this).Config); GrassInstancePool.Bind(((BaseUnityPlugin)this).Config); GrassFadeCarry.Bind(((BaseUnityPlugin)this).Config); WearUpdaterBudget.Bind(((BaseUnityPlugin)this).Config); VpoPorts0166.Bind(((BaseUnityPlugin)this).Config); WearNTearOwnerCache.Bind(((BaseUnityPlugin)this).Config); PerfPorts0170.Bind(((BaseUnityPlugin)this).Config); HealthBandSkip.Bind(((BaseUnityPlugin)this).Config); WearPathTrims.Bind(((BaseUnityPlugin)this).Config); ReflectionCubeRenderer.Bind(((BaseUnityPlugin)this).Config); VpoMethods0171.Bind(((BaseUnityPlugin)this).Config); HeightmapGenerateFast.Bind(((BaseUnityPlugin)this).Config); SyncedAnimatorCache.Bind(((BaseUnityPlugin)this).Config); VpoStudy0174.Bind(((BaseUnityPlugin)this).Config); PauseFarLoopingSounds.BindVerify(((BaseUnityPlugin)this).Config); SelfCost.InitConfig(((BaseUnityPlugin)this).Config); MaterialVariationRetry.Bind(((BaseUnityPlugin)this).Config); FastActiveArea.Bind(((BaseUnityPlugin)this).Config); SpreadOwnershipPass.Bind(((BaseUnityPlugin)this).Config); MovedFromFgn.Host = this; MovedFromFgn.Bind(((BaseUnityPlugin)this).Config); NullRefStudy0175.Bind(((BaseUnityPlugin)this).Config); GhostLoad0175.Bind(((BaseUnityPlugin)this).Config); TeleportWait.Bind(((BaseUnityPlugin)this).Config); FrameBudget.Bind(((BaseUnityPlugin)this).Config); PortalArrival.Bind(((BaseUnityPlugin)this).Config); MistChecks.Bind(((BaseUnityPlugin)this).Config); SpawnCountsOnce.Bind(((BaseUnityPlugin)this).Config); AmbientParticlesOffScreen.Bind(((BaseUnityPlugin)this).Config); AmbientEmitters.Bind(((BaseUnityPlugin)this).Config); LooseObjectSupport.Bind(((BaseUnityPlugin)this).Config); DungeonInteriorHold.Bind(((BaseUnityPlugin)this).Config); SavedSnowHide.Bind(((BaseUnityPlugin)this).Config); StationsAndArrival0199.Bind(((BaseUnityPlugin)this).Config); CollisionLoadHold.Bind(((BaseUnityPlugin)this).Config); RegenerateSplitProbe.Bind(((BaseUnityPlugin)this).Config); LocationLoadFrameHold.Bind(((BaseUnityPlugin)this).Config); SavePath.Bind(((BaseUnityPlugin)this).Config); TerrainPaintOnlyPokes.Bind(((BaseUnityPlugin)this).Config); SnowPaintOnce.Bind(((BaseUnityPlugin)this).Config); TerrainShortSnowTimer.Bind(((BaseUnityPlugin)this).Config); TailFrameRate.Bind(((BaseUnityPlugin)this).Config); TailBuoyancy.Bind(((BaseUnityPlugin)this).Config); ForcedCleanupHold.Bind(((BaseUnityPlugin)this).Config); WorldSaveProof.Bind(((BaseUnityPlugin)this).Config); LocationDeadChildren.Bind(((BaseUnityPlugin)this).Config); TerrainCompilerMerge.Bind(((BaseUnityPlugin)this).Config); DistantRingBudget.Bind(((BaseUnityPlugin)this).Config); SaveTableFilter.Bind(((BaseUnityPlugin)this).Config); TerrainCookingOptions.Bind(((BaseUnityPlugin)this).Config); RadialLodHide.Bind(((BaseUnityPlugin)this).Config); DistantFlagCensus.Bind(((BaseUnityPlugin)this).Config); LoadFieldsCache.Bind(((BaseUnityPlugin)this).Config); LoadFieldsCache.BindHashedKeys(((BaseUnityPlugin)this).Config); TerrainRenderShortcuts.Bind(((BaseUnityPlugin)this).Config); GcMoments.Bind(((BaseUnityPlugin)this).Config); FightFrame.Bind(((BaseUnityPlugin)this).Config); Pathing.Bind(((BaseUnityPlugin)this).Config); ZoneCensus.Bind(((BaseUnityPlugin)this).Config); TerrainDrawCensus.Bind(((BaseUnityPlugin)this).Config); UiFrame.Bind(((BaseUnityPlugin)this).Config); WorldLoad.Bind(((BaseUnityPlugin)this).Config); ZoneExpiryLookup.Bind(((BaseUnityPlugin)this).Config); CharacterStepCaches.Bind(((BaseUnityPlugin)this).Config); LocationSpawnBudget.Bind(((BaseUnityPlugin)this).Config); SafePatching.Bind(((BaseUnityPlugin)this).Config); PatchAudit.Bind(((BaseUnityPlugin)this).Config); PlayerLoopTiming.Bind(((BaseUnityPlugin)this).Config); UpdateCostCensus.Bind(((BaseUnityPlugin)this).Config); MonoUpdaterCensus.Bind(((BaseUnityPlugin)this).Config); SaveStepProbe.Bind(((BaseUnityPlugin)this).Config); IdleOwnedSyncPark.Bind(((BaseUnityPlugin)this).Config); OffScreenLightFlicker.Bind(((BaseUnityPlugin)this).Config); SettledDoorAnimators.Bind(((BaseUnityPlugin)this).Config); WearNTearHub.BindW8Diag(((BaseUnityPlugin)this).Config); ConfigEntry<int> val = ((BaseUnityPlugin)this).Config.Bind<int>("Performance", "Defaults Migrated", 0, new ConfigDescription("Internal: which default changes were applied once.", (AcceptableValueBase)null, new object[1] { new ConfigurationManagerAttributes { Browsable = false } })); if (val.Value < 39) { val.Value = 39; } GrassRebuildSpread = ((BaseUnityPlugin)this).Config.Bind<bool>("Performance", "Spread Grass Rebuilds", true, "After a terrain edit, rebuild nearby grass over a few frames instead of all in one (less hitching)."); DeferAssetCleanup = ((BaseUnityPlugin)this).Config.Bind<bool>("Performance", "Defer Hourly Cleanup While Players Are On", true, "Dedicated server: skip the hourly unused-asset cleanup while players are connected, at most 3 hours in a row."); EquipModifierNoBox = ((BaseUnityPlugin)this).Config.Bind<bool>("Performance", "Equipment Modifiers Without Allocations", true, "Adds up your gear's movement and stamina modifiers without creating garbage every physics step."); if (val.Value < 40) { val.Value = 40; } if (val.Value < 112) { Log.LogDebug((object)"[FiresFixes] settings marker 112: saved values kept as they are (since 0.1.145 a default change never rewrites a saved value)"); val.Value = 112; } if (val.Value < 128) { val.Value = 128; } ValPerfPatcher.Prime(); SafePatching.PatchEachClass(new Harmony("com.Fire.FiresFixes"), typeof(Plugin).Assembly); OverlapNotice.Scan(); if (s_dropped && !StartupConfigSaves.SaveOwnOnce.Value) { try { ((BaseUnityPlugin)this).Config.Save(); } catch (Exception) { } } Log.LogInfo((object)("Fires Fixes 0.1.206: loading wait " + (LoadingWait.Value ? "on" : "off") + ", terrain crease " + (TerrainCrease.Value ? "on" : "off") + ", terrain edit borders " + (TerrainEditBorders.Value ? "on" : "off") + ", tamed forget spawner " + (TamedForgetSpawnPoint.Value ? "on" : "off") + ", crash guards on (recipe any-one-of, icon variant, null spawner prefab, null effect prefab, null extension connection), guards on (unkillable creatures, stamina floor, chest grid reset, bed spawn keep, station refund), effect areas " + (EffectAreaStaleCharacters.Enabled.Value ? "on" : "off") + ", client changes saved " + (ClientChangesSaved.Enabled.Value ? "on" : "off") + ", stale instances " + (StaleInstanceUnregister.Enabled.Value ? "on" : "off") + ", love potion " + (LovePotionSpawns.Enabled.Value ? "on" : "off") + ", settings window " + (SettingsWindowUnsubscribe.Enabled.Value ? "on" : "off") + ", looping sounds " + (LoopingSoundRestart.Enabled.Value ? "on" : "off"))); Log.LogDebug((object)"[FiresFixes] unkillable creatures guard: health read first (0.1.33), IsOwner/IsDead only when health <= 0 or NaN"); Log.LogDebug((object)"[EventDriven] 0.1.48 caches on: sleeping-creature component fields (no behaviour change)"); } private void Start() { //IL_000a: 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_0015: Expected O, but got Unknown //IL_001a: Expected O, but got Unknown GrassForeignDraw.Check(); Harmony val = new Harmony("com.Fire.FiresFixes.late"); VppParitySmall.ApplyLate(val); OtherModFixes.AtStart(val); } private void DropOrphan(string section, string key) { //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Expected O, but got Unknown try { if (AccessTools.Property(typeof(ConfigFile), "OrphanedEntries")?.GetValue(((BaseUnityPlugin)this).Config) is Dictionary<ConfigDefinition, string> dictionary) { ConfigDefinition key2 = new ConfigDefinition(section, key); if (dictionary.TryGetValue(key2, out var value) && dictionary.Remove(key2)) { s_dropped = true; Log.LogInfo((object)("[FiresFixes] config: retired key [" + section + "] \"" + key + "\" (was " + value + ") removed; its successor starts at the tested default")); } } } catch (Exception ex) { Log.LogWarning((object)("[FiresFixes] config: could not drop [" + section + "] \"" + key + "\": " + ex.Message)); } } } internal sealed class ConfigurationManagerAttributes { public bool? Browsable; public bool? IsAdvanced; public int? Order; } [HarmonyPatch(typeof(ZNet), "OnDestroy")] internal static class TerrainPaintSeamsReset { private static void Postfix() { TerrainPaintSeams.Reset(); TerrainSaveBatch.Reset(); } } } namespace FiresFixes.Api { public static class FixesApi { private sealed class Skip { internal string Owner; internal Func<Character, bool> Test; } private sealed class Area { internal string Owner; internal Func<Vector3, bool> Test; } private sealed class Hold { internal string Owner; internal Func<ZDO, bool> Test; } public const int Version = 7; private static readonly List<Skip> s_skips = new List<Skip>(); private static readonly List<Area> s_areas = new List<Area>(); private static readonly List<Hold> s_holds = new List<Hold>(); public static bool ParticleCullingActive { get; internal set; } public static bool PiecesGroupedPerTileWanted { get { if (VpoMethods0171.HeightmapSubs != null) { return VpoMethods0171.HeightmapSubs.Value; } return false; } } public static bool PiecesGroupedPerTileActive { get { if (PieceHeightmapGroups.Attached && VpoMethods0171.HeightmapSubs != null) { return VpoMethods0171.HeightmapSubs.Value; } return false; } } internal static int CreateHoldCount => s_holds.Count; public static bool HoldsInteriorObject(ZDO zdo) { return DungeonInteriorHold.HoldsInteriorObject(zdo); } public static bool RegisterCreatureSkip(string owner, Func<Character, bool> keepFullSpeed) { if (string.IsNullOrEmpty(owner) || keepFullSpeed == null) { Plugin.Log.LogWarning((object)"[FiresFixes] RegisterCreatureSkip refused: owner and keepFullSpeed are required"); return false; } s_skips.RemoveAll((Skip s) => s.Owner == owner); s_skips.Add(new Skip { Owner = owner, Test = keepFullSpeed }); Plugin.Log.LogInfo((object)$"[FiresFixes] creature skip registered by {owner}: its creatures are never throttled ({s_skips.Count} skip(s))"); return true; } public static bool UnregisterCreatureSkip(string owner) { if (s_skips.RemoveAll((Skip s) => s.Owner == owner) == 0) { return false; } Plugin.Log.LogInfo((object)$"[FiresFixes] creature skip removed by {owner} ({s_skips.Count} left)"); return true; } public static bool RegisterAreaKeepAlive(string owner, Func<Vector3, bool> keptAlive) { if (string.IsNullOrEmpty(owner) || keptAlive == null) { Plugin.Log.LogWarning((object)"[FiresFixes] RegisterAreaKeepAlive refused: owner and keptAlive are required"); return false; } s_areas.RemoveAll((Area a) => a.Owner == owner); s_areas.Add(new Area { Owner = owner, Test = keptAlive }); Plugin.Log.LogInfo((object)$"[FiresFixes] keep-alive area registered by {owner} ({s_areas.Count} in all)"); return true; } public static bool UnregisterAreaKeepAlive(string owner) { return s_areas.RemoveAll((Area a) => a.Owner == owner) > 0; } public static bool RegisterCreateHold(string owner, Func<ZDO, bool> holdUncreated) { if (string.IsNullOrEmpty(owner) || holdUncreated == null) { Plugin.Log.LogWarning((object)"[FiresFixes] RegisterCreateHold refused: owner and holdUncreated are required"); return false; } s_holds.RemoveAll((Hold h) => h.Owner == owner); s_holds.Add(new Hold { Owner = owner, Test = holdUncreated }); Plugin.Log.LogInfo((object)$"[FiresFixes] create hold registered by {owner}: the objects it names stay uncreated until it lets go, 20 s at most each ({s_holds.Count} hold(s))"); return true; } public static bool UnregisterCreateHold(string owner) { if (s_holds.RemoveAll((Hold h) => h.Owner == owner) == 0) { return false; } Plugin.Log.LogInfo((object)$"[FiresFixes] create hold removed by {owner} ({s_holds.Count} left)"); return true; } internal static string HeldBy(ZDO zdo) { for (int i = 0; i < s_holds.Count; i++) { try { if (s_holds[i].Test(zdo)) { return s_holds[i].Owner; } } catch (Exception ex) { Plugin.Log.LogWarning((object)("[FiresFixes] create hold of " + s_holds[i].Owner + " threw (" + ex.Message + "); dropped")); s_holds.RemoveAt(i); i--; } } return null; } internal static string KeptAliveBy(Vector3 point) { //IL_0018: Unknown result type (might be due to invalid IL or missing references) for (int i = 0; i < s_areas.Count; i++) { try { if (s_areas[i].Test(point)) { return s_areas[i].Owner; } } catch (Exception ex) { Plugin.Log.LogWarning((object)("[FiresFixes] keep-alive area of " + s_areas[i].Owner + " threw (" + ex.Message + "); dropped")); s_areas.RemoveAt(i); i--; } } return null; } internal static string SkippedBy(Character c) { if ((Object)(object)c == (Object)null) { return null; } for (int i = 0; i < s_skips.Count; i++) { try { if (s_skips[i].Test(c)) { return s_skips[i].Owner; } } catch (Exception ex) { Plugin.Log.LogWarning((object)("[FiresFixes] creature skip of " + s_skips[i].Owner + " threw (" + ex.Message + "); dropped")); s_skips.RemoveAt(i); i--; } } return null; } } } namespace FiresFixes.Moved { [HarmonyPatch] internal static class DungeonSpawnSpread { internal static ConfigEntry<bool> ConfigEnabled; private const double DungeonBudgetMs = 6.0; private static readonly HashSet<DungeonGenerator> s_pending = new HashSet<DungeonGenerator>(); private static bool s_finishing; private static bool s_releasing; private static FieldInfo s_loadedRooms; private static FieldInfo s_roomData; private static FieldInfo s_position; private static FieldInfo s_rotation; private static MethodInfo s_placeRoom; private static MethodInfo s_release; private static bool s_resolved; private static bool s_broken; private static int s_gens; private static int s_frames; private static int s_rooms; private static double s_worstMs; private static float s_nextLog; internal static ConfigEntry<bool> ConfigLearned; private static readonly Dictionary<string, float> s_cost = new Dictionary<string, float>(); private static bool s_costsLoaded; private static bool s_costsDirty; private static int s_ownFrame; private static readonly Vector3[] s_lastPos = (Vector3[])(object)new Vector3[32]; private static readonly float[] s_lastAt = new float[32]; private static int s_lastNext; private static int c_dupSpawn; private static bool LearnedOn { get { if (ConfigLearned != null) { return ConfigLearned.Value; } return false; } } private static string CostPath => Path.Combine(Paths.ConfigPath, "FiresFixes_dungeon_room_ms.txt"); internal static void InitConfig(ConfigFile config) { ConfigEnabled = config.Bind<bool>("02 - Client Performance", "Spread Dungeon Room Spawns", true, Cfg.Adv("When a dungeon or cave loads near you, its rooms are put in a few per frame instead of all in one frame. Same rooms in the same places; the area counts as loading until every room is in.")); ConfigLearned = config.Bind<bool>("02 - Client Performance", "Dungeon Rooms Use Learned Cost", true, Cfg.Adv("Remembers how long each dungeon room takes to build (in a small file next to this config) and gives a heavy room a frame of its own instead of stacking it after lighter ones. Same rooms in the same places.")); } private static bool Resolve() { if (s_resolved) { return !s_broken; } s_resolved = true; try { s_loadedRooms = AccessTools.Field(typeof(DungeonGenerator), "m_loadedRooms"); Type? obj = s_loadedRooms?.FieldType.GetElementType(); s_roomData = AccessTools.Field(obj, "m_roomData"); s_position = AccessTools.Field(obj, "m_position"); s_rotation = AccessTools.Field(obj, "m_rotation"); s_placeRoom = AccessTools.Method(typeof(DungeonGenerator), "PlaceRoom", new Type[5] { typeof(RoomData), typeof(Vector3), typeof(Quaternion), typeof(RoomConnection), typeof(SpawnMode) }, (Type[])null); s_release = AccessTools.Method(typeof(DungeonGenerator), "ReleaseHeldReferences", (Type[])null, (Type[])null); s_broken = s_loadedRooms == null || s_roomData == null || s_position == null || s_rotation == null || s_placeRoom == null || s_release == null; } catch { s_broken = true; } if (s_broken) { LoggerOptions.LogWarning("[DungeonSpread] this game version's DungeonGenerator differs; dungeon rooms spawn as in vanilla"); } return !s_broken; } [HarmonyPatch(typeof(DungeonGenerator), "Spawn")] [HarmonyPrefix] [HarmonyPriority(800)] private static bool SpawnPrefix(DungeonGenerator __instance) { //IL_0056: Unknown result type (might be due to invalid IL or missing references) if (s_finishing || ConfigEnabled == null || !ConfigEnabled.Value || (Object)(object)__instance == (Object)null || !Resolve()) { return true; } if (s_pending.Contains(__instance)) { c_dupSpawn++; LoggerOptions.LogDebug($"[DungeonSpread] '{((Object)__instance).name}' at {((Component)__instance).transform.position:F0} asked to spawn again while its rooms are still going in: refused (they would be placed twice)"); return false; } if (!(s_loadedRooms.GetValue(__instance) is Array { Length: >1 } array)) { return true; } s_pending.Add(__instance); ((MonoBehaviour)__instance).StartCoroutine(PlaceOverFrames(__instance, array)); return false; } [HarmonyPatch(typeof(DungeonGenerator), "ReleaseHeldReferences")] [HarmonyPrefix] private static bool ReleasePrefix(DungeonGenerator __instance) { if (!s_releasing) { return !s_pending.Contains(__instance); } return true; } [HarmonyPatch(typeof(DungeonGenerator), "OnDestroy")] [HarmonyPrefix] private static void DestroyPrefix(DungeonGenerator __instance) { s_pending.Remove(__instance); } private static IEnumerator PlaceOverFrames(DungeonGenerator gen, Array rooms) { Stopwatch sw = new Stopwatch(); int placed = 0; int frames = 0; double worst = 0.0; bool failed = false; while (placed < rooms.Length) { frames++; long num = (long)((double)(FrameHeadroom.Take("dungeon", 6f) * (float)Stopwatch.Frequency) / 1000.0); sw.Restart(); int num2 = 0; try { while (placed < rooms.Length && (num2 == 0 || sw.ElapsedTicks < num)) { object value = rooms.GetValue(placed); object value2 = s_roomData.GetValue(value); string text = RoomName(value2); if (num2 > 0 && LearnedOn && text != null && s_cost.TryGetValue(text, out var value3) && sw.ElapsedTicks + (long)((double)(value3 * (float)Stopwatch.Frequency) / 1000.0) > num) { s_ownFrame++; break; } long elapsedTicks = sw.ElapsedTicks; s_placeRoom.Invoke(gen, new object[5] { value2, s_position.GetValue(value), s_rotation.GetValue(value), null, (object)(SpawnMode)1 }); placed++; num2++; if (text != null) { Learn(text, (float)((double)(sw.ElapsedTicks - elapsedTicks) * 1000.0 / (double)Stopwatch.Frequency)); } } } catch (Exception ex) { LoggerOptions.LogWarning($"[DungeonSpread] placing room {placed + 1} of {rooms.Length} in '{((Object)gen).name}' threw; the rest go in now as in vanilla. {ex.InnerException?.Message ?? ex.Message}"); failed = true; } double num3 = (double)sw.ElapsedTicks * 1000.0 / (double)Stopwatch.Frequency; FrameHeadroom.Used("dungeon", sw.ElapsedTicks); if (num3 > worst) { worst = num3; } if (failed) { break; } if (placed < rooms.Length) { yield return null; } if ((Object)(object)gen == (Object)null) { yield break; } } if (!((Object)(object)gen == (Object)null)) { int num4 = rooms.Length - placed; Array array = Array.CreateInstance(rooms.GetType().GetElementType(), num4); if (num4 > 0) { Array.Copy(rooms, placed, array, 0, num4); } s_loadedRooms.SetValue(gen, array); s_finishing = true; try { AccessTools.Method(typeof(DungeonGenerator), "Spawn", (Type[])null, (Type[])null).Invoke(gen, null); } finally { s_finishing = false; } s_pending.Remove(gen); s_releasing = true; try { s_release.Invoke(gen, null); } finally { s_releasing = false; } s_gens++; s_frames += frames; s_rooms += rooms.Length; if (worst > s_worstMs) { s_worstMs = worst; } string text2 = Again(((Component)gen).transform.position); LoggerOptions.LogDebug(string.Format("[DungeonSpread] '{0}' at {1:F0} (id {2}){3}: {4} room(s) over {5} frame(s), worst frame {6:0} ms{7}", ((Object)gen).name, ((Component)gen).transform.position, ((Object)gen).GetInstanceID(), text2, rooms.Length, frames, worst, failed ? " (finished in vanilla after a throw)" : "") + (LearnedOn ? $"; {s_ownFrame} known-heavy room(s) given their own frame, {s_cost.Count} room cost(s) known" : "")); s_ownFrame = 0; Report(); } } private static string RoomName(object roomData) { RoomData val = (RoomData)((roomData is RoomData) ? roomData : null); GameObject val2 = ((val != null && val.m_prefab.IsValid) ? val.m_prefab.Asset : null); if (!((Object)(object)val2 != (Object)null)) { return null; } return ((Object)val2).name; } private static void Learn(string name, float ms) { if (!LearnedOn) { return; } LoadCosts(); if (s_cost.TryGetValue(name, out var value)) { float num = ((ms > value) ? ms : (value * 0.75f + ms * 0.25f)); if (Mathf.Abs(num - value) < 0.5f) { return; } s_cost[name] = num; } else { if (s_cost.Count >= 2048) { return; } s_cost[name] = ms; } s_costsDirty = true; } private static void LoadCosts() { if (s_costsLoaded) { return; } s_costsLoaded = true; try { if (!File.Exists(CostPath)) { return; } string[] array = File.ReadAllLines(CostPath); foreach (string text in array) { int num = text.LastIndexOf('\t'); if (num > 0 && float.TryParse(text.Substring(num + 1), NumberStyles.Float, CultureInfo.InvariantCulture, out var result)) { s_cost[text.Substring(0, num)] = result; } } LoggerOptions.LogDebug($"[DungeonSpread] {s_cost.Count} learned room cost(s) read"); } catch (Exception ex) { LoggerOptions.LogDebug("[DungeonSpread] learned room costs not read: " + ex.Message); } } private static string Again(Vector3 pos) { //IL_0079: Unknown result type (might be due to invalid IL or missing references) //IL_007a: 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_0029: 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) //IL_002f: Unknown result type (might be due to invalid IL or missing references) float unscaledTime = Time.unscaledTime; string result = ""; for (int i = 0; i < s_lastPos.Length; i++) { if (s_lastAt[i] > 0f) { Vector3 val = s_lastPos[i] - pos; if (((Vector3)(ref val)).sqrMagnitude < 1f) { result = $", BUILT AGAIN at this spot {unscaledTime - s_lastAt[i]:0} s after the last time"; s_lastAt[i] = unscaledTime; return result; } } } s_lastPos[s_lastNext] = pos; s_lastAt[s_lastNext] = unscaledTime; s_lastNext = (s_lastNext + 1) % s_lastPos.Length; return result; } internal static void ShutdownSave() { SaveCosts(); } private static void SaveCosts() { if (!s_costsDirty) { return; } s_costsDirty = false; try { List<string> list = new List<string>(s_cost.Count); foreach (KeyValuePair<string, float> item in s_cost) { list.Add(item.Key + "\t" + item.Value.ToString("0.0", CultureInfo.InvariantCulture)); } File.WriteAllLines(CostPath, list); } catch (Exception ex) { LoggerOptions.LogDebug("[DungeonSpread] learned room costs not written: " + ex.Message); } } internal static void Report() { float unscaledTime = Time.unscaledTime; if (!(unscaledTime < s_nextLog)) { if (s_nextLog > 0f && s_gens > 0) { LoggerOptions.LogDebug($"[DungeonSpread] dungeon/location gen spread (last 30 s): {s_gens} generation(s), {s_rooms} room(s), worst frame {s_worstMs:0} ms, frames used {s_frames}"); } s_nextLog = unscaledTime + 30f; s_gens = (s_frames = (s_rooms = 0)); s_worstMs = 0.0; } } } [HarmonyPatch] internal static class FireplaceFuelTicks { private enum Decision { NotOurs, Write, Defer } public static ConfigEntry<bool> ConfigEnabled; private const double DeferSeconds = 30.0; private const double MisdrainFraction = 0.01; private static readonly FieldRef<Fireplace, ZNetView> s_nview = AccessTools.FieldRefAccess<Fireplace, ZNetView>("m_nview"); private static Action<Fireplace> s_updateState; private static bool s_bound; internal static long TicksDeferred; internal static long TicksRun; public static void InitConfig(ConfigFile config) { ConfigEnabled = config.Bind<bool>("04 - Networking", "Slow Fuel Ticks On Long Burning Fires", true, Cfg.Adv("Torches and slow fires send fuel updates less often. Fuel burns the same.")); } [HarmonyPatch(typeof(Fireplace), "UpdateFireplace")] [HarmonyPrefix] public static bool UpdateFireplace_Prefix(Fireplace __instance) { switch (Decide(__instance)) { case Decision.Defer: TicksDeferred++; return false; case Decision.Write: TicksRun++; return true; default: return true; } } private static Decision Decide(Fireplace __instance) { try { if (__instance.m_secPerFuel <= 0f) { return Decision.NotOurs; } ZNetView val = s_nview.Invoke(__instance); if ((Object)(object)val == (Object)null || !val.IsValid() || !val.IsOwner()) { return Decision.NotOurs; } ZDO zDO = val.GetZDO(); if (zDO == null || (Object)(object)ZNet.instance == (Object)null) { return Decision.NotOurs; } if (ConfigEnabled == null || !ConfigEnabled.Value) { return Decision.Write; } long num = zDO.GetLong(ZDOVars.s_lastTime, 0L); if (num == 0L) { return Decision.Write; } double num2 = (double)(ZNet.instance.GetTime().Ticks - num) / 10000000.0; if (num2 < 0.0 || num2 >= 30.0) { return Decision.Write; } if (!__instance.m_infiniteFuel && 30.0 / (double)__instance.m_secPerFuel > (double)__instance.m_maxFuel * 0.01) { return Decision.Write; } if (!BindUpdateState()) { return Decision.Write; } s_updateState(__instance); return Decision.Defer; } catch { return Decision.NotOurs; } } private static bool BindUpdateState() { if (s_bound) { return s_updateState != null; } s_bound = true; MethodInfo methodInfo = AccessTools.Method(typeof(Fireplace), "UpdateState", (Type[])null, (Type[])null); if (methodInfo != null) { s_updateState = (Action<Fireplace>)Delegate.CreateDelegate(typeof(Action<Fireplace>), methodInfo); } if (s_updateState == null) { LoggerOptions.LogWarning("[Fireplace] UpdateState not found; fuel ticks are left on vanilla's two second beat."); } return s_updateState != null; } internal static string TakeReportLine() { if (TicksDeferred == 0L && TicksRun == 0L) { return null; } long num = TicksDeferred + TicksRun; string result = $"[Upload] Fire fuel ticks on fires this machine owns: {TicksRun:N0} written, " + $"{TicksDeferred:N0} held back ({((num > 0) ? (TicksDeferred * 100 / num) : 0)}%)."; TicksDeferred = 0L; TicksRun = 0L; return result; } } internal static class MovedFromFgn { [HarmonyPatch(typeof(ZNetScene), "Shutdown")] private static class ClearOnUnload { [HarmonyPostfix] private static void Postfix() { try { TerrainRebuildSpread.Clear(); } catch { } try { DungeonSpawnSpread.ShutdownSave(); } catch { } } } internal static ConfigEntry<bool> FixSlowSleep; internal static ConfigEntry<bool> ConfigFixGroundSnapThroughFloors; internal static ConfigEntry<bool> ConfigEnableInvulnerableSupportSkip; internal static ConfigEntry<bool> ConfigEnableCapeCrashDiagnostics; internal static ConfigEntry<bool> ConfigEnableFallThroughDiagnostics; internal static ConfigEntry<float> ConfigCartPushUpWheelDepth; internal static Plugin Host; internal static void Bind(ConfigFile c) { FixSlowSleep = c.Bind<bool>("12 - Advanced", "Fix Slow Sleep On Busy Servers", true, Cfg.Adv("Morning arrives on time when sleeping on a laggy server.")); FireplaceFuelTicks.InitConfig(c); TerrainRebuildSpread.InitConfig(c); DungeonSpawnSpread.InitConfig(c); ZdoDeserializeNoDelegates.InitConfig(c); RegenerateCensus.InitConfig(c); FarIdleCreatureTicks.InitConfig(c); AiDisabledGuard.InitConfig(c); ConfigFixGroundSnapThroughFloors = c.Bind<bool>("12 - Advanced", "Fix Ground Snap Through Floors", true, Cfg.Adv("Stops tombstones and dropped items popping up through floors built below ground. Players and creatures that really are under the terrain are still lifted.")); ConfigCartPushUpWheelDepth = c.Bind<float>("12 - Advanced", "Cart push-up wheel depth (m)", 0.5f, Cfg.Adv("A cart is only pushed back up out of the ground when one of its wheels is at least this far below the terrain under it. Carts on or against build pieces are left alone.")); ConfigEnableInvulnerableSupportSkip = c.Bind<bool>("12 - Advanced", "Enable Invulnerable Support Skip", true, Cfg.Adv("Pieces that cannot be damaged skip the structural support check, which they never need.")); ConfigEnableCapeCrashDiagnostics = c.Bind<bool>("01 - General", "Enable Cape Crash Diagnostics", false, Cfg.Adv("Debug log for crashes during cape setup. Very noisy. Restart.")); ConfigEnableFallThroughDiagnostics = c.Bind<bool>("01 - General", "Enable Fall-Through Diagnostics", false, Cfg.Adv("Debug log for items and tombstones sinking through floors. Costs performance. Restart.")); Plugin.Log.LogInfo((object)"[FiresFixes] single-player split: 13 features moved in from FiresGhettoNetworking (fireplace fuel writes, sleep skip, spawn and terrain-compiler guards, terrain rebuild spread, dungeon room spread, ZDO read without delegates, fgn_tamecheck, terrain rebuild census, ground snap on clients and hosts, invulnerable support skip, cape and fall-through diagnostics)"); } } internal static class LoggerOptions { internal static bool DebugEnabled => FfLog.DebugOn; internal static bool VerboseEnabled => true; internal static void LogError(object o) { Plugin.Log.LogError(o); } internal static void LogWarning(object o) { Plugin.Log.LogWarning(o); } internal static void LogMessage(object o) { Plugin.Log.LogMessage(o); } internal static void LogInfo(object o) { Plugin.Log.LogInfo(o); } internal static void LogDebug(object o) { Plugin.Log.LogDebug(o); } } internal static class Cfg { internal static ConfigDescription Basic(string text, AcceptableValueBase range = null) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Expected O, but got Unknown return new ConfigDescription(text, range, Array.Empty<object>()); } internal static ConfigDescription Adv(string text, AcceptableValueBase range = null) { //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Expected O, but got Unknown return new ConfigDescription(text, range, new object[1] { new ConfigurationManagerAttributes { IsAdvanced = true } }); } internal static ConfigDescription Hidden(string text, AcceptableValueBase range = null) { //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Expected O, but got Unknown return new ConfigDescription(text, range, new object[1] { new ConfigurationManagerAttributes { Browsable = false } }); } } internal static class ValheimCommunityPatchCompat { private const string RecoveryType = "ValheimCommunityPatch.Patches.Terrain.TerrainCompNullHmapPatch"; private static bool s_checked; private static bool s_attached; private static FieldInfo s_enabled; internal static bool RecoversTerrainCompilers { get { if (!s_checked) { s_checked = true; Patches patchInfo = Harmony.GetPatchInfo((MethodBase)AccessTools.DeclaredMethod(typeof(TerrainComp), "Update", Type.EmptyTypes, (Type[])null)); if (patchInfo != null) { foreach (Patch prefix in patchInfo.Prefixes) { if (prefix.PatchMethod?.DeclaringType?.FullName == "ValheimCommunityPatch.Patches.Terrain.TerrainCompNullHmapPatch") { s_attached = true; break; } } } if (s_attached) { Type type = AccessTools.TypeByName("ValheimCommunityPatch.Patches.Terrain.TerrainCompNullHmapPatch"); s_enabled = ((type != null) ? AccessTools.Field(type, "Enabled") : null); } } if (s_attached) { if (s_enabled?.GetValue(null) is ConfigEntry<bool> val) { return val.Value; } return true; } return false; } } } internal static class ServerClientUtils { internal static readonly bool IsDedicatedProcess = Paths.ProcessName.StartsWith("valheim_server", StringComparison.OrdinalIgnoreCase); internal static bool ZNetIsDedicated() { if ((Object)(object)ZNet.instance != (Object)null) { return ZNet.instance.IsDedicated(); } return false; } } public static class SolidSurface { public const string DefaultLayerCsv = "Default,static_solid,Default_small,piece,terrain,vehicle"; private static int _cachedMask; private static string _cachedLayerCsv; public static int Mask() { string text = "Default,static_solid,Default_small,piece,terrain,vehicle"; if (_cachedLayerCsv == text && _cachedMask != 0) { return _cachedMask; } int num = ParseLayerMask(text); if (num == 0) { LoggerOptions.LogWarning("[SolidSurface] '" + text + "' matched no layers in this build; falling back to terrain only."); num = LayerMask.GetMask(new string[1] { "terrain" }); } _cachedMask = num; _cachedLayerCsv = text; return num; } private static int ParseLayerMask(string layerCsv) { List<string> list = new List<string>(); string[] array = layerCsv.Split(new char[1] { ',' }); for (int i = 0; i < array.Length; i++) { string text = array[i]?.Trim(); if (!string.IsNullOrEmpty(text)) { list.Add(text); } } if (list.Count <= 0) { return 0; } return LayerMask.GetMask(list.ToArray()); } } [HarmonyPatch(typeof(ZSyncTransform), "OwnerSync")] internal static class KinematicOwnerSyncGuard { private static int s_skipped; private static float s_next; [HarmonyPrefix] private static void Prefix(ZNetView ___m_nview, Rigidbody ___m_body, bool ___m_wasOwner, ref bool ___m_syncBodyVelocity, out bool __state) { __state = false; if (!___m_wasOwner && ___m_syncBodyVelocity && !((Object)(object)___m_body == (Object)null) && ___m_body.isKinematic && !((Object)(object)___m_nview == (Object)null)) { ZDO zDO = ___m_nview.GetZDO(); if (zDO != null && zDO.IsOwner()) { ___m_syncBodyVelocity = false; __state = true; s_skipped++; } } } [HarmonyPostfix] private static void Postfix(ref bool ___m_syncBodyVelocity, bool __state) { if (!__state) { return; } ___m_syncBodyVelocity = true; if (Time.unscaledTime >= s_next) { s_next = Time.unscaledTime + 30f; if (LoggerOptions.DebugEnabled) { LoggerOptions.LogDebug($"[KinematicSync] last 30 s: {s_skipped} ownership takeover(s) of a kinematic body skipped the velocity copy (no velocity on a held body)"); } s_skipped = 0; } } } [HarmonyPatch] public static class GroundSnapPatches { private const float ProbeStartHeightAboveObject = 2f; private const float ProbeMaxDistance = 8f; private const float MaxCartTiltDegrees = 45f; private const float SupportAboveTolerance = 0.05f; private static readonly RaycastHit[] s_hits = (RaycastHit[])(object)new RaycastHit[16]; private static int s_vehicleLayer = -2; private const float VanillaUnderWorldMargin = 1f; private const float FloorHoldSeconds = 5f; private const float FloorHoldGapSeconds = 0.5f; private static float s_floorSince; private static float s_floorLastSeen; private static int s_terrainMask; private static readonly Collider[] s_touch = (Collider[])(object)new Collider[16]; private static int s_pieceMask; private static readonly Dictionary<int, string> s_lastWhy = new Dictionary<int, string>(); private static bool Prepare() { return !ServerClientUtils.IsDedicatedProcess; } [HarmonyPatch(typeof(Character), "UnderWorldCheck")] [HarmonyTranspiler] public static IEnumerable<CodeInstruction> Character_UnderWorldCheck_UseSupportProbe(IEnumerable<CodeInstruction> instructions) { return RedirectGroundHeightToSupportProbe(instructions, "Character.UnderWorldCheck"); } [HarmonyPatch(typeof(TombStone), "PositionCheck")] [HarmonyTranspiler] public static IEnumerable<CodeInstruction> TombStone_PositionCheck_UseSupportProbe(IEnumerable<CodeInstruction> instructions) { return RedirectGroundHeightToSupportProbe(instructions, "TombStone.PositionCheck"); } [HarmonyPatch(typeof(ItemDrop), "TerrainCheck")] [HarmonyTranspiler] public static IEnumerable<CodeInstruction> ItemDrop_TerrainCheck_UseSupportProbe(IEnumerable<CodeInstruction> instructions) { return RedirectGroundHeightToSupportProbe(instructions, "ItemDrop.TerrainCheck"); } [HarmonyPatch(typeof(Floating), "TerrainCheck")] [HarmonyTranspiler] public static IEnumerable<CodeInstruction> Floating_TerrainCheck_UseSupportProbe(IEnumerable<CodeInstruction> instructions) { return RedirectGroundHeightToSupportProbe(instructions, "Floating.TerrainCheck"); } private static IEnumerable<CodeInstruction> RedirectGroundHeightToSupportProbe(IEnumerable<CodeInstruction> instructions, string patchedMethod) { //IL_009c: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Expected O, but got Unknown //IL_00db: Unknown result type (might be due to invalid IL or missing references) //IL_00e5: Expected O, but got Unknown List<CodeInstruction> list = new List<CodeInstruction>(instructions); MethodInfo methodInfo = AccessTools.Method(typeof(GroundSnapPatches), "SupportOrGroundHeightFor", (Type[])null, (Type[])null); int num = 0; for (int i = 0; i < list.Count; i++) { if (!(list[i].opcode != OpCodes.Call) || !(list[i].opcode != OpCodes.Callvirt)) { MethodInfo methodInfo2 = list[i].operand as MethodInfo; if (!(methodInfo2 == null) && !(methodInfo2.Name != "GetGroundHeight") && methodInfo2.GetParameters().Length == 1) { CodeInstruction val = new CodeInstruction(OpCodes.Ldarg_0, (object)null); val.labels.AddRange(list[i].labels); val.blocks.AddRange(list[i].blocks); list[i] = new CodeInstruction(OpCodes.Call, (object)methodInfo); list.Insert(i, val); i++; num++; } } } if (num == 0) { LoggerOptions.LogWarning("[GroundSnap] " + patchedMethod + " has no GetGroundHeight call to redirect; vanilla behaviour stands there."); } return list; } public static float SupportOrGroundHeight(ZoneSystem zoneSystem, Vector3 point) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return SupportOrGroundHeightFor(zoneSystem, point, null); } private static int VehicleLayer() { if (s_vehicleLayer == -2) { s_vehicleLayer = LayerMask.NameToLayer("vehicle"); } return s_vehicleLayer; } public static float SupportOrGroundHeightFor(ZoneSystem zoneSystem, Vector3 point, Component self) { //IL_0001: 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_003c: 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_0074: 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_007f: 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) //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_01c3: Unknown result type (might be due to invalid IL or missing references) //IL_019d: Unknown result type (might be due to invalid IL or missing references) //IL_0101: Unknown result type (might be due to invalid IL or missing references) //IL_010b: Unknown result type (might be due to invalid IL or missing references) //IL_01f0: Unknown result type (might be due to invalid IL or missing references) //IL_01f7: Unknown result type (might be due to invalid IL or missing references) //IL_01d1: Unknown result type (might be due to invalid IL or missing references) //IL_01e8: Unknown result type (might be due to invalid IL or missing references) //IL_016f: Unknown result type (might be due to invalid IL or missing references) float groundHeight = zoneSystem.GetGroundHeight(point); ConfigEntry<bool> configFixGroundSnapThroughFloors = MovedFromFgn.ConfigFixGroundSnapThroughFloors; if (configFixGroundSnapThroughFloors != null && !configFixGroundSnapThroughFloors.Value) { return groundHeight; } Vagon val = (((Object)(object)self != (Object)null) ? self.GetComponentInParent<Vagon>() : null); if ((Object)(object)val != (Object)null) { return CartDecision(zoneSystem, val, self, point); } if (point.y >= groundHeight) { return groundHeight; } Character val2 = (Character)(object)((self is Character) ? self : null); if (val2 != null) { return CharacterDecision(point, groundHeight, val2); } Transform val3 = (((Object)(object)self != (Object)null) ? self.transform : null); int num = Physics.RaycastNonAlloc(point + Vector3.up * 2f, Vector3.down, s_hits, 8f, SolidSurface.Mask(), (QueryTriggerInteraction)1); float num2 = float.MaxValue; float num3 = groundHeight; string text = null; for (int i = 0; i < num; i++) { Collider collider = ((RaycastHit)(ref s_hits[i])).collider; if (!((Object)(object)collider == (Object)null) && (!((Object)(object)val3 != (Object)null) || !((Component)collider).transform.IsChildOf(val3)) && !(((RaycastHit)(ref s_hits[i])).point.y > point.y + 0.05f) && (!((Object)(object)((Component)collider).GetComponentInParent<WearNTear>() == (Object)null) || ((Component)collider).gameObject.layer == VehicleLayer()) && ((RaycastHit)(ref s_hits[i])).distance < num2) { num2 = ((RaycastHit)(ref s_hits[i])).distance; num3 = ((RaycastHit)(ref s_hits[i])).point.y; text = ((Object)collider).name; } } if (num2 < float.MaxValue) { Why(self, point, string.Format("skip: resting on {0} at {1:0.0}, not the terrain", text ?? "a surface", num3)); return num3; } string text2 = TouchingPiece(self, point, val3); if (text2 != null) { Why(self, point, "skip: wedged against piece " + text2 + ", not on the terrain"); return point.y; } Why(self, point, $"snapped: sunk {groundHeight - point.y:0.0} m into the terrain, nothing under it"); return groundHeight; } private static float CharacterDecision(Vector3 point, float terrain, Character character) { //IL_0001: 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_0019: Unknown result type (might be due to invalid IL or missing references) //IL_0127: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_011f: Unknown result type (might be due to invalid IL or missing references) //IL_00ea: Unknown result type (might be due to invalid IL or missing references) float num = terrain - point.y; if (num <= 1f) { if (LoggerOptions.DebugEnabled) { Why((Component)(object)character, point, $"skip: only {num:0.0} m under the terrain, within vanilla's {1f:0} m"); } return terrain; } if (CarvedGroundUnder(point, out var y)) { if (LoggerOptions.DebugEnabled) { Why((Component)(object)character, point, $"skip: carved terrain collider at {y:0.0}, under the surface at {terrain:0.0}"); } return y; } float num2 = 0f; if (character.IsPlayer() && character.IsOnGround() && (Object)(object)character.m_lastGroundCollider != (Object)null) { WearNTear componentInParent = ((Component)character.m_lastGroundCollider).GetComponentInParent<WearNTear>(); if ((Object)(object)componentInParent != (Object)null) { float time = Time.time; if (time - s_floorLastSeen > 0.5f) { s_floorSince = time; } s_floorLastSeen = time; num2 = time - s_floorSince; if (num2 < 5f) { if (LoggerOptions.DebugEnabled) { Why((Component)(object)character, point, string.Format("hold: standing on piece {0}, {1:0.0} m under the terrain; lifted after {2:0} s if the terrain does not drop", ((Object)componentInParent).name.Replace("(Clone)", ""), num, 5f)); } return point.y; } } } Why((Component)(object)character, point, $"snapped: {num:0.0} m under the terrain at {terrain:0.0}" + ((num2 > 0f) ? $", stood on a piece for {num2:0.0} s" : "")); return terrain; } private static bool CarvedGroundUnder(Vector3 point, out float y) { //IL_0026: 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_0031: 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) //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_00b8: Unknown result type (might be due to invalid IL or missing references) y = 0f; if (s_terrainMask == 0) { s_terrainMask = LayerMask.GetMask(new string[1] { "terrain" }); } int num = Physics.RaycastNonAlloc(point + Vector3.up * 0.5f, Vector3.down, s_hits, 8f, s_terrainMask, (QueryTriggerInteraction)1); float num2 = float.MaxValue; for (int i = 0; i < num; i++) { Collider collider = ((RaycastHit)(ref s_hits[i])).collider; if (!((Object)(object)collider == (Object)null) && !((Object)(object)((Component)collider).GetComponent<Heightmap>() != (Object)null) && ((RaycastHit)(ref s_hits[i])).distance < num2) { num2 = ((RaycastHit)(ref s_hits[i])).distance; y = ((RaycastHit)(ref s_hits[i])).point.y; } } return num2 < float.MaxValue; } private static float CartDecision(ZoneSystem zoneSystem, Vagon cart, Component self, Vector3 point) { //IL_0008: 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_003f: 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_0037: 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_005c: 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_0080: Unknown result type (might be due to invalid IL or missing references) //IL_01b6: Unknown result type (might be due to invalid IL or missing references) //IL_01c3: Unknown result type (might be due to invalid IL or missing references) //IL_01c8: Unknown result type (might be due to invalid IL or missing references) //IL_01cc: Unknown result type (might be due to invalid IL or missing references) //IL_01d1: Unknown result type (might be due to invalid IL or missing references) //IL_01d3: Unknown result type (might be due to invalid IL or missing references) //IL_0197: Unknown result type (might be due to invalid IL or missing references) //IL_01af: Unknown result type (might be due to invalid IL or missing references) //IL_0219: Unknown result type (might be due to invalid IL or missing references) //IL_0239: Unknown result type (might be due to invalid IL or missing references) //IL_01f2: Unknown result type (might be due to invalid IL or missing references) //IL_01f7: Unknown result type (might be due to invalid IL or missing references) //IL_01f9: Unknown result type (might be due to invalid IL or missing references) //IL_020e: Unknown result type (might be due to invalid IL or missing references) //IL_0131: Unknown result type (might be due to invalid IL or missing references) Transform transform = ((Component)cart).transform; float num = Vector3.Angle(transform.up, Vector3.up); if (num > 45f) { Why(self, point, $"skip: tilted {num:0} deg from upright (hung or wedged on purpose)"); return point.y; } string text = TouchingPiece((Component)(object)cart, point, transform); if (text != null) { Why(self, point, "skip: resting on or wedged against piece " + text); return point.y; } if (cart.m_wheels == null || cart.m_wheels.Length == 0) { Why(self, point, "skip: no wheels to measure"); return point.y; } float num2 = MovedFromFgn.ConfigCartPushUpWheelDepth?.Value ?? 0.5f; float num3 = 0f; StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < cart.m_wheels.Length; i++) { Rigidbody val = cart.m_wheels[i]; if (!((Object)(object)val == (Object)null)) { string text2 = i switch { 1 => "R", 0 => "L", _ => i.ToString(), }; if (WheelOnPiece(val, transform, out var name)) { stringBuilder.Append(" wheel " + text2 + " on piece " + name + " -> skip;"); } else { float num4 = zoneSystem.GetGroundHeight(val.position) - WheelBottom(val); stringBuilder.Append(string.Format(" wheel {0} {1:0.00} m below terrain -> {2};", text2, num4, (num4 >= num2) ? "snap" : "skip")); num3 = Mathf.Max(num3, num4); } } } if (num3 < num2) { Why(self, point, $"skip:{stringBuilder} (needs {num2:0.0} m)"); return point.y; } Vector3 val2 = Vector3.up * (num3 + 0.05f); transform.position += val2; Rigidbody component = ((Component)cart).GetComponent<Rigidbody>(); if ((Object)(object)component != (Object)null) { component.position += val2; if (!component.isKinematic) { component.linearVelocity = Vector3.zero; } } Why(self, point, $"snapped:{stringBuilder} lifted {num3 + 0.05f:0.00} m"); return transform.position.y; } private static bool WheelOnPiece(Rigidbody wheel, Transform own, out string name) { //IL_0004: 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_0022: Unknown result type (might be due to invalid IL or missing references) name = null; float num = wheel.position.y - WheelBottom(wheel) + 0.3f; int num2 = Physics.RaycastNonAlloc(wheel.position, Vector3.down, s_hits, num, SolidSurface.Mask(), (QueryTriggerInteraction)1); for (int i = 0; i < num2; i++) { Collider collider = ((RaycastHit)(ref s_hits[i])).collider; if (!((Object)(object)collider == (Object)null) && !((Component)collider).transform.IsChildOf(own)) { WearNTear componentInParent = ((Component)collider).GetComponentInParent<WearNTear>(); if ((Object)(object)componentInParent != (Object)null) { name = ((Object)componentInParent).name.Replace("(Clone)", ""); return true; } } } return false; } private static float WheelBottom(Rigidbody wheel) { //IL_0054: 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_002d: 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) float num = float.MaxValue; Collider[] componentsInChildren = ((Component)wheel).GetComponentsInChildren<Collider>(); foreach (Collider val in componentsInChildren) { if ((Object)(object)val != (Object)null && !val.isTrigger) { float num2 = num; Bounds bounds = val.bounds; num = Mathf.Min(num2, ((Bounds)(ref bounds)).min.y); } } if (!(num < float.MaxValue)) { return wheel.position.y; } return num; } private static string TouchingPiece(Component self, Vector3 point, Transform own) { //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_0038: 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_0043: 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) //IL_00d9: Unknown result type (might be due to invalid IL or missing references) //IL_00da: Unknown result type (might be due to invalid IL or missing references) //IL_00e0: 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_00b7: Unknown result type (might be due to invalid IL or missing references) //IL_00bc: Unknown result type (might be due to invalid IL or missing references) //IL_00bf: Unknown result type (might be due to invalid IL or missing references) //IL_00c4: 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) //IL_00d3: Unknown result type (might be due to invalid IL or missing references) //IL_00d8: Unknown result type (might be due to invalid IL or missing references) //IL_009a: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Unknown result type (might be due to invalid IL or missing references) //IL_0090: Unknown result type (might be due to invalid IL or missing references) if (s_pieceMask == 0) { s_pieceMask = LayerMask.GetMask(new string[4] { "piece", "piece_nonsolid", "Default", "static_solid" }); } Vector3 val = point; Vector3 val2 = Vector3.one * 0.6f; if ((Object)(object)self != (Object)null) { bool flag = false; Bounds val3 = default(Bounds); Collider[] componentsInChildren = self.GetComponentsInChildren<Collider>(); foreach (Collider val4 in componentsInChildren) { if (!((Object)(object)val4 == (Object)null) && !val4.isTrigger) { if (!flag) { val3 = val4.bounds; flag = true; } else { ((Bounds)(ref val3)).Encapsulate(val4.bounds); } } } if (flag) { val = ((Bounds)(ref val3)).center; val2 = ((Bounds)(ref val3)).extents + Vector3.one * 0.3f; } } int num = Physics.OverlapBoxNonAlloc(val, val2, s_touch, Quaternion.identity, s_pieceMask, (QueryTriggerInteraction)1); for (int j = 0; j < num; j++) { Collider val5 = s_touch[j]; if (!((Object)(object)val5 == (Object)null) && (!((Object)(object)own != (Object)null) || !((Component)val5).transform.IsChildOf(own))) { WearNTear componentInParent = ((Component)val5).GetComponentInParent<WearNTear>(); if ((Object)(object)componentInParent != (Object)null) { return ((Object)componentInParent).name.Replace("(Clone)", ""); } } } return null; } private static void Why(Component self, Vector3 point, string what) { //IL_00b8: Unknown result type (might be due to invalid IL or missing references) //IL_00c6: Unknown result type (might be due to invalid IL or missing references) //IL_00d4: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)self == (Object)null)) { int instanceID = ((Object)self).GetInstanceID(); string text = (what.StartsWith("snapped") ? "snapped" : (what.Substring(0, what.IndexOf(':') + 1) + what.Split(new char[1] { ' ' })[1])); if (!s_lastWhy.TryGetValue(instanceID, out var value) || !(value == text)) { s_lastWhy[instanceID] = text; bool flag = (Object)(object)self.GetComponentInParent<Vagon>() != (Object)null; LoggerOptions.LogDebug(string.Format("[{0}] {1} at ({2:0.0},{3:0.0},{4:0.0}) {5}", flag ? "CartSnap" : "GroundSnap", ((Object)self).name.Replace("(Clone)", ""), point.x, point.y, point.z, what)); } } } } [HarmonyPatch] public static class WearNTearClientSupportPatches { private static readonly FieldRef<WearNTear, float> _supportField = AccessTools.FieldRefAccess<WearNTear, float>("m_support"); [HarmonyReversePatch(/*Could not decode attribute arguments.*/)] [HarmonyPatch(typeof(WearNTear), "GetMaxSupport")] public static float CallGetMaxSupport(WearNTear self) { throw new NotImplementedException("Harmony reverse patch failed for WearNTear.GetMaxSupport"); } public static bool TrySkip(WearNTear __instance) { return !UpdateSupport_Prefix(__instance); } private static bool UpdateSupport_Prefix(WearNTear __instance) { ConfigEntry<bool> configEnableInvulnerableSupportSkip = MovedFromFgn.ConfigEnableInvulnerableSupportSkip; if (configEnableInvulnerableSupportSkip == null || !configEnableInvulnerableSupportSkip.Value) { return true; } if ((Object)(object)ZNet.instance != (Object)null && ZNet.instance.IsDedicated()) { return true; } if (!WearNTearClassifier.IsFullyInvulnerable(__instance)) { return true; } try { float num = CallGetMaxSupport(__instance); _supportField.Invoke(__instance) = num; ZNetView nview = __instance.m_nview; if ((Object)(object)nview != (Object)null && nview.IsValid() && nview.IsOwner()) { nview.GetZDO().Set(ZDOVars.s_support, num); } } catch (Exception ex) { LoggerOptions.LogWarning("[WNT-Support] Skip threw, falling back to vanilla: " + ex.Message); return true; } return false; } } public static class WearNTearClassifier { public static bool IsFullyInvulnerable(WearNTear wnt) { //IL_0011: 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_003b: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_005f: 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_0083: 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_00a7: Unknown result type (might be due to invalid IL or missing references) //IL_00b9: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)wnt == (Object)null) { return false; } if (IsZeroOrIgnored(wnt.m_damages.m_blunt) && IsZeroOrIgnored(wnt.m_damages.m_slash) && IsZeroOrIgnored(wnt.m_damages.m_pierce) && IsZeroOrIgnored(wnt.m_damages.m_chop) && IsZeroOrIgnored(wnt.m_damages.m_pickaxe) && IsZeroOrIgnored(wnt.m_damages.m_fire) && IsZeroOrIgnored(wnt.m_damages.m_frost) && IsZeroOrIgnored(wnt.m_damages.m_lightning) && IsZeroOrIgnored(wnt.m_damages.m_poison)) { return IsZeroOrIgnored(wnt.m_damages.m_spirit); } return false; } private static bool IsZeroOrIgnored(DamageModifier mod) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Invalid comparison between Unknown and I4 //IL_0004: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Invalid comparison between Unknown and I4 if ((int)mod != 3) { return (int)mod == 4; } return true; } } [HarmonyPatch] public static class FallThroughProbe { private const float SettleSeconds = 0.25f; private const float RecheckSeconds = 3f; private const float RayStartAbove = 0.3f; private const float RayMaxDistance = 8f; private const float FellDropMeters = 0.5f; private static int s_groundMask; private static bool s_maskReady; private static bool Prepare() { if (MovedFromFgn.ConfigEnableFallThroughDiagnostics != null) { return MovedFromFgn.ConfigEnableFallThroughDiagnostics.Value; } return false; } private static int GroundMask() { if (!s_maskReady) { s_groundMask = SolidSurface.Mask(); s_maskReady = true; } return s_groundMask; } private static Vector3 Up(Vector3 pos) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) return FgnRing.Up(pos); } [HarmonyPatch(typeof(ItemDrop), "Awake")] [HarmonyPostfix] public static void ItemDrop_Awake_Probe(ItemDrop __instance) { Begin(((Object)(object)__instance != (Object)null) ? ((Component)__instance).gameObject : null, "ItemDrop"); } [HarmonyPatch(typeof(TombStone), "Awake")] [HarmonyPostfix] public static void TombStone_Awake_Probe(TombStone __instance) { Begin(((Object)(object)__instance != (Object)null) ? ((Component)__instance).gameObject : null, "TombStone"); } private static void Begin(GameObject go, string kind) { if (!((Object)(object)go == (Object)null) && !((Object)(object)MovedFromFgn.Host == (Object)null)) { ((MonoBehaviour)MovedFromFgn.Host).StartCoroutine(Track(go, kind)); } } private static IEnumerator Track(GameObject go, string kind) { yield return (object)new WaitForSeconds(0.25f); if ((Object)(object)go == (Object)null) { yield break; } ZNetView component = go.GetComponent<ZNetView>(); Vector3 spawnPos = go.transform.position; Vector3 up = Up(spawnPos); if (((Vector3)(ref spawnPos)).sqrMagnitude < 1f) { yield break; } bool flag = (Object)(object)component != (Object)null && component.IsValid() && component.IsOwner(); RaycastHit val = default(RaycastHit); bool flag2 = Physics.Raycast(spawnPos + up * 0.3f, -up, ref val, 8f, GroundMask(), (QueryTriggerInteraction)1); string beneath = (flag2 ? $"{((Object)((Component)((RaycastHit)(ref val)).collider).gameObject).name}@{((RaycastHit)(ref val)).distance:F2}m" : "NONE"); if (!flag2) { LoggerOptions.LogDebug($"[FallProbe] SPAWN {kind} pos=({spawnPos.x:F1},{spawnPos.y:F1},{spawnPos.z:F1}) " + $"owner={flag} beneath=NONE"); } yield return (object)new WaitForSeconds(3f); if (!((Object)(object)go == (Object)null)) { Vector3 position = go.transform.position; float num = Vector3.Dot(spawnPos - position, up); if (num > 0.5f) { RaycastHit val2 = default(RaycastHit); string text = (Physics.Raycast(position + up * 0.3f, -up, ref val2, 8f, GroundMask(), (QueryTriggerInteraction)1) ? $"{((Object)((Component)((RaycastHit)(ref val2)).collider).gameObject).name}@{((RaycastHit)(ref val2)).distance:F2}m" : "NONE"); LoggerOptions.LogInfo($"[FallProbe] FELL {kind} drop={num:F2}m spawn=({spawnPos.x:F1},{spawnPos.y:F1},{spawnPos.z:F1}) " + $"now=({position.x:F1},{position.y:F1},{position.z:F1}) spawnBeneath={beneath} nowBeneath={text}"); } } } } [HarmonyPatch] public static class CapeCrashDiagnostics { private const int MaxPathDepth = 12; private const int MaxStackFrames = 14; private const int CreationBurstLogCount = 25; private const float HeartbeatIntervalSec = 5f; private static readonly FieldInfo ClothCollidersField = AccessTools.Field(typeof(VisEquipment), "m_clothColliders"); private static readonly Dictionary<int, int[]> s_colliderSnapshots = new Dictionary<int, int[]>(); private static float s_nextHeartbeat; private static PropertyInfo s_magicaTeamProperty; private static PropertyInfo s_magicaTeamCountProperty; private static bool s_magicaTeamResolved; public static bool Enabled => MovedFromFgn.ConfigEnableCapeCrashDiagnostics?.Value ?? false; private static bool Prepare() { if (Enabled) { return !ServerClientUtils.IsDedicatedProcess; } return false; } public static void Log(string message) { if (Enabled) { ManualLogSource log = Plugin.Log; if (log != null) { log.LogMessage((object)$"[CapeDiag {DateTime.Now:HH:mm:ss.fff}] {message}"); } } } [HarmonyPatch(typeof(Player), "StartDoodadControl")] [HarmonyPostfix] public static void Player_StartDoodadControl_Postfix(Player __instance, IDoodadController shipControl) { if (Enabled && !((Object)(object)__instance != (Object)(object)Player.m_localPlayer)) { Component val = (Component)(object)((shipControl is Component) ? shipControl : null); Log(string.Format("Local player took control of '{0}' (frame {1})", ((Object)(object)val != (Object)null) ? ((Object)val).name : "unknown", Time.frameCount)); } } [HarmonyPatch(typeof(Player), "StopDoodadControl")] [HarmonyPrefix] public static void Player_StopDoodadControl_Prefix(Player __instance) { if (Enabled && !((Object)(object)__instance != (Object)(object)Player.m_localPlayer)) { Log($"Local player released ship control (frame {Time.frameCount})"); } } [HarmonyPatch(typeof(VisEquipment), "SetShoulderEquipped")] [HarmonyPrefix] public static void VisEquipment_SetShoulderEquipped_Prefix(VisEquipment __instance, int hash, int variant, int quality, int ___m_currentShoulderItemHash, int ___m_currentShoulderItemVariant, int ___m_currentShoulderItemQuality, ZNetView ___m_nview) { if (Enabled && (___m_currentShoulderItemHash != hash || ___m_currentShoulderItemVariant != variant || ___m_currentShoulderItemQuality != quality)) { bool flag = (Object)(object)Player.m_localPlayer != (Object)null && (Object)(object)((Component)__instance).gameObject == (Object)(object)((Component)Player.m_localPlayer).gameObject; Log($"Shoulder item change on '{((Object)__instance).name}' ({DescribeView(___m_nview)}, player={__instance.m_isPlayer}, local={flag}, frame {Time.frameCount}): " + $"{___m_currentShoulderItemHash}/{___m_currentShoulderItemVariant}/q{___m_currentShoulderItemQuality} -> {hash}/{variant}/q{quality}; called from {ShortStack()}"); } } [HarmonyPatch(typeof(VisEquipment), "SetupCloth")] [HarmonyPrefix] public static void VisEquipment_SetupCloth_Prefix(VisEquipment __instance, GameObject item) { if (!Enabled) { return; } IList list = ClothCollidersField?.GetValue(__instance) as IList; Log(string.Format("SetupCloth '{0}' on '{1}' (frame {2}, cloth teams {3}): ", ((Object)(object)item != (Object)null) ? ((Object)item).name : "null", ((Object)__instance).name, Time.frameCount, MagicaTeamCount()) + ((list == null) ? "no collider list" : (list.Count + " cloth collider(s)"))); if (list == null) { return; } for (int i = 0; i < list.Count; i++) { object obj = list[i]; if (obj == null) { Log($" collider[{i}]: null reference"); continue; } Log($" collider[{i}]: checking"); Object val = (Object)((obj is Object) ? obj : null); if (val == null) { Log($" collider[{i}]: not a Unity object ({obj.GetType().FullName})"); continue; } if (val == (Object)null) { Log($" collider[{i}]: destroyed (instance {val.GetInstanceID()})"); continue; } Component val2 = (Component)(object)((val is Component) ? val : null); Behaviour val3 = (Behaviour)(object)((val is Behaviour) ? val : null); Log($" collider[{i}]: {((object)val).GetType().Name} instance {val.GetInstanceID()} " + $"at '{(((Object)(object)val2 != (Object)null) ? PathOf(val2.transform) : val.name)}' active={(Object)(object)val3 == (Object)null || val3.isActiveAndEnabled}"); } } [HarmonyPatch(typeof(VisEquipment), "SetupCloth")] [HarmonyPostfix] public static void VisEquipment_SetupCloth_Postfix(GameObject item) { if (Enabled) { Log("SetupCloth '" + (((Object)(object)item != (Object)null) ? ((Object)item).name : "null") + "' finished"); } } [HarmonyPatch(typeof(VisEquipment), "CustomUpdate")] [HarmonyPostfix] public static void VisEquipment_CustomUpdate_Postfix(VisEquipment __instance) { if (!Enabled) { return; } if ((Object)(object)Player.m_localPlayer != (Object)null && (Object)(object)((Component)__instance).gameObject == (Object)(object)((Component)Player.m_localPlayer).gameObject) { Heartbeat(); } if (!(ClothCollidersField?.GetValue(__instance) is IList { Count: not 0 } list)) { return; } int instanceID = ((Object)__instance).GetInstanceID(); if (!s_colliderSnapshots.TryGetValue(instanceID, out var value)) { s_colliderSnapshots[instanceID] = ColliderIds(list); return; } string text = FindColliderListChange(list, value); if (text != null) { Log($"COLLIDER LIST CHANGED on '{((Object)__instance).name}' (frame {Time.frameCount}): {text}"); s_colliderSnapshots[instanceID] = ColliderIds(list); } } [HarmonyPatch(typeof(VisEquipment), "OnDisable")] [HarmonyPostfix] public static void VisEquipment_OnDisable_Postfix(VisEquipment __instance) { s_colliderSnapshots.Remove(((Object)__instance).GetInstanceID()); } [HarmonyPatch(typeof(ZNetScene), "CreateDistantObjects")] [HarmonyPostfix] public unsafe static void ZNetScene_CreateDistantObjects_Postfix(int maxCreatedPerFrame, ref int created) { //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) if (!Enabled || created < 25) { return; } FfMarkers.Ensure(); AutoScope val = ((ProfilerMarker)(ref FfMarkers.CreateDistantLog)).Auto(); try { Log($"Created {created} objects in frame {Time.frameCount} (per-frame cap {maxCreatedPerFrame})"); } finally { ((IDisposable)(*(AutoScope*)(&val))/*cast due to .constrained prefix*/).Dispose(); } } [HarmonyPatch(typeof(ZDO), "Deserialize")] [HarmonyPostfix] public static void ZDO_Deserialize_Postfix(ZDO __instance) { //IL_0042: Unknown result type (might be due to invalid IL or missing references) if (Enabled) { Player localPlayer = Player.m_localPlayer; if (!((Object)(object)localPlayer == (Object)null) && !((Object)(object)((Character)localPlayer).m_nview == (Object)null) && ((Character)localPlayer).m_nview.GetZDO() == __instance) { Log($"Received data overwrote the local player's ZDO {__instance.m_uid} (data rev {__instance.DataRevision}, owner {__instance.GetOwner()}, ours={__instance.IsOwner()}, frame {Time.frameCount})"); } } } private static void Heartbeat() { float realtimeSinceStartup = Time.realtimeSinceStartup; if (!(realtimeSinceStartup < s_nextHeartbeat)) { s_nextHeartbeat = realtimeSinceStartup + 5f; int num = (((Object)(object)ZNetScene.instance != (Object)null) ? ZNetScene.instance.m_instances.Count : (-1)); Log($"Heartbeat frame {Time.frameCount}: managed heap {GC.GetTotalMemory(forceFullCollection: false) / 1048576} MB, GC {GC.CollectionCount(0)}, " + $"objects {num}, cloth teams {MagicaTeamCount()}"); } } private static int[] ColliderIds(IList colliders) { int[] array = new int[colliders.Count]; for (int i = 0; i < array.Length; i++) { int num = i; object? obj = colliders[i]; Object val = (Object)((obj is Object) ? obj : null); array[num] = ((val != null) ? val.GetInstanceID() : 0); } return array; } private static string FindColliderListChange(IList colliders, int[] expected) { if (colliders.Count != expected.Length) { return $"count {expected.Length} -> {colliders.Count}"; } for (int i = 0; i < expected.Length; i++) { object obj = colliders[i]; if (obj == null) { if (expected[i] != 0) { return $"[{i}] instance {expected[i]} -> null reference"; } return null; } Object val = (Object)((obj is Object) ? obj : null); if (val == null) { return $"[{i}] instance {expected[i]} -> non-Unity object {obj.GetType().FullName}"; } if (val.GetInstanceID() != expected[i]) { return $"[{i}] instance {expected[i]} -> {DescribeObject(obj)}"; } } return null; } private static int MagicaTeamCount() { try { if (!s_magicaTeamResolved) { s_magicaTeamResolved = true; s_magicaTeamProperty = AccessTools.Property(AccessTools.TypeByName("MagicaCloth2.MagicaManager"), "Team"); s_magicaTeamCountProperty = AccessTools.Property(AccessTools.TypeByName("MagicaCloth2.TeamManager"), "TeamCount"); } object obj = s_magicaTeamProperty?.GetValue(null); return (obj != null && s_magicaTeamCountProperty != null) ? ((int)s_magicaTeamCountProperty.GetValue(obj)) : (-1); } catch { return -1; } } private static string ShortStack() { StackFrame[] frames = new StackTrace(2, fNeedFileInfo: false).GetFrames(); if (frames == null) { return "unknown"; } StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < frames.Length && i < 14; i++) { MethodBase method = frames[i].GetMethod(); if (!(method == null)) { if (stringBuilder.Length > 0) { stringBuilder.Append(" < "); } stringBuilder.Append((method.DeclaringType != null) ? (method.DeclaringType.Name + "." + method.Name) : method.Name); } } return stringBuilder.ToString(); } internal static string DescribeObject(object value) { if (value == null) { return "null reference"; } Object val = (Object)((value is Object) ? value : null); if (val == null) { return value.GetType().FullName; } if (val == (Object)null) { return $"destroyed {value.GetType().Name} (instance {val.GetInstanceID()})"; } Component val2 = (Component)(object)((val is Component) ? val : null); return $"{value.GetType().Name} instance {val.GetInstanceID()} at '{(((Object)(object)val2 != (Object)null) ? PathOf(val2.transform) : val.name)}'"; } private static string DescribeView(ZNetView view) { //IL_0032: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)view == (Object)null) { return "no ZNetView"; } if (!view.IsValid()) { return "invalid ZNetView"; } ZDO zDO = view.GetZDO(); return $"zdo {zDO.m_uid} owner {zDO.GetOwner()} ours={zDO.IsOwner()} data rev {zDO.DataRevision}"; } private static string PathOf(Transform transform) { StringBuilder stringBuilder = new StringBuilder(((Object)transform).name); Transform parent = transform.parent; int num = 0; while ((Object)(object)parent != (Object)null && num < 12) { stringBuilder.Insert(0, ((Object)parent).name + "/"); num++; parent = parent.parent; } return stringBuilder.ToString(); } } [HarmonyPatch] public static class MagicaColliderRegistrationDiagnostics { private const string ColliderManagerTypeName = "MagicaCloth2.ColliderManager"; public static bool Prepare() { if (CapeCrashDiagnostics.Enabled && !ServerClientUtils.IsDedicatedProcess) { return AccessTools.TypeByName("MagicaCloth2.ColliderManager") != null; } return false; } public static MethodBase TargetMethod() { return AccessTools.Method(AccessTools.TypeByName("MagicaCloth2.ColliderManager"), "AddCollider", (Type[])null, (Type[])null); } [HarmonyPrefix] public static void Prefix(object[] __args) { if (CapeCrashDiagnostics.Enabled) { CapeCrashDiagnostics.Log(" MagicaCloth2 AddCollider " + CapeCrashDiagnostics.DescribeObject((__args.Length > 1) ? __args[1] : null)); } } [HarmonyPostfix] public static void Postfix() { if (CapeCrashDiagnostics.Enabled) { CapeCrashDiagnostics.Log(" MagicaCloth2 AddCollider returned"); } } } [HarmonyPatch] public static class MagicaClothLifecycleDiagnostics { private const string MagicaClothTypeName = "MagicaCloth2.MagicaCloth"; public static bool Prepare() { if (CapeCrashDiagnostics.Enabled && !ServerClientUtils.IsDedicatedProcess) { return AccessTools.TypeByName("MagicaCloth2.MagicaCloth") != null; } return false; } public static IEnumerable<MethodBase> TargetMethods() { Type cloth = AccessTools.TypeByName("MagicaCloth2.MagicaCloth"); yield return AccessTools.Method(cloth, "BuildAndRun", (Type[])null, (Type[])null); yield return AccessTools.Method(cloth, "OnDestroy", (Type[])null, (Type[])null); } [HarmonyPrefix] public static void Prefix(object __instance, MethodBase __originalMethod) { if (CapeCrashDiagnostics.Enabled) { CapeCrashDiagnostics.Log($"MagicaCloth {__originalMethod.Name} on {CapeCrashDiagnostics.DescribeObject(__instance)} (frame {Time.frameCount})"); } } } internal static class FgnRing { private delegate bool TryUp(Vector3 pos, out Vector3 up); private static bool s_looked; private static Func<bool> s_on; private static Func<Vector3, Vector2s> s_zone; private static Func<Vector2s, Vector2s, Vector2s> s_delta; private static Func<Vector3, Vector3, float> s_dist; private static int s_onAt = int.MinValue; private static bool s_onCached; private static bool s_upLooked; private static TryUp s_tryUp; internal static bool On { get { int tickCount = Environment.TickCount; if (tickCount - s_onAt < 250 && s_onAt != int.MinValue) { return s_onCached; } Look(); bool result = false; if (s_on != null) { try { result = s_on(); } catch (Exception) { result = false; } } s_onCached = result; s_onAt = tickCount; return result; } } private static void Look() { if (s_looked) { return; } s_looked = true; try { Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); for (int i = 0; i < assemblies.Length; i++) { Type type = assemblies[i].GetType("VerdantsAscent.FatApi", throwOnError: false); if (!(type == null)) { MethodInfo methodInfo = type.GetProperty("HaloZonesOn", BindingFlags.Static | BindingFlags.Public)?.GetGetMethod(); MethodInfo method = type.GetMethod("HaloZone", BindingFlags.Static | BindingFlags.Public, null, new Type[1] { typeof(Vector3) }, null); MethodInfo method2 = type.GetMethod("HaloZoneDelta", BindingFlags.Static | BindingFlags.Public, null, new Type[2] { typeof(Vector2s), typeof(Vector2s) }, null); MethodInfo method3 = type.GetMethod("HaloSurfaceDistance", BindingFlags.Static | BindingFlags.Public, null, new Type[2] { typeof(Vector3), typeof(Vector3) }, null); if (!(methodInfo == null) && !(method == null) && !(method2 == null) && !(method3 == null)) { s_on = (Func<bool>)Delegate.CreateDelegate(typeof(Func<bool>), methodInfo); s_zone = (Func<Vector3, Vector2s>)Delegate.CreateDelegate(typeof(Func<Vector3, Vector2s>), method); s_delta = (Func<Vector2s, Vector2s, Vector2s>)Delegate.CreateDelegate(typeof(Func<Vector2s, Vector2s, Vector2s>), method2); s_dist = (Func<Vector3, Vector3, float>)Delegate.CreateDelegate(typeof(Func<Vector3, Vector3, float>), method3); LoggerOptions.LogInfo("[FGN halo] bound FAT's ring object sectors (FatApi.HaloZone / HaloZoneDelta / HaloSurfaceDistance)"); } break; } } } catch (Exception) { s_on = null; s_zone = null; s_delta = null; s_dist = null; } } internal static Vector3 Up(Vector3 p) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) return -Down(p); } internal static Vector2s Sector(Vector3 p) { //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_001f: 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_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0027: 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_0015: 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) if (!On) { return ZoneSystem.GetZone(p); } try { return s_zone(p); } catch (Exception) { return ZoneSystem.GetZone(p); } } internal static Vector2s Delta(Vector2s a, Vector2s b) { //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_003e: 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) //IL_004b: 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_0057: Unknown result type (might be due to invalid IL or missing references) //IL_0007: 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_0014: 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_0021: Unknown result type (might be due to invalid IL or missing references) //IL_005a: 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_002f: 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) if (!On) { return new Vector2s(b.x - a.x, b.y - a.y); } try { return s_delta(a, b); } catch (Exception) { return new Vector2s(b.x - a.x, b.y - a.y); } } internal static Vector3 Down(Vector3 p) { //IL_00d1: Unknown result type (might be due to invalid IL or missing references) //IL_00d6: Unknown result type (might be due to invalid IL or missing references) //IL_00da: 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_00b5: Unknown result type (might be due to invalid IL or missing references) //IL_00c6: Unknown result type (might be due to invalid IL or missing references) //IL_00c7: Unknown result type (might be due to invalid IL or missing references) //IL_00bf: Unknown result type (might be due to invalid IL or missing references) //IL_00cc: Unknown result type (might be due to invalid IL or missing references) if (!s_upLooked) { s_upLooked = true; try { Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); for (int i = 0; i < assemblies.Length; i++) { MethodInfo methodInfo = assemblies[i].GetType("VerdantsAscent.FatApi", throwOnError: false)?.GetMethod("HaloTryGetUp", BindingFlags.Static | BindingFlags.Public, null, new Type[2] { typeof(Vector3), typeof(Vector3).MakeByRefType() }, null); if (!(methodInfo == null)) { s_tryUp = (TryUp)Delegate.CreateDelegate(typeof(TryUp), methodInfo); break; } } } catch (Exception) { s_tryUp = null; } } if (s_tryUp == null) { return Vector3.down; } try { Vector3 up; return s_tryUp(p, out up) ? (-up) : Vector3.down; } catch (Exception) { return Vector3.down; } } internal static float PriorityDistanceSqr(Vector3 a, Vector3 b) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) return PriorityDistanceSqr(a, b, On); } internal static float PriorityDistanceSqr(Vector3 a, Vector3 b, bool ringOn) { //IL_0017: 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_0024: 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) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) if (ringOn) { try { float num = s_dist(a, b); return num * num; } catch (Exception) { } } float num2 = a.x - b.x; float num3 = a.z - b.z; return num2 * num2 + num3 * num3; } } [HarmonyPatch] internal static class RegenerateCensus { private sealed class Row { public int Count; public int Full; public int Paint; public int Repeat; } internal static ConfigEntry<bool> ConfigEnabled; private const int SampleEvery = 4; private const float ReportSeconds = 10f; private const float RepeatSeconds = 2f; private static readonly Dictionary<string, Row> s_rows = new Dictionary<string, Row>(); private static readonly Dictionary<Heightmap, string> s_pokedBy = new Dictionary<Heightmap, string>(); private static readonly Dictionary<Heightmap, int> s_pokeFrame = new Dictionary<Heightmap, int>(); private static readonly Dictionary<Heightmap, float> s_lastRegen = new Dictionary<Heightmap, float>(); private static readonly Dictionary<Heightmap, uint> s_lastStamp = new Dictionary<Heightmap, uint>(); private static readonly Dictionary<string, Row> s_repeats = new Dictionary<string, Row>(); private static readonly Dictionary<Heightmap, string> s_queuedBy = new Dictionary<Heightmap, string>(); private const int MaxHashes = 4096; private static readonly Dictionary<Heightmap, ulong> s_heightHash = new Dictionary<Heightmap, ulong>(); private static int s_collisionBuilds; private static int s_collisionSame; private static long s_collisionTicks; private static int s_calls; private static int s_seq; private static int s_skipped; private static float s_nextReport = -1f; private static bool s_infoLogged; private static bool On { get { if (ConfigEnabled != null && ConfigEnabled.Value) { return LoggerOptions.DebugEnabled; } return false; } } private static bool Prepare() { return ConfigEnabled != null; } internal static void InitConfig(ConfigFile config) { ConfigEnabled = config.Bind<bool>("14 - Diagnostics", "Regenerate Census", false, Cfg.Adv("Debug only: counts who asks for terrain tile rebuilds, one log line every 10 seconds (for testing).")); ConfigEnabled.SettingChanged += delegate { Clear(); }; ConfigEnabled.SettingChanged += delegate { Plugin.Log.LogInfo((object)("[FiresFixes] Regenerate Census now " + (ConfigEnabled.Value ? "ON" : "OFF") + ", applied live: counters cleared; " + (ConfigEnabled.Value ? "counting from now (Debug lines every 10 s)" : "hooks return at once"))); }; } private static void Clear() { s_rows.Clear(); s_repeats.Clear(); s_queuedBy.Clear(); s_pokedBy.Clear(); s_pokeFrame.Clear(); s_lastRegen.Clear(); s_lastStamp.Clear(); s_heightHash.Clear(); s_calls = (s_skipped = 0); s_nextReport = -1f; } private static string Caller(StackTrace st, out string path) { path = null; for (int i = 0; i < st.FrameCount; i++) { MethodBase methodBase = st.GetFrame(i)?.GetMethod(); if (methodBase == null) { continue; } Type declaringType = methodBase.DeclaringType; if (declaringType == null) { string text = methodBase.Name ?? ""; int num = text.IndexOf("Heightmap::", StringComparison.Ordinal); if (num >= 0 && path == null) { string text2 = text.Substring(num + 11).TrimEnd(new char[1] { '>' }); if (text2 != "Regenerate") { path = text2; } } else if (num < 0 && text.StartsWith("DMD<", StringComparison.Ordinal)) { return text.Substring(4).TrimEnd(new char[1] { '>' }).Replace("::", ".") + " (patched)"; } } else if (declaringType == typeof(Heightmap)) { string text3 = methodBase.Name ?? ""; if (text3.StartsWith("DMD<", StringComparison.Ordinal)) { int num2 = text3.IndexOf("::", StringComparison.Ordinal); text3 = ((num2 >= 0) ? text3.Substring(num2 + 2) : text3.Substring(4)).TrimEnd(new char[1] { '>' }); } if (path == null && text3 != "Regenerate") { path = text3; } } else if ((!(declaringType.Assembly == typeof(RegenerateCensus).Assembly) || declaringType.Namespace == null || !(declaringType == typeof(RegenerateCensus))) && (declaringType.FullName == null || !declaringType.FullName.StartsWith("HarmonyLib", StringComparison.Ordinal))) { return declaringType.Name + "." + methodBase.Name + " (" + declaringType.Assembly.GetName().Name + ")"; } } return "(no caller frame)"; } [HarmonyPatch(typeof(Heightmap), "Poke")] [HarmonyPrefix] private static void PokePrefix(Heightmap __instance, int delayed) { if (!On || (Object)(object)__instance == (Object)null || delayed == 0) { return; } int frameCount = Time.frameCount; if (s_pokeFrame.TryGetValue(__instance, out var value) && value == frameCount) { return; } s_pokeFrame[__instance] = frameCount; try { s_pokedBy[__instance] = Caller(new StackTrace(1, fNeedFileInfo: false), out var _); } catch { } } internal static void RegeneratePrefix(Heightmap __instance, bool __runOriginal) { //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Invalid comparison between Unknown and I4 if (!On || (Object)(object)__instance == (Object)null) { return; } if (!__runOriginal) { s_skipped++; try { s_queuedBy[__instance] = Asker(__instance, new StackTrace(1, fNeedFileInfo: false)); return; } catch { return; } } s_calls++; try { float realtimeSinceStartup = Time.realtimeSinceStartup; bool flag = (int)__instance.m_regenRequest == 1; float value; bool flag2 = s_lastRegen.TryGetValue(__instance, out value) && realtimeSinceStartup - value < 2f; s_lastRegen[__instance] = realtimeSinceStartup; uint num = Stamp(__instance); uint value2; bool flag3 = s_lastStamp.TryGetValue(__instance, out value2) && value2 != num; s_lastStamp[__instance] = num; bool flag4 = ++s_seq % 4 == 0; if (!flag4 && !flag2) { return; } string text = Asker(__instance, new StackTrace(1, fNeedFileInfo: false)); if (text.StartsWith("direct <- TerrainRebuildSpread.Drain", StringComparison.Ordinal) || text.StartsWith("direct <- TerrainRebuildSpread.ForceAllPre", StringComparison.Ordinal)) { text = text.Substring(0, (text.IndexOf(" (", StringComparison.Ordinal) < 0) ? text.Length : text.IndexOf(" (", StringComparison.Ordinal)) + " for [" + (s_queuedBy.TryGetValue(__instance, out var value3) ? value3 : "as