using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.IO.Compression; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using BalrondBetterBuild.Config; using BalrondBetterBuild.Core; using BalrondBetterBuild.Runtime; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using JetBrains.Annotations; using Microsoft.CodeAnalysis; using ServerSync; using TMPro; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: AssemblyTitle("BalrondBetterBuild")] [assembly: AssemblyDescription("Event-driven cached structural integrity replacement for Valheim.")] [assembly: AssemblyCompany("Balrond")] [assembly: AssemblyProduct("BalrondBetterBuild")] [assembly: AssemblyCopyright("Copyright © Balrond 2026")] [assembly: ComVisible(false)] [assembly: Guid("d46e22d2-04cd-4df4-b90f-b4ea0c812b48")] [assembly: AssemblyFileVersion("0.3.7.0")] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("0.3.7.0")] [module: UnverifiableCode] namespace BalrondBetterBuild { [BepInPlugin("balrond.astafaraios.BalrondBetterBuild", "BalrondBetterBuild", "0.1.0")] public sealed class Launch : BaseUnityPlugin { public const string PluginGuid = "balrond.astafaraios.BalrondBetterBuild"; public const string PluginName = "BalrondBetterBuild"; public const string PluginVersion = "0.1.0"; private readonly Harmony harmony = new Harmony("balrond.astafaraios.BalrondBetterBuild"); internal static Launch Instance; internal static Harmony Harmony; internal static IntegrityService Integrity; internal static readonly ConfigSync ConfigSync = new ConfigSync("balrond.astafaraios.BalrondBetterBuild") { DisplayName = "BalrondBetterBuild", CurrentVersion = "0.1.0", MinimumRequiredVersion = "0.1.0" }; private bool worldSessionActive; internal static IntegrityMode RuntimeMode { get; private set; } internal static DiagnosticsLevel RuntimeDiagnostics { get; private set; } internal static bool InformationLoggingEnabled { get; private set; } internal static bool RuntimeStatisticsEnabled => InformationLoggingEnabled && RuntimeDiagnostics != DiagnosticsLevel.Off; internal static bool ProfilingEnabled => InformationLoggingEnabled && RuntimeDiagnostics == DiagnosticsLevel.Profiling; internal BetterBuildConfig Settings { get; private set; } internal static bool WorldSessionActive => (Object)(object)Instance != (Object)null && Instance.worldSessionActive; internal ConfigEntry SyncedConfig(string section, string key, T defaultValue, string description, bool synchronizedSetting) { //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Expected O, but got Unknown ConfigEntry val = ((BaseUnityPlugin)this).Config.Bind(section, key, defaultValue, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty())); SyncedConfigEntry syncedConfigEntry = ConfigSync.AddConfigEntry(val); syncedConfigEntry.SynchronizedConfig = synchronizedSetting; return val; } internal static void LogInfo(object message) { if (InformationLoggingEnabled) { if ((Object)(object)Instance != (Object)null) { ((BaseUnityPlugin)Instance).Logger.LogInfo(message); } else { Debug.Log((object)("[BalrondBetterBuild] " + message)); } } } internal static void LogWarning(object message) { if ((Object)(object)Instance != (Object)null) { ((BaseUnityPlugin)Instance).Logger.LogWarning(message); } else { Debug.LogWarning((object)("[BalrondBetterBuild] " + message)); } } internal static void LogError(object message) { if ((Object)(object)Instance != (Object)null) { ((BaseUnityPlugin)Instance).Logger.LogError(message); } else { Debug.LogError((object)("[BalrondBetterBuild] " + message)); } } private void Awake() { Instance = this; Harmony = harmony; Settings = new BetterBuildConfig(this); RefreshRuntimeFlags(); ConfigSync.AddLockingConfigEntry(Settings.LockConfiguration); WearNTearAccess.Initialize(((BaseUnityPlugin)this).Logger, Settings); MaterialProfiles.Initialize(Settings); Integrity = new IntegrityService(((BaseUnityPlugin)this).Logger, Settings); SubscribeConfigEvents(); harmony.PatchAll(); LogInfo("BalrondBetterBuild 0.1.0 loaded. Mode=" + RuntimeMode.ToString() + ", diagnostics=" + RuntimeDiagnostics.ToString() + "."); if (RuntimeMode == IntegrityMode.Replace) { ((BaseUnityPlugin)this).Logger.LogWarning((object)("Integrity replacement is active with safety arming and a session circuit breaker. Test on a copied world first. Vanilla support cache release is " + (Settings.ReleaseVanillaSupportCache.Value ? "ENABLED." : "disabled."))); } else { LogInfo("Plugin loaded. Integrity runtime will remain dormant until a world is active."); } } private void Update() { if (Integrity == null) { return; } if (!IsWorldRuntimeReady()) { if (worldSessionActive) { EndWorldSession(); } return; } if (!worldSessionActive) { BeginWorldSession(); } Integrity.Tick(Time.realtimeSinceStartup); } internal static void NotifyZNetSceneAwake() { if ((Object)(object)Instance != (Object)null) { Instance.TryBeginWorldSession(); } } private void TryBeginWorldSession() { if (!worldSessionActive && IsWorldRuntimeReady()) { BeginWorldSession(); } } private void BeginWorldSession() { worldSessionActive = true; Integrity.BeginWorldSession(Time.realtimeSinceStartup); if (RuntimeMode != IntegrityMode.Vanilla) { Integrity.RegisterExistingInstances(); } if (InformationLoggingEnabled) { ((BaseUnityPlugin)this).Logger.LogInfo((object)("Integrity world session started. Mode=" + RuntimeMode.ToString() + ", discovered=" + WearNTear.GetAllInstances().Count + ".")); } } private void EndWorldSession() { worldSessionActive = false; Integrity.Reset(); } private static bool IsWorldRuntimeReady() { return (Object)(object)ZNetScene.instance != (Object)null && ZDOMan.instance != null && (Object)(object)ZoneSystem.instance != (Object)null; } private void OnDestroy() { UnsubscribeConfigEvents(); if (worldSessionActive && Integrity != null) { EndWorldSession(); } if (Harmony != null) { Harmony.UnpatchSelf(); } if (Integrity != null) { Integrity.Reset(); } Integrity = null; Harmony = null; Instance = null; } private void SubscribeConfigEvents() { Settings.Mode.SettingChanged += OnGraphConfigChanged; Settings.SpatialCellSize.SettingChanged += OnGraphConfigChanged; Settings.ContactPadding.SettingChanged += OnGraphConfigChanged; Settings.MaximumOverlapResults.SettingChanged += OnGraphConfigChanged; Settings.MaximumIslandNodes.SettingChanged += OnGraphConfigChanged; Settings.SolveDebounceMilliseconds.SettingChanged += OnGraphConfigChanged; Settings.MaterialPreset.SettingChanged += OnGraphConfigChanged; Settings.CustomMaxSupportMultiplier.SettingChanged += OnGraphConfigChanged; Settings.CustomMinSupportMultiplier.SettingChanged += OnGraphConfigChanged; Settings.CustomHorizontalLossMultiplier.SettingChanged += OnGraphConfigChanged; Settings.CustomVerticalLossMultiplier.SettingChanged += OnGraphConfigChanged; Settings.WorkBudgetMilliseconds.SettingChanged += OnRuntimeConfigChanged; Settings.ActiveAreaReconcileSeconds.SettingChanged += OnRuntimeConfigChanged; Settings.RequireInitialStableGraphBeforeReplace.SettingChanged += OnRuntimeConfigChanged; Settings.MaximumPooledNodeLists.SettingChanged += OnRuntimeConfigChanged; Settings.MaximumRetainedNodeListCapacity.SettingChanged += OnRuntimeConfigChanged; Settings.MaximumPooledSpatialCellLists.SettingChanged += OnRuntimeConfigChanged; Settings.ApplySupportToZdo.SettingChanged += OnRuntimeConfigChanged; Settings.NetworkWriteEpsilon.SettingChanged += OnRuntimeConfigChanged; Settings.NetworkNormalizedWriteEpsilon.SettingChanged += OnRuntimeConfigChanged; Settings.OwnershipRecheckSeconds.SettingChanged += OnRuntimeConfigChanged; Settings.MaximumSupportZdoWritesPerFrame.SettingChanged += OnRuntimeConfigChanged; Settings.ReleaseVanillaSupportCache.SettingChanged += OnRuntimeConfigChanged; Settings.VanillaCacheReleaseStableSeconds.SettingChanged += OnRuntimeConfigChanged; Settings.VanillaCacheReleaseFallbackCooldownSeconds.SettingChanged += OnRuntimeConfigChanged; Settings.MaximumVanillaCacheReleasesPerFrame.SettingChanged += OnRuntimeConfigChanged; Settings.Diagnostics.SettingChanged += OnDiagnosticConfigChanged; Settings.EnableInformationLogging.SettingChanged += OnDiagnosticConfigChanged; Settings.DetailedTimingDiagnostics.SettingChanged += OnDiagnosticConfigChanged; } private void UnsubscribeConfigEvents() { if (Settings != null) { Settings.Mode.SettingChanged -= OnGraphConfigChanged; Settings.SpatialCellSize.SettingChanged -= OnGraphConfigChanged; Settings.ContactPadding.SettingChanged -= OnGraphConfigChanged; Settings.MaximumOverlapResults.SettingChanged -= OnGraphConfigChanged; Settings.MaximumIslandNodes.SettingChanged -= OnGraphConfigChanged; Settings.SolveDebounceMilliseconds.SettingChanged -= OnGraphConfigChanged; Settings.MaterialPreset.SettingChanged -= OnGraphConfigChanged; Settings.CustomMaxSupportMultiplier.SettingChanged -= OnGraphConfigChanged; Settings.CustomMinSupportMultiplier.SettingChanged -= OnGraphConfigChanged; Settings.CustomHorizontalLossMultiplier.SettingChanged -= OnGraphConfigChanged; Settings.CustomVerticalLossMultiplier.SettingChanged -= OnGraphConfigChanged; Settings.WorkBudgetMilliseconds.SettingChanged -= OnRuntimeConfigChanged; Settings.ActiveAreaReconcileSeconds.SettingChanged -= OnRuntimeConfigChanged; Settings.RequireInitialStableGraphBeforeReplace.SettingChanged -= OnRuntimeConfigChanged; Settings.MaximumPooledNodeLists.SettingChanged -= OnRuntimeConfigChanged; Settings.MaximumRetainedNodeListCapacity.SettingChanged -= OnRuntimeConfigChanged; Settings.MaximumPooledSpatialCellLists.SettingChanged -= OnRuntimeConfigChanged; Settings.ApplySupportToZdo.SettingChanged -= OnRuntimeConfigChanged; Settings.NetworkWriteEpsilon.SettingChanged -= OnRuntimeConfigChanged; Settings.NetworkNormalizedWriteEpsilon.SettingChanged -= OnRuntimeConfigChanged; Settings.OwnershipRecheckSeconds.SettingChanged -= OnRuntimeConfigChanged; Settings.MaximumSupportZdoWritesPerFrame.SettingChanged -= OnRuntimeConfigChanged; Settings.ReleaseVanillaSupportCache.SettingChanged -= OnRuntimeConfigChanged; Settings.VanillaCacheReleaseStableSeconds.SettingChanged -= OnRuntimeConfigChanged; Settings.VanillaCacheReleaseFallbackCooldownSeconds.SettingChanged -= OnRuntimeConfigChanged; Settings.MaximumVanillaCacheReleasesPerFrame.SettingChanged -= OnRuntimeConfigChanged; Settings.Diagnostics.SettingChanged -= OnDiagnosticConfigChanged; Settings.EnableInformationLogging.SettingChanged -= OnDiagnosticConfigChanged; Settings.DetailedTimingDiagnostics.SettingChanged -= OnDiagnosticConfigChanged; } } private void OnGraphConfigChanged(object sender, EventArgs eventArgs) { if (Integrity != null && worldSessionActive) { RefreshRuntimeFlags(); Integrity.MarkRuntimeOptionsDirty(); LogInfo("Integrity configuration changed. Rebuilding graph. Mode=" + RuntimeMode.ToString() + "."); Integrity.BeginWorldSession(Time.realtimeSinceStartup); if (RuntimeMode != IntegrityMode.Vanilla) { Integrity.RegisterExistingInstances(); } } } private void OnRuntimeConfigChanged(object sender, EventArgs eventArgs) { if (Integrity != null) { Integrity.MarkRuntimeOptionsDirty(); } } private void OnDiagnosticConfigChanged(object sender, EventArgs eventArgs) { RefreshRuntimeFlags(); if (Integrity != null) { Integrity.RefreshDiagnosticMode(); } } private void RefreshRuntimeFlags() { if (Settings == null) { RuntimeMode = IntegrityMode.Vanilla; RuntimeDiagnostics = DiagnosticsLevel.Off; InformationLoggingEnabled = false; } else { RuntimeMode = Settings.Mode.Value; RuntimeDiagnostics = Settings.Diagnostics.Value; InformationLoggingEnabled = Settings.EnableInformationLogging.Value; } } } } namespace BalrondBetterBuild.Runtime { internal sealed class BenchmarkRecorder { private struct ComparisonSample { internal readonly float RawDifference; internal readonly float NormalizedDifference; internal readonly float VisualDifference; internal readonly bool StabilityMismatch; internal readonly bool VisualMismatch; internal ComparisonSample(float rawDifference, float normalizedDifference, float visualDifference, bool stabilityMismatch, bool visualMismatch) { RawDifference = rawDifference; NormalizedDifference = normalizedDifference; VisualDifference = visualDifference; StabilityMismatch = stabilityMismatch; VisualMismatch = visualMismatch; } } private sealed class ComparisonAccumulator { private long comparisons; private long stabilityMismatches; private long visualMismatches; private double rawDifferenceSum; private double normalizedDifferenceSum; private double visualDifferenceSum; private float maximumRawDifference; private float maximumNormalizedDifference; private float maximumVisualDifference; internal void Add(ComparisonSample sample) { comparisons++; if (sample.StabilityMismatch) { stabilityMismatches++; } if (sample.VisualMismatch) { visualMismatches++; } rawDifferenceSum += sample.RawDifference; normalizedDifferenceSum += sample.NormalizedDifference; visualDifferenceSum += sample.VisualDifference; maximumRawDifference = Math.Max(maximumRawDifference, sample.RawDifference); maximumNormalizedDifference = Math.Max(maximumNormalizedDifference, sample.NormalizedDifference); maximumVisualDifference = Math.Max(maximumVisualDifference, sample.VisualDifference); } internal ComparisonTotals Snapshot() { return new ComparisonTotals(comparisons, stabilityMismatches, visualMismatches, (comparisons == 0L) ? 0.0 : (rawDifferenceSum / (double)comparisons), maximumRawDifference, (comparisons == 0L) ? 0.0 : (normalizedDifferenceSum / (double)comparisons), maximumNormalizedDifference, (comparisons == 0L) ? 0.0 : (visualDifferenceSum / (double)comparisons), maximumVisualDifference); } internal void Reset() { comparisons = 0L; stabilityMismatches = 0L; visualMismatches = 0L; rawDifferenceSum = 0.0; normalizedDifferenceSum = 0.0; visualDifferenceSum = 0.0; maximumRawDifference = 0f; maximumNormalizedDifference = 0f; maximumVisualDifference = 0f; } } private struct NodeComparison { internal readonly int NodeId; internal readonly string Name; internal readonly MaterialType MaterialType; internal readonly float VanillaSupport; internal readonly float GraphSupport; internal readonly float VanillaNormalized; internal readonly float GraphNormalized; internal readonly float VisualDifference; internal readonly bool StabilityMismatch; internal readonly bool VisualMismatch; internal readonly Vector3 Position; internal readonly int ZoneX; internal readonly int ZoneY; internal readonly float DistanceFromReference; internal readonly bool OutsideActiveArea; internal readonly AnchorKind Anchor; internal readonly int LinkCount; internal float NormalizedDifference => Math.Abs(VanillaNormalized - GraphNormalized); internal float Score { get { float num = Math.Max(NormalizedDifference, VisualDifference); return StabilityMismatch ? (num + 2f) : num; } } internal NodeComparison(int nodeId, string name, MaterialType materialType, float vanillaSupport, float graphSupport, float vanillaNormalized, float graphNormalized, float visualDifference, bool stabilityMismatch, bool visualMismatch, Vector3 position, int zoneX, int zoneY, float distanceFromReference, bool outsideActiveArea, AnchorKind anchor, int linkCount) { //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Unknown result type (might be due to invalid IL or missing references) NodeId = nodeId; Name = (string.IsNullOrEmpty(name) ? "WearNTear" : name); MaterialType = materialType; VanillaSupport = vanillaSupport; GraphSupport = graphSupport; VanillaNormalized = vanillaNormalized; GraphNormalized = graphNormalized; VisualDifference = visualDifference; StabilityMismatch = stabilityMismatch; VisualMismatch = visualMismatch; Position = position; ZoneX = zoneX; ZoneY = zoneY; DistanceFromReference = distanceFromReference; OutsideActiveArea = outsideActiveArea; Anchor = anchor; LinkCount = linkCount; } internal bool IsEquivalentTo(NodeComparison other, float epsilon) { //IL_0002: 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_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Unknown result type (might be due to invalid IL or missing references) //IL_00b0: Unknown result type (might be due to invalid IL or missing references) return MaterialType == other.MaterialType && Math.Abs(VanillaSupport - other.VanillaSupport) <= epsilon && Math.Abs(GraphSupport - other.GraphSupport) <= epsilon && StabilityMismatch == other.StabilityMismatch && VisualMismatch == other.VisualMismatch && Anchor == other.Anchor && LinkCount == other.LinkCount && ZoneX == other.ZoneX && ZoneY == other.ZoneY && OutsideActiveArea == other.OutsideActiveArea && Vector3.SqrMagnitude(Position - other.Position) <= 0.0001f; } } private sealed class MaterialSummaryAccumulator { private struct MaterialCurrentStats { internal int Nodes; internal int StabilityMismatches; internal int VisualMismatches; internal double NormalizedDifferenceSum; internal double VisualDifferenceSum; } private readonly Dictionary values = new Dictionary(); internal void Add(NodeComparison comparison) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Unknown result type (might be due to invalid IL or missing references) values.TryGetValue(comparison.MaterialType, out var value); value.Nodes++; value.NormalizedDifferenceSum += comparison.NormalizedDifference; value.VisualDifferenceSum += comparison.VisualDifference; if (comparison.StabilityMismatch) { value.StabilityMismatches++; } if (comparison.VisualMismatch) { value.VisualMismatches++; } values[comparison.MaterialType] = value; } internal string BuildSummary() { //IL_0086: 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_0093: Unknown result type (might be due to invalid IL or missing references) //IL_009d: Unknown result type (might be due to invalid IL or missing references) if (values.Count == 0) { return string.Empty; } List list = new List(values.Keys); list.Sort((MaterialType left, MaterialType right) => ((int)left).CompareTo((int)right)); StringBuilder stringBuilder = new StringBuilder(192); for (int num = 0; num < list.Count; num++) { if (num > 0) { stringBuilder.Append(" | "); } MaterialType val = list[num]; MaterialCurrentStats materialCurrentStats = values[val]; stringBuilder.Append(val); stringBuilder.Append(':'); stringBuilder.Append(materialCurrentStats.Nodes); stringBuilder.Append(" n="); stringBuilder.Append((materialCurrentStats.NormalizedDifferenceSum / (double)Math.Max(1, materialCurrentStats.Nodes)).ToString("F3")); stringBuilder.Append(" c="); stringBuilder.Append((materialCurrentStats.VisualDifferenceSum / (double)Math.Max(1, materialCurrentStats.Nodes)).ToString("F3")); stringBuilder.Append(" s="); stringBuilder.Append(materialCurrentStats.StabilityMismatches); stringBuilder.Append(" v="); stringBuilder.Append(materialCurrentStats.VisualMismatches); } return stringBuilder.ToString(); } } private const float Epsilon = 0.0001f; private readonly Dictionary latestByNode = new Dictionary(); private readonly ComparisonAccumulator lifetime = new ComparisonAccumulator(); private readonly ComparisonAccumulator window = new ComparisonAccumulator(); internal bool Record(int nodeId, string nodeName, MaterialType materialType, MaterialProfile material, float vanilla, float graph, bool vanillaStable, bool graphStable, float visualMismatchThreshold, float changeEpsilon, Vector3 position, int zoneX, int zoneY, float distanceFromReference, bool outsideActiveArea, AnchorKind anchor, int linkCount) { //IL_007e: 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) float rawDifference = Math.Abs(vanilla - graph); float num = NormalizeSupport(vanilla, material); float num2 = NormalizeSupport(graph, material); GetVisualValue(vanilla, material, out var value, out var blue); GetVisualValue(graph, material, out var value2, out var blue2); float num3 = ((blue != blue2) ? 1f : (blue ? 0f : Math.Abs(value - value2))); bool stabilityMismatch = vanillaStable != graphStable; bool visualMismatch = num3 >= Mathf.Clamp01(visualMismatchThreshold); NodeComparison nodeComparison = new NodeComparison(nodeId, nodeName, materialType, vanilla, graph, num, num2, num3, stabilityMismatch, visualMismatch, position, zoneX, zoneY, distanceFromReference, outsideActiveArea, anchor, linkCount); float epsilon = Mathf.Clamp(changeEpsilon, 1E-05f, 10f); if (latestByNode.TryGetValue(nodeId, out var value3) && value3.IsEquivalentTo(nodeComparison, epsilon)) { return false; } ComparisonSample sample = new ComparisonSample(rawDifference, Math.Abs(num - num2), num3, stabilityMismatch, visualMismatch); lifetime.Add(sample); window.Add(sample); latestByNode[nodeId] = nodeComparison; return true; } internal void RemoveNode(int nodeId) { latestByNode.Remove(nodeId); } internal BenchmarkSnapshot SnapshotAndResetWindow(int topDifferenceCount) { int num = 0; int num2 = 0; MaterialSummaryAccumulator materialSummaryAccumulator = new MaterialSummaryAccumulator(); int num3 = Mathf.Clamp(topDifferenceCount, 0, 20); NodeComparison[] top = ((num3 > 0) ? new NodeComparison[num3] : null); float[] scores = ((num3 > 0) ? new float[num3] : null); int used = 0; foreach (NodeComparison value in latestByNode.Values) { if (value.StabilityMismatch) { num++; } if (value.VisualMismatch) { num2++; } materialSummaryAccumulator.Add(value); if (num3 > 0 && (value.StabilityMismatch || value.VisualMismatch || value.NormalizedDifference > 0.0005f || value.VisualDifference > 0.0005f)) { InsertTop(top, scores, ref used, value, value.Score); } } BenchmarkSnapshot result = new BenchmarkSnapshot(lifetime.Snapshot(), window.Snapshot(), latestByNode.Count, num, num2, materialSummaryAccumulator.BuildSummary(), BuildTopSummary(top, used)); window.Reset(); return result; } internal void Reset() { latestByNode.Clear(); lifetime.Reset(); window.Reset(); } private static void InsertTop(NodeComparison[] top, float[] scores, ref int used, NodeComparison candidate, float score) { int num = top.Length; int num2 = used; for (int i = 0; i < used; i++) { if (score > scores[i]) { num2 = i; break; } } if (num2 < num) { int num3 = Math.Min(used, num - 1); for (int num4 = num3; num4 > num2; num4--) { top[num4] = top[num4 - 1]; scores[num4] = scores[num4 - 1]; } top[num2] = candidate; scores[num2] = score; if (used < num) { used++; } } } private static string BuildTopSummary(NodeComparison[] top, int count) { //IL_0083: Unknown result type (might be due to invalid IL or missing references) //IL_01f6: Unknown result type (might be due to invalid IL or missing references) if (top == null || count <= 0) { return string.Empty; } StringBuilder stringBuilder = new StringBuilder(512); for (int i = 0; i < count; i++) { if (i > 0) { stringBuilder.Append(" | "); } NodeComparison nodeComparison = top[i]; stringBuilder.Append(nodeComparison.Name); stringBuilder.Append('#'); stringBuilder.Append(nodeComparison.NodeId); stringBuilder.Append('['); stringBuilder.Append(nodeComparison.MaterialType); stringBuilder.Append("]:v="); float vanillaSupport = nodeComparison.VanillaSupport; stringBuilder.Append(vanillaSupport.ToString("F1")); stringBuilder.Append(",g="); vanillaSupport = nodeComparison.GraphSupport; stringBuilder.Append(vanillaSupport.ToString("F1")); stringBuilder.Append(",n="); stringBuilder.Append(nodeComparison.NormalizedDifference.ToString("F3")); stringBuilder.Append(",c="); vanillaSupport = nodeComparison.VisualDifference; stringBuilder.Append(vanillaSupport.ToString("F3")); stringBuilder.Append(",a="); stringBuilder.Append(nodeComparison.Anchor); stringBuilder.Append(",e="); stringBuilder.Append(nodeComparison.LinkCount); stringBuilder.Append(",z="); stringBuilder.Append(nodeComparison.ZoneX); stringBuilder.Append('/'); stringBuilder.Append(nodeComparison.ZoneY); stringBuilder.Append(",d="); vanillaSupport = nodeComparison.DistanceFromReference; stringBuilder.Append(vanillaSupport.ToString("F1")); stringBuilder.Append(",out="); stringBuilder.Append(nodeComparison.OutsideActiveArea ? '1' : '0'); stringBuilder.Append(",p="); AppendPosition(stringBuilder, nodeComparison.Position); if (nodeComparison.StabilityMismatch) { stringBuilder.Append(",STABLE!"); } } return stringBuilder.ToString(); } private static void AppendPosition(StringBuilder builder, Vector3 position) { builder.Append('('); builder.Append(position.x.ToString("F1")); builder.Append(','); builder.Append(position.y.ToString("F1")); builder.Append(','); builder.Append(position.z.ToString("F1")); builder.Append(')'); } private static float NormalizeSupport(float support, MaterialProfile material) { float num = material.MaxSupport - material.MinSupport; if (num <= 0.0001f) { return (support >= material.MinSupport) ? 1f : 0f; } return Mathf.Clamp01((support - material.MinSupport) / num); } private static void GetVisualValue(float support, MaterialProfile material, out float value, out bool blue) { blue = support >= material.MaxSupport; if (blue) { value = -1f; return; } float num = material.MaxSupport * 0.5f - material.MinSupport; if (num <= 0.0001f) { value = ((support >= material.MinSupport) ? 1f : 0f); } else { value = Mathf.Clamp01((support - material.MinSupport) / num); } } } internal struct ComparisonTotals { internal long Comparisons; internal long StabilityMismatches; internal long VisualMismatches; internal double AverageRawDifference; internal float MaximumRawDifference; internal double AverageNormalizedDifference; internal float MaximumNormalizedDifference; internal double AverageVisualDifference; internal float MaximumVisualDifference; internal ComparisonTotals(long comparisons, long stabilityMismatches, long visualMismatches, double averageRawDifference, float maximumRawDifference, double averageNormalizedDifference, float maximumNormalizedDifference, double averageVisualDifference, float maximumVisualDifference) { Comparisons = comparisons; StabilityMismatches = stabilityMismatches; VisualMismatches = visualMismatches; AverageRawDifference = averageRawDifference; MaximumRawDifference = maximumRawDifference; AverageNormalizedDifference = averageNormalizedDifference; MaximumNormalizedDifference = maximumNormalizedDifference; AverageVisualDifference = averageVisualDifference; MaximumVisualDifference = maximumVisualDifference; } } internal struct BenchmarkSnapshot { internal ComparisonTotals Lifetime; internal ComparisonTotals Window; internal int UniqueComparedNodes; internal int CurrentStabilityMismatchNodes; internal int CurrentVisualMismatchNodes; internal string MaterialSummary; internal string TopDifferences; internal BenchmarkSnapshot(ComparisonTotals lifetime, ComparisonTotals window, int uniqueComparedNodes, int currentStabilityMismatchNodes, int currentVisualMismatchNodes, string materialSummary, string topDifferences) { Lifetime = lifetime; Window = window; UniqueComparedNodes = uniqueComparedNodes; CurrentStabilityMismatchNodes = currentStabilityMismatchNodes; CurrentVisualMismatchNodes = currentVisualMismatchNodes; MaterialSummary = materialSummary; TopDifferences = topDifferences; } } internal sealed class BoundedListPool { private readonly Stack> pool = new Stack>(); private int maximumCount; private int maximumRetainedCapacity; private readonly int initialCapacity; private long allocated; private long discarded; internal int Count => pool.Count; internal long Allocated => allocated; internal long Discarded => discarded; internal BoundedListPool(int initialListCapacity, int maximumPooledLists, int maximumListCapacity) { initialCapacity = Math.Max(0, initialListCapacity); SetLimits(maximumPooledLists, maximumListCapacity); } internal void SetLimits(int maximumPooledLists, int maximumListCapacity) { maximumCount = Math.Max(0, maximumPooledLists); maximumRetainedCapacity = Math.Max(initialCapacity, maximumListCapacity); TrimToLimit(); } internal List Rent() { if (pool.Count > 0) { return pool.Pop(); } allocated++; return new List(initialCapacity); } internal void Return(List list) { if (list == null) { return; } list.Clear(); if (maximumCount <= 0 || pool.Count >= maximumCount) { discarded++; return; } if (list.Capacity > maximumRetainedCapacity) { list.Capacity = maximumRetainedCapacity; } pool.Push(list); } internal void Clear() { pool.Clear(); } internal void TrimToCount(int targetCount) { int num = Math.Max(0, Math.Min(targetCount, maximumCount)); while (pool.Count > num) { pool.Pop(); discarded++; } } private void TrimToLimit() { while (pool.Count > maximumCount) { pool.Pop(); discarded++; } } } internal sealed class ContactDetector { private const int InitialOverlapCapacity = 128; private const float HalfPi = (float)Math.PI / 2f; private Collider[] overlapBuffer = (Collider[])(object)new Collider[128]; private readonly int supportMask; private readonly int terrainLayer; private long overlapRetries; private long overlapOverflows; internal long OverlapRetries => overlapRetries; internal long OverlapOverflows => overlapOverflows; internal int OverlapCapacity => overlapBuffer.Length; internal ContactDetector() { supportMask = LayerMask.GetMask(new string[5] { "piece", "Default", "static_solid", "Default_small", "terrain" }); terrainLayer = LayerMask.NameToLayer("terrain"); } internal int QueryCollider(Collider collider, float padding, int configuredMaximum) { //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Unknown result type (might be due to invalid IL or missing references) if (!IsStructuralCollider(collider)) { return 0; } BuildProbe(collider, Mathf.Max(0f, padding), out var center, out var rotation, out var halfExtents); int num = Mathf.Clamp(configuredMaximum, 128, 16384); int num2; while (true) { num2 = Physics.OverlapBoxNonAlloc(center, halfExtents, overlapBuffer, rotation, supportMask, (QueryTriggerInteraction)1); if (num2 < overlapBuffer.Length || overlapBuffer.Length >= num) { break; } int num3 = Mathf.Min(num, overlapBuffer.Length * 2); overlapBuffer = (Collider[])(object)new Collider[num3]; overlapRetries++; } if (num2 >= overlapBuffer.Length && overlapBuffer.Length >= num) { overlapOverflows++; } return num2; } internal Collider GetResult(int index) { return (index >= 0 && index < overlapBuffer.Length) ? overlapBuffer[index] : null; } internal void ClearResults(int count) { int num = Mathf.Min(count, overlapBuffer.Length); for (int i = 0; i < num; i++) { overlapBuffer[i] = null; } } internal bool IsTerrain(Collider collider) { return (Object)(object)collider != (Object)null && ((Component)collider).gameObject.layer == terrainLayer; } internal StructuralContact CreateDirectionalContact(IntegrityNode target, IntegrityNode source, Collider sourceCollider) { //IL_0002: 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_000a: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_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_0070: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Unknown result type (might be due to invalid IL or missing references) //IL_0077: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_0098: Unknown result type (might be due to invalid IL or missing references) //IL_00d2: 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) Vector3 centerOfMass = target.CenterOfMass; float num = Vector3.Distance(centerOfMass, source.CenterOfMass) + 0.1f; float num2 = Vector3.Distance(centerOfMass, source.OriginPosition) + 0.1f; if (!target.ForceCorrectComCalculation && num2 < num) { num = num2; } Vector3 val = FindSupportPoint(centerOfMass, source, sourceCollider); Vector3 relativePoint = val - centerOfMass; Vector3 val2 = ((((Vector3)(ref relativePoint)).sqrMagnitude > 1E-06f) ? ((Vector3)(ref relativePoint)).normalized : Vector3.zero); bool flag = val.y < centerOfMass.y + 0.05f; float directVerticalBlend = 0f; if (flag && val2.y < 0f) { directVerticalBlend = Mathf.Acos(1f - Mathf.Abs(val2.y)) / ((float)Math.PI / 2f); } SupportPointData supportPoint = new SupportPointData(relativePoint, num); return new StructuralContact(num, directVerticalBlend, flag, supportPoint); } private static void BuildProbe(Collider collider, float padding, out Vector3 center, out Quaternion rotation, out Vector3 halfExtents) { //IL_00be: Unknown result type (might be due to invalid IL or missing references) //IL_00c3: Unknown result type (might be due to invalid IL or missing references) //IL_00c7: 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) //IL_00d2: Unknown result type (might be due to invalid IL or missing references) //IL_00d7: 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_00e5: Unknown result type (might be due to invalid IL or missing references) //IL_00eb: Unknown result type (might be due to invalid IL or missing references) //IL_00f0: Unknown result type (might be due to invalid IL or missing references) //IL_00f5: 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_0028: 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) //IL_0039: 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_004a: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0059: 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_0079: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_00b1: Unknown result type (might be due to invalid IL or missing references) //IL_00b6: Unknown result type (might be due to invalid IL or missing references) BoxCollider val = (BoxCollider)(object)((collider is BoxCollider) ? collider : null); if ((Object)(object)val != (Object)null) { Transform transform = ((Component)val).transform; Vector3 lossyScale = transform.lossyScale; center = transform.position + transform.TransformVector(val.center); rotation = transform.rotation; halfExtents = new Vector3(Mathf.Abs(lossyScale.x * val.size.x) * 0.5f + padding, Mathf.Abs(lossyScale.y * val.size.y) * 0.5f + padding, Mathf.Abs(lossyScale.z * val.size.z) * 0.5f + padding); } else { Bounds bounds = collider.bounds; center = ((Bounds)(ref bounds)).center; rotation = Quaternion.identity; halfExtents = ((Bounds)(ref bounds)).extents + Vector3.one * padding; } } private static Vector3 FindSupportPoint(Vector3 targetCom, IntegrityNode source, Collider sourceCollider) { //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0026: 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_0054: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Unknown result type (might be due to invalid IL or missing references) MeshCollider val = (MeshCollider)(object)((sourceCollider is MeshCollider) ? sourceCollider : null); if ((Object)(object)val == (Object)null || val.convex) { return sourceCollider.ClosestPoint(targetCom); } RaycastHit val2 = default(RaycastHit); if (((Collider)val).Raycast(new Ray(targetCom, Vector3.down), ref val2, 10f)) { return ((RaycastHit)(ref val2)).point; } return (targetCom + source.CenterOfMass) * 0.5f; } private static bool IsStructuralCollider(Collider collider) { return (Object)(object)collider != (Object)null && !collider.isTrigger && (Object)(object)collider.attachedRigidbody == (Object)null; } } internal enum AnchorKind : byte { None, Terrain, StaticWorld } internal enum LinkCommitResult : byte { None, ImprovedOnly, RemovedOrWeakened } internal sealed class IntegrityNode { private static readonly Collider[] EmptyColliders = (Collider[])(object)new Collider[0]; internal readonly WearNTear Instance; internal readonly int RuntimeId; internal readonly ZNetView NView; internal readonly List Links; internal readonly List Dependents; internal MaterialProfile Material; internal bool CanTransmitSupport; internal bool RequiresSupport; internal bool ForceCorrectComCalculation; internal Collider[] Colliders; internal Bounds RawBounds; internal Bounds QueryBounds; internal Vector3 CenterOfMass; internal Vector3 OriginPosition; internal AnchorKind Anchor; internal float GraphSupport; internal float WorkingSupport; internal bool GraphStable; internal bool IsReady; internal bool IsPrepared; internal bool GeometryDirty; internal bool ContactsDirty; internal bool PrepareQueued; internal bool RefreshQueued; internal bool SolveQueued; internal bool RelaxQueued; internal bool VanillaCacheReleased; internal bool SupportValid; internal bool OwnerSyncQueued; internal bool OwnerSyncEstablished; internal bool LastKnownOwner; internal bool OwnershipKnown; internal float NextOwnershipCheckTime; internal float CacheReleaseEligibleTime; internal float LastVanillaFallbackTime; internal int ActiveListIndex = -1; internal bool IsAlive => (Object)(object)Instance != (Object)null && (Object)(object)((Component)Instance).gameObject != (Object)null; internal bool IsAnchor => Anchor != AnchorKind.None; internal IntegrityNode(WearNTear instance, ZNetView nview, List links, List dependents) { //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_00a1: Unknown result type (might be due to invalid IL or missing references) //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Unknown result type (might be due to invalid IL or missing references) //IL_00b2: 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_00c1: 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_00cb: Unknown result type (might be due to invalid IL or missing references) //IL_00d2: Unknown result type (might be due to invalid IL or missing references) //IL_00d7: Unknown result type (might be due to invalid IL or missing references) Instance = instance; RuntimeId = ((Object)instance).GetInstanceID(); NView = nview; Material = MaterialProfiles.Get(instance, NView); CanTransmitSupport = WearNTearAccess.CanTransmitSupport(instance); RequiresSupport = WearNTearAccess.RequiresSupport(instance); ForceCorrectComCalculation = WearNTearAccess.ForceCorrectComCalculation(instance); Links = links ?? new List(6); Dependents = dependents ?? new List(6); Colliders = EmptyColliders; OriginPosition = ((Component)instance).transform.position; CenterOfMass = WearNTearAccess.GetCenterOfMass(instance, OriginPosition); RawBounds = new Bounds(CenterOfMass, Vector3.one * 0.05f); QueryBounds = RawBounds; GeometryDirty = true; ContactsDirty = true; } internal void ReleaseManagedCaches() { Links.Clear(); Dependents.Clear(); Colliders = EmptyColliders; IsPrepared = false; IsReady = false; SupportValid = false; GeometryDirty = true; ContactsDirty = true; } internal void RefreshStaticProperties() { Material = MaterialProfiles.Get(Instance, NView); CanTransmitSupport = WearNTearAccess.CanTransmitSupport(Instance); RequiresSupport = WearNTearAccess.RequiresSupport(Instance); ForceCorrectComCalculation = WearNTearAccess.ForceCorrectComCalculation(Instance); } internal void PrepareGeometry(float contactPadding) { //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Unknown result type (might be due to invalid IL or missing references) //IL_00eb: Unknown result type (might be due to invalid IL or missing references) //IL_00ec: Unknown result type (might be due to invalid IL or missing references) //IL_00f2: Unknown result type (might be due to invalid IL or missing references) //IL_00f3: Unknown result type (might be due to invalid IL or missing references) //IL_00c8: 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) //IL_00bd: Unknown result type (might be due to invalid IL or missing references) if (!IsAlive) { Colliders = EmptyColliders; IsPrepared = false; return; } RefreshStaticProperties(); Colliders = WearNTearAccess.GetOrCreateStructuralColliders(Instance); OriginPosition = ((Component)Instance).transform.position; CenterOfMass = WearNTearAccess.GetCenterOfMass(Instance, OriginPosition); bool flag = false; Bounds bounds = default(Bounds); ((Bounds)(ref bounds))..ctor(CenterOfMass, Vector3.one * 0.05f); for (int i = 0; i < Colliders.Length; i++) { Collider val = Colliders[i]; if (IsStructuralCollider(val)) { if (!flag) { bounds = val.bounds; flag = true; } else { ((Bounds)(ref bounds)).Encapsulate(val.bounds); } } } RawBounds = bounds; QueryBounds = bounds; ((Bounds)(ref QueryBounds)).Expand(Mathf.Max(0f, contactPadding) * 2f); IsPrepared = true; GeometryDirty = false; } internal LinkCommitResult ReplaceLinks(List pending, AnchorKind pendingAnchor, List removedSources, List addedSources) { removedSources.Clear(); addedSources.Clear(); bool flag = Anchor != AnchorKind.None && pendingAnchor == AnchorKind.None; bool flag2 = Anchor == AnchorKind.None && pendingAnchor != AnchorKind.None; Anchor = pendingAnchor; for (int i = 0; i < Links.Count; i++) { StructuralLink structuralLink = Links[i]; int num = FindLinkIndex(pending, structuralLink.OtherId); if (num < 0) { removedSources.Add(structuralLink.OtherId); flag = true; continue; } StructuralContact contact = pending[num].Contact; if (!structuralLink.Contact.ApproximatelyEquals(contact)) { flag = true; } } for (int j = 0; j < pending.Count; j++) { StructuralLink structuralLink2 = pending[j]; if (FindLinkIndex(Links, structuralLink2.OtherId) < 0) { addedSources.Add(structuralLink2.OtherId); flag2 = true; } } Links.Clear(); for (int k = 0; k < pending.Count; k++) { Links.Add(pending[k]); } ContactsDirty = false; IsReady = false; VanillaCacheReleased = false; if (flag) { return LinkCommitResult.RemovedOrWeakened; } return flag2 ? LinkCommitResult.ImprovedOnly : LinkCommitResult.None; } internal bool AddDependent(int targetId) { for (int i = 0; i < Dependents.Count; i++) { if (Dependents[i] == targetId) { return false; } } Dependents.Add(targetId); return true; } internal bool RemoveDependent(int targetId) { for (int i = 0; i < Dependents.Count; i++) { if (Dependents[i] == targetId) { int index = Dependents.Count - 1; Dependents[i] = Dependents[index]; Dependents.RemoveAt(index); return true; } } return false; } internal bool RemoveLink(int sourceId) { for (int i = 0; i < Links.Count; i++) { if (Links[i].OtherId == sourceId) { int index = Links.Count - 1; Links[i] = Links[index]; Links.RemoveAt(index); IsReady = false; return true; } } return false; } private static int FindLinkIndex(List links, int otherId) { for (int i = 0; i < links.Count; i++) { if (links[i].OtherId == otherId) { return i; } } return -1; } private static bool IsStructuralCollider(Collider collider) { return (Object)(object)collider != (Object)null && !collider.isTrigger && (Object)(object)collider.attachedRigidbody == (Object)null; } } internal sealed class IntegrityService { private enum SolvePhase : byte { None, Collect, Initialize, Relax, Commit } private enum ReconcilePhase : byte { None, ScanInstances, PruneNodes } private enum ReconcileReason : byte { None, WorldStart, ZoneChange, PeriodicSafety, LifecycleRequest, RestartRequested } private enum WorkStage : byte { None, Prepare, Refresh, Solve, Reconcile, Maintenance } private struct ColliderOwnerCacheEntry { internal Collider Collider; internal int OwnerId; } private const float SupportEpsilon = 0.001f; private const float VanillaBraceCosine = -0.17364818f; private const float CacheReleaseSweepIntervalSeconds = 5f; private readonly ManualLogSource log; private readonly BetterBuildConfig config; private readonly Dictionary nodes = new Dictionary(); private readonly Dictionary colliderOwners = new Dictionary(); private readonly Dictionary staticColliderCache = new Dictionary(); private readonly BoundedListPool linkListPool; private readonly BoundedListPool dependentListPool; private readonly SpatialHash spatialHash; private readonly ContactDetector contactDetector = new ContactDetector(); private readonly Queue prepareQueue = new Queue(); private readonly Queue refreshQueue = new Queue(); private readonly Queue solveQueue = new Queue(); private readonly Queue ownerSyncQueue = new Queue(); private readonly HashSet queryBuffer = new HashSet(); private readonly List removedSourceBuffer = new List(8); private readonly List addedSourceBuffer = new List(8); private readonly List pendingLinks = new List(8); private int currentRefreshNodeId; private int currentRefreshColliderIndex; private AnchorKind currentPendingAnchor; private bool ownerSweepActive; private int ownerSweepIndex; private float nextOwnershipSweepTime; private bool cacheReleaseSweepActive; private int cacheReleaseSweepIndex; private float nextCacheReleaseSweepTime; private int cacheReleaseBudgetFrame = -1; private int cacheReleasesThisFrame; private SolvePhase solvePhase; private int solveSeedId; private int solveGraphRevision; private int graphRevision; private int solveInitializeIndex; private int solveCommitIndex; private readonly List solveIsland = new List(256); private readonly Queue solveCollectQueue = new Queue(); private readonly HashSet solveVisited = new HashSet(); private readonly Queue relaxationQueue = new Queue(); private ReconcilePhase reconcilePhase; private readonly List activeNodeIds = new List(512); private List reconcileInstances; private int reconcileInstanceIndex; private int reconcileNodeIndex; private bool reconcileGraphChanged; private bool reconcileRestartRequested; private ReconcileReason reconcileReason; private ReconcileReason reconcileRestartReason; private ReconcileReason lastCompletedReconcileReason; private float nextReconcileTime; private float nextReferenceZoneCheckTime; private bool hasReferenceZone; private Vector2Int lastReferenceZone; private long completedReconciliations; private long zoneChangeReconciliations; private long periodicReconciliations; private long requestedReconciliations; private long reconciledPrunedNodes; private bool replacementArmed; private bool replacementFaulted; private string replacementFaultReason = string.Empty; private long replacementRequests; private long replacementHits; private long replacementMissNotArmed; private long replacementMissNotReady; private long replacementMissOutsideArea; private long replacementMissFaulted; private long replacementInvalidSupport; private long replacementExceptions; private long replacementCircuitTrips; private long windowReplacementRequests; private long windowReplacementHits; private long windowReplacementMissNotArmed; private long windowReplacementMissNotReady; private long windowReplacementMissOutsideArea; private long windowReplacementMissFaulted; private long windowReplacementInvalidSupport; private long windowReplacementExceptions; private long windowReplacementCircuitTrips; private readonly BenchmarkRecorder benchmark = new BenchmarkRecorder(); private readonly PerformanceProfiler profiler = new PerformanceProfiler(); private readonly Stopwatch workWatch = new Stopwatch(); private readonly StringBuilder statsBuilder = new StringBuilder(1024); private bool diagnosticsEnabled; private bool profilingEnabled; private bool detailedStageTimingEnabled; private bool runtimeOptionsDirty; private bool dedicatedServer; private float currentRealtimeSinceStartup; private double cachedWorkBudgetMilliseconds; private float cachedContactPadding; private int cachedMaximumOverlapResults; private int cachedMaximumIslandNodes; private float cachedSolveDebounceSeconds; private float cachedReconcileSeconds; private bool cachedRequireInitialStableGraph; private bool cachedReleaseVanillaCache; private bool cachedApplySupportToZdo; private float cachedNetworkAbsoluteEpsilon; private float cachedNetworkNormalizedEpsilon; private float cachedOwnershipRecheckSeconds; private int cachedMaximumSupportZdoWritesPerFrame; private int cachedMaximumPooledNodeLists; private int cachedMaximumRetainedNodeListCapacity; private int cachedMaximumPooledSpatialCellLists; private float cachedVanillaCacheReleaseStableSeconds; private float cachedVanillaCacheReleaseFallbackCooldownSeconds; private int cachedMaximumVanillaCacheReleasesPerFrame; private int zdoWriteBudgetFrame = -1; private int zdoWritesThisFrame; private long zdoWritesSkippedEpsilon; private long zdoWritesSkippedNotOwner; private long zdoWritesDeferredBudget; private long nodeAllocations; private long nodeRemovals; private long negativeColliderCacheHits; private long negativeColliderCacheMisses; private float nextStatsTime; private float solveNotBefore; private long solvedIslands; private long solvedNodes; private long supportRelaxations; private long zdoWrites; private long vanillaCachesReleased; private double lastWorkMilliseconds; private double maximumWorkMilliseconds; private double windowMaximumWorkMilliseconds; private double windowMaxPrepareMilliseconds; private double windowMaxRefreshMilliseconds; private double windowMaxSolveMilliseconds; private double windowMaxReconcileMilliseconds; private double windowMaxMaintenanceMilliseconds; private double lifetimeMaxPrepareMilliseconds; private double lifetimeMaxRefreshMilliseconds; private double lifetimeMaxSolveMilliseconds; private double lifetimeMaxReconcileMilliseconds; private double lifetimeMaxMaintenanceMilliseconds; private float nextIdleHeartbeatTime; private int lastLoggedNodes = -1; private int lastLoggedEdges = -1; private int lastLoggedTerrainAnchors = -1; private int lastLoggedStaticAnchors = -1; private int lastLoggedStableMismatches = -1; private int lastLoggedVisualMismatches = -1; internal IntegrityService(ManualLogSource logger, BetterBuildConfig settings) { log = logger; config = settings; linkListPool = new BoundedListPool(6, 2048, 16); dependentListPool = new BoundedListPool(6, 2048, 16); spatialHash = new SpatialHash(GetSpatialCellSize()); RefreshDiagnosticMode(); RefreshRuntimeOptions(0f); } internal void RefreshDiagnosticMode() { bool flag = profilingEnabled; diagnosticsEnabled = Launch.RuntimeStatisticsEnabled; profilingEnabled = Launch.ProfilingEnabled; detailedStageTimingEnabled = profilingEnabled && config.DetailedTimingDiagnostics.Value; if (flag != profilingEnabled) { profiler.Reset(); } } internal void MarkRuntimeOptionsDirty() { runtimeOptionsDirty = true; } internal void RecordUpdateSupportTiming(bool vanillaPath, long elapsedTicks) { if (profilingEnabled) { profiler.RecordSupportCall(vanillaPath, elapsedTicks); } } internal void RecordWearUpdaterTiming(long elapsedTicks) { if (profilingEnabled) { profiler.RecordWearUpdater(elapsedTicks); } } internal void BeginWorldSession(float realtimeSinceStartup) { Reset(); currentRealtimeSinceStartup = realtimeSinceStartup; dedicatedServer = IsDedicatedServer(); RefreshDiagnosticMode(); RefreshRuntimeOptions(realtimeSinceStartup); float num = Math.Max(0f, config.StatsIntervalSeconds.Value); nextStatsTime = realtimeSinceStartup + num; float num2 = Math.Max(0f, config.IdleHeartbeatSeconds.Value); nextIdleHeartbeatTime = ((num2 > 0f) ? (realtimeSinceStartup + num2) : float.PositiveInfinity); nextReconcileTime = realtimeSinceStartup; nextReferenceZoneCheckTime = realtimeSinceStartup; nextOwnershipSweepTime = realtimeSinceStartup; nextCacheReleaseSweepTime = realtimeSinceStartup + 5f; } internal void RegisterExistingInstances() { RequestActiveAreaReconciliation(immediate: true, ReconcileReason.WorldStart); } internal void Reset() { foreach (IntegrityNode value in nodes.Values) { value.ReleaseManagedCaches(); linkListPool.Return(value.Links); dependentListPool.Return(value.Dependents); } nodes.Clear(); activeNodeIds.Clear(); colliderOwners.Clear(); staticColliderCache.Clear(); spatialHash.Clear(); linkListPool.TrimToCount(0); dependentListPool.TrimToCount(0); spatialHash.TrimPool(0); prepareQueue.Clear(); refreshQueue.Clear(); solveQueue.Clear(); ownerSyncQueue.Clear(); queryBuffer.Clear(); removedSourceBuffer.Clear(); addedSourceBuffer.Clear(); pendingLinks.Clear(); currentRefreshNodeId = 0; currentRefreshColliderIndex = 0; currentPendingAnchor = AnchorKind.None; CancelActiveSolve(); CancelReconciliation(); ownerSweepActive = false; ownerSweepIndex = 0; nextOwnershipSweepTime = 0f; cacheReleaseSweepActive = false; cacheReleaseSweepIndex = 0; nextCacheReleaseSweepTime = 0f; cacheReleaseBudgetFrame = -1; cacheReleasesThisFrame = 0; benchmark.Reset(); profiler.Reset(); graphRevision = 0; solvedIslands = 0L; solvedNodes = 0L; supportRelaxations = 0L; zdoWrites = 0L; vanillaCachesReleased = 0L; zdoWritesSkippedEpsilon = 0L; zdoWritesSkippedNotOwner = 0L; zdoWritesDeferredBudget = 0L; zdoWriteBudgetFrame = -1; zdoWritesThisFrame = 0; nodeAllocations = 0L; nodeRemovals = 0L; negativeColliderCacheHits = 0L; negativeColliderCacheMisses = 0L; lastWorkMilliseconds = 0.0; maximumWorkMilliseconds = 0.0; windowMaximumWorkMilliseconds = 0.0; windowMaxPrepareMilliseconds = 0.0; windowMaxRefreshMilliseconds = 0.0; windowMaxSolveMilliseconds = 0.0; windowMaxReconcileMilliseconds = 0.0; windowMaxMaintenanceMilliseconds = 0.0; lifetimeMaxPrepareMilliseconds = 0.0; lifetimeMaxRefreshMilliseconds = 0.0; lifetimeMaxSolveMilliseconds = 0.0; lifetimeMaxReconcileMilliseconds = 0.0; lifetimeMaxMaintenanceMilliseconds = 0.0; nextStatsTime = 0f; solveNotBefore = 0f; nextReconcileTime = 0f; nextReferenceZoneCheckTime = 0f; hasReferenceZone = false; completedReconciliations = 0L; zoneChangeReconciliations = 0L; periodicReconciliations = 0L; requestedReconciliations = 0L; reconciledPrunedNodes = 0L; reconcileReason = ReconcileReason.None; reconcileRestartReason = ReconcileReason.None; lastCompletedReconcileReason = ReconcileReason.None; replacementArmed = false; replacementFaulted = false; replacementFaultReason = string.Empty; replacementRequests = 0L; replacementHits = 0L; replacementMissNotArmed = 0L; replacementMissNotReady = 0L; replacementMissOutsideArea = 0L; replacementMissFaulted = 0L; replacementInvalidSupport = 0L; replacementExceptions = 0L; replacementCircuitTrips = 0L; windowReplacementRequests = 0L; windowReplacementHits = 0L; windowReplacementMissNotArmed = 0L; windowReplacementMissNotReady = 0L; windowReplacementMissOutsideArea = 0L; windowReplacementMissFaulted = 0L; windowReplacementInvalidSupport = 0L; windowReplacementExceptions = 0L; windowReplacementCircuitTrips = 0L; nextIdleHeartbeatTime = 0f; lastLoggedNodes = -1; lastLoggedEdges = -1; lastLoggedTerrainAnchors = -1; lastLoggedStaticAnchors = -1; lastLoggedStableMismatches = -1; lastLoggedVisualMismatches = -1; } internal void Register(WearNTear instance) { if (Launch.RuntimeMode == IntegrityMode.Vanilla || (Object)(object)instance == (Object)null) { return; } int instanceID = ((Object)instance).GetInstanceID(); if (nodes.TryGetValue(instanceID, out var _) || !ShouldManageInstance(instance, out var nview)) { return; } bool flag = WearNTearAccess.RequiresSupport(instance); bool flag2 = WearNTearAccess.CanTransmitSupport(instance); if (flag || flag2) { IntegrityNode integrityNode = new IntegrityNode(instance, nview, linkListPool.Rent(), dependentListPool.Rent()); integrityNode.GraphSupport = WearNTearAccess.ReadSupport(instance); integrityNode.WorkingSupport = integrityNode.GraphSupport; integrityNode.GraphStable = !integrityNode.RequiresSupport || integrityNode.GraphSupport >= integrityNode.Material.MinSupport; integrityNode.IsReady = false; integrityNode.ActiveListIndex = activeNodeIds.Count; nodes.Add(instanceID, integrityNode); activeNodeIds.Add(instanceID); if (diagnosticsEnabled) { nodeAllocations++; } QueuePrepare(integrityNode); } } internal void Unregister(WearNTear instance) { if (!((Object)(object)instance == (Object)null)) { RemoveNode(((Object)instance).GetInstanceID(), markNearby: true, mutateImmediately: true); } } private bool RemoveNode(int id, bool markNearby, bool mutateImmediately) { //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_0172: Unknown result type (might be due to invalid IL or missing references) if (!nodes.TryGetValue(id, out var value)) { return false; } Bounds queryBounds = value.QueryBounds; bool isPrepared = value.IsPrepared; RemoveColliderMappings(value); for (int i = 0; i < value.Links.Count; i++) { if (nodes.TryGetValue(value.Links[i].OtherId, out var value2)) { value2.RemoveDependent(id); } } for (int j = 0; j < value.Dependents.Count; j++) { if (nodes.TryGetValue(value.Dependents[j], out var value3)) { value3.RemoveLink(id); QueueSolve(value3); } } spatialHash.Remove(id); RemoveFromActiveNodeList(value); nodes.Remove(id); if (diagnosticsEnabled) { nodeRemovals++; } benchmark.RemoveNode(id); if (currentRefreshNodeId == id) { CancelCurrentRefresh(); } if (solvePhase != SolvePhase.None && solveVisited.Contains(id)) { CancelActiveSolve(); } if (markNearby && isPrepared) { MarkNearbyContactsDirty(queryBounds, id); } value.ReleaseManagedCaches(); linkListPool.Return(value.Links); dependentListPool.Return(value.Dependents); if (mutateImmediately) { MutatedGraph(); } else { reconcileGraphChanged = true; } return true; } internal void MarkGeometryDirty(WearNTear instance) { //IL_0044: Unknown result type (might be due to invalid IL or missing references) Register(instance); if (!((Object)(object)instance == (Object)null) && nodes.TryGetValue(((Object)instance).GetInstanceID(), out var value)) { if (value.IsPrepared) { MarkNearbyContactsDirty(value.QueryBounds, value.RuntimeId); } bool flag = !value.GeometryDirty || !value.ContactsDirty || value.IsReady; value.GeometryDirty = true; value.ContactsDirty = true; value.IsReady = false; value.SupportValid = false; value.OwnerSyncEstablished = false; value.NextOwnershipCheckTime = 0f; value.VanillaCacheReleased = false; if (currentRefreshNodeId == value.RuntimeId) { CancelCurrentRefresh(); flag = true; } bool flag2 = QueuePrepare(value); if (flag || flag2) { MutatedGraph(); } } } internal void MarkSupportDirty(WearNTear instance) { Register(instance); if (!((Object)(object)instance == (Object)null) && nodes.TryGetValue(((Object)instance).GetInstanceID(), out var value) && ((value.IsPrepared && !value.GeometryDirty) ? QueueRefresh(value) : QueuePrepare(value))) { MutatedGraph(); } } internal void ForceFullRebuild() { MaterialProfiles.Invalidate(); colliderOwners.Clear(); staticColliderCache.Clear(); spatialHash.Clear(); spatialHash.SetCellSize(GetSpatialCellSize()); prepareQueue.Clear(); refreshQueue.Clear(); solveQueue.Clear(); ownerSyncQueue.Clear(); ownerSweepActive = false; ownerSweepIndex = 0; cacheReleaseSweepActive = false; cacheReleaseSweepIndex = 0; CancelCurrentRefresh(); CancelActiveSolve(); benchmark.Reset(); replacementArmed = false; replacementFaulted = false; replacementFaultReason = string.Empty; foreach (IntegrityNode value in nodes.Values) { value.Links.Clear(); value.Dependents.Clear(); value.IsReady = false; value.IsPrepared = false; value.GeometryDirty = true; value.ContactsDirty = true; value.PrepareQueued = false; value.RefreshQueued = false; value.SolveQueued = false; value.RelaxQueued = false; value.Anchor = AnchorKind.None; value.VanillaCacheReleased = false; value.SupportValid = false; value.OwnerSyncQueued = false; if (value.IsAlive) { QueuePrepare(value); } } MutatedGraph(); if (Launch.InformationLoggingEnabled) { log.LogInfo((object)("Forced integrity graph rebuild for " + nodes.Count + " registered WearNTear instances.")); } } internal bool TryGetCachedSupport(WearNTear instance, out float support) { support = 0f; if (diagnosticsEnabled) { replacementRequests++; windowReplacementRequests++; } if (replacementFaulted) { if (diagnosticsEnabled) { replacementMissFaulted++; windowReplacementMissFaulted++; } return false; } if ((Object)(object)instance == (Object)null) { if (diagnosticsEnabled) { replacementMissOutsideArea++; windowReplacementMissOutsideArea++; } return false; } int instanceID = ((Object)instance).GetInstanceID(); if (!nodes.TryGetValue(instanceID, out var value)) { Register(instance); if (!nodes.TryGetValue(instanceID, out value)) { if (diagnosticsEnabled) { replacementMissOutsideArea++; windowReplacementMissOutsideArea++; } return false; } } if (cachedRequireInitialStableGraph && !replacementArmed) { if (diagnosticsEnabled) { replacementMissNotArmed++; windowReplacementMissNotArmed++; } return false; } if (value == null || !value.IsReady || !value.IsPrepared || value.GeometryDirty || value.ContactsDirty || value.PrepareQueued || value.RefreshQueued || value.SolveQueued) { if (cachedReleaseVanillaCache && value != null) { value.LastVanillaFallbackTime = currentRealtimeSinceStartup; value.VanillaCacheReleased = false; } if (diagnosticsEnabled) { replacementMissNotReady++; windowReplacementMissNotReady++; } return false; } if (!value.SupportValid) { if (diagnosticsEnabled) { replacementInvalidSupport++; windowReplacementInvalidSupport++; } string[] obj = new string[7] { "Invalid graph support for ", ((Object)instance).name, "#", null, null, null, null }; int runtimeId = value.RuntimeId; obj[3] = runtimeId.ToString(); obj[4] = ": "; obj[5] = value.GraphSupport.ToString(); obj[6] = "."; DisableReplacementForSession(string.Concat(obj), null); return false; } support = value.GraphSupport; if (diagnosticsEnabled) { replacementHits++; windowReplacementHits++; } return true; } private void SynchronizeOwnerIfNeeded(IntegrityNode node, bool forceCheck) { if (!cachedApplySupportToZdo || node == null || (Object)(object)node.NView == (Object)null || (!forceCheck && currentRealtimeSinceStartup < node.NextOwnershipCheckTime)) { return; } bool flag = forceCheck || !node.OwnerSyncEstablished; node.NextOwnershipCheckTime = currentRealtimeSinceStartup + cachedOwnershipRecheckSeconds; bool flag2; try { flag2 = node.NView.IsValid() && node.NView.IsOwner(); } catch { flag2 = false; } bool flag3 = node.OwnershipKnown && flag2 != node.LastKnownOwner; node.OwnershipKnown = true; node.LastKnownOwner = flag2; if (!flag2) { node.OwnerSyncEstablished = false; if (diagnosticsEnabled) { zdoWritesSkippedNotOwner++; } } else { if (!flag && !flag3) { return; } ResetZdoWriteBudgetIfNeeded(); bool allowNonCriticalWrite = zdoWritesThisFrame < cachedMaximumSupportZdoWritesPerFrame; ZdoWriteResult zdoWriteResult = WearNTearAccess.WriteSupportToZdo(node.Instance, node.NView, node.GraphSupport, node.Material, cachedNetworkAbsoluteEpsilon, cachedNetworkNormalizedEpsilon, flag3, allowNonCriticalWrite); if (zdoWriteResult == ZdoWriteResult.Written) { zdoWritesThisFrame++; if (diagnosticsEnabled) { zdoWrites++; } } else if (zdoWriteResult == ZdoWriteResult.SkippedEpsilon) { if (diagnosticsEnabled) { zdoWritesSkippedEpsilon++; } } else if (zdoWriteResult == ZdoWriteResult.SkippedNotOwner && diagnosticsEnabled) { zdoWritesSkippedNotOwner++; } else if (zdoWriteResult == ZdoWriteResult.SkippedBudget) { node.NextOwnershipCheckTime = currentRealtimeSinceStartup + 0.05f; nextOwnershipSweepTime = Math.Min(nextOwnershipSweepTime, node.NextOwnershipCheckTime); if (diagnosticsEnabled) { zdoWritesDeferredBudget++; } } node.OwnerSyncEstablished = zdoWriteResult == ZdoWriteResult.Written || zdoWriteResult == ZdoWriteResult.SkippedEpsilon; } } internal void DisableReplacementForSession(string reason, Exception exception) { if (exception != null) { replacementExceptions++; windowReplacementExceptions++; } if (!replacementFaulted) { replacementFaulted = true; replacementArmed = false; replacementCircuitTrips++; windowReplacementCircuitTrips++; replacementFaultReason = (string.IsNullOrEmpty(reason) ? "Unknown replacement failure." : reason); string text = "Replacement circuit breaker opened for this world session. " + replacementFaultReason + " Vanilla integrity remains active until the world is reloaded or the graph is rebuilt."; if (exception == null) { log.LogError((object)text); } else { log.LogError((object)(text + " Exception: " + exception)); } } } internal unsafe void RecordVanillaResult(WearNTear instance, float vanillaSupport) { //IL_0085: Unknown result type (might be due to invalid IL or missing references) //IL_008a: 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_008c: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_00ac: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00ad: Unknown result type (might be due to invalid IL or missing references) //IL_00af: Unknown result type (might be due to invalid IL or missing references) //IL_00b0: 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) //IL_00fe: Unknown result type (might be due to invalid IL or missing references) //IL_0348: Unknown result type (might be due to invalid IL or missing references) //IL_0349: Unknown result type (might be due to invalid IL or missing references) //IL_0366: Unknown result type (might be due to invalid IL or missing references) //IL_036b: Unknown result type (might be due to invalid IL or missing references) if (!diagnosticsEnabled || (Object)(object)instance == (Object)null || !nodes.TryGetValue(((Object)instance).GetInstanceID(), out var value) || !value.IsReady) { return; } bool vanillaStable = !value.RequiresSupport || vanillaSupport >= value.Material.MinSupport; float visualMismatchThreshold = Mathf.Clamp01(config.VisualDifferenceThreshold.Value); Vector3 position = ((Component)instance).transform.position; Vector2Int zoneCoordinate = GetZoneCoordinate(position); Vector3 val = (((Object)(object)ZNet.instance == (Object)null) ? position : ZNet.instance.GetReferencePosition()); float distanceFromReference = Vector3.Distance(position, val); bool outsideActiveArea = IsOutsideActiveArea(instance); if (benchmark.Record(value.RuntimeId, ((Object)instance).name, WearNTearAccess.GetMaterialType(instance), value.Material, vanillaSupport, value.GraphSupport, vanillaStable, value.GraphStable, visualMismatchThreshold, config.ComparisonChangeEpsilon.Value, position, ((Vector2Int)(ref zoneCoordinate)).x, ((Vector2Int)(ref zoneCoordinate)).y, distanceFromReference, outsideActiveArea, value.Anchor, value.Links.Count)) { float num = Math.Abs(vanillaSupport - value.GraphSupport); float num2 = Math.Abs(NormalizeSupport(vanillaSupport, value.Material) - NormalizeSupport(value.GraphSupport, value.Material)); if (config.VerboseLogging.Value && (num >= Math.Max(0f, config.DifferenceWarning.Value) || num2 >= Mathf.Clamp01(config.NormalizedDifferenceWarning.Value))) { ManualLogSource obj = log; string[] array = new string[32]; array[0] = "Support difference "; array[1] = ((Object)instance).name; array[2] = "#"; int runtimeId = value.RuntimeId; array[3] = runtimeId.ToString(); array[4] = ": vanilla="; array[5] = vanillaSupport.ToString("F2"); array[6] = ", graph="; array[7] = value.GraphSupport.ToString("F2"); array[8] = ", normalized="; array[9] = num2.ToString("F3"); array[10] = ", stable="; array[11] = vanillaStable.ToString(); array[12] = "/"; array[13] = value.GraphStable.ToString(); array[14] = ", anchor="; array[15] = value.Anchor.ToString(); array[16] = ", edges="; array[17] = value.Links.Count.ToString(); array[18] = ", colliders="; array[19] = value.Colliders.Length.ToString(); array[20] = ", zone="; array[21] = ((Vector2Int)(ref zoneCoordinate)).x.ToString(); array[22] = "/"; array[23] = ((Vector2Int)(ref zoneCoordinate)).y.ToString(); array[24] = ", distance="; array[25] = distanceFromReference.ToString("F1"); array[26] = ", outside="; array[27] = outsideActiveArea.ToString(); array[28] = ", position="; Vector3 val2 = position; array[29] = ((object)(*(Vector3*)(&val2))/*cast due to .constrained prefix*/).ToString(); array[30] = ", material="; array[31] = ((object)WearNTearAccess.GetMaterialType(instance)/*cast due to .constrained prefix*/).ToString(); obj.LogWarning((object)string.Concat(array)); } } } internal void Tick(float realtimeSinceStartup) { currentRealtimeSinceStartup = realtimeSinceStartup; if (runtimeOptionsDirty) { RefreshRuntimeOptions(realtimeSinceStartup); } if (Launch.RuntimeMode == IntegrityMode.Vanilla) { if (diagnosticsEnabled && Launch.InformationLoggingEnabled) { float num = Math.Max(0f, config.StatsIntervalSeconds.Value); if (num > 0f && realtimeSinceStartup >= nextStatsTime) { nextStatsTime = realtimeSinceStartup + num; LogStats(realtimeSinceStartup); } } return; } UpdateActiveAreaSchedule(realtimeSinceStartup); UpdateMaintenanceSchedule(realtimeSinceStartup); if (HasPendingWork()) { double num2 = cachedWorkBudgetMilliseconds; workWatch.Restart(); bool flag = true; while (workWatch.Elapsed.TotalMilliseconds < num2) { WorkStage workStage = WorkStage.None; bool flag2 = prepareQueue.Count > 0 || currentRefreshNodeId != 0 || refreshQueue.Count > 0 || ((solvePhase != SolvePhase.None || solveQueue.Count > 0) && realtimeSinceStartup >= solveNotBefore) || HasPendingMaintenance(); double num3 = (detailedStageTimingEnabled ? workWatch.Elapsed.TotalMilliseconds : 0.0); bool flag3; if (reconcilePhase != ReconcilePhase.None && (flag || !flag2)) { workStage = WorkStage.Reconcile; flag3 = ProcessReconciliationStep(); flag = false; } else if (prepareQueue.Count > 0) { workStage = WorkStage.Prepare; flag3 = ProcessPrepare(); flag = true; } else if (currentRefreshNodeId != 0 || refreshQueue.Count > 0) { workStage = WorkStage.Refresh; flag3 = ProcessRefreshStep(); flag = true; } else if ((solvePhase != SolvePhase.None || solveQueue.Count > 0) && realtimeSinceStartup >= solveNotBefore) { workStage = WorkStage.Solve; flag3 = ProcessSolveStep(); flag = true; } else if (HasPendingMaintenance()) { workStage = WorkStage.Maintenance; flag3 = ProcessMaintenanceStep(); flag = true; } else { if (reconcilePhase == ReconcilePhase.None) { break; } workStage = WorkStage.Reconcile; flag3 = ProcessReconciliationStep(); flag = false; } if (detailedStageTimingEnabled && workStage != WorkStage.None) { RecordStageTiming(workStage, Math.Max(0.0, workWatch.Elapsed.TotalMilliseconds - num3)); } if (!flag3 && !HasPendingWork()) { break; } } workWatch.Stop(); if (diagnosticsEnabled) { lastWorkMilliseconds = workWatch.Elapsed.TotalMilliseconds; maximumWorkMilliseconds = Math.Max(maximumWorkMilliseconds, lastWorkMilliseconds); windowMaximumWorkMilliseconds = Math.Max(windowMaximumWorkMilliseconds, lastWorkMilliseconds); } } else if (diagnosticsEnabled) { lastWorkMilliseconds = 0.0; } if (!replacementArmed && !replacementFaulted && IsGraphSettled()) { if (ValidateGraphForReplacement(out var failure)) { replacementArmed = true; if (Launch.RuntimeMode == IntegrityMode.Replace && Launch.InformationLoggingEnabled) { log.LogInfo((object)("Initial active-area graph is stable. Replacement is now armed for " + nodes.Count + " WearNTear nodes.")); } } else { DisableReplacementForSession(failure, null); } } if (diagnosticsEnabled && Launch.InformationLoggingEnabled) { float num4 = Math.Max(0f, config.StatsIntervalSeconds.Value); if (num4 > 0f && realtimeSinceStartup >= nextStatsTime) { nextStatsTime = realtimeSinceStartup + num4; LogStats(realtimeSinceStartup); } } } private bool ValidateGraphForReplacement(out string failure) { foreach (IntegrityNode value in nodes.Values) { if (value.IsAlive) { if (!value.IsPrepared || !value.IsReady || value.GeometryDirty || value.ContactsDirty || value.PrepareQueued || value.RefreshQueued || value.SolveQueued) { string[] obj = new string[5] { "Graph settled with an unready node: ", ((Object)value.Instance).name, "#", null, null }; int runtimeId = value.RuntimeId; obj[3] = runtimeId.ToString(); obj[4] = "."; failure = string.Concat(obj); return false; } if (!value.SupportValid || !IsFiniteSupport(value.GraphSupport, value.Material)) { string[] obj2 = new string[7] { "Graph settled with invalid support on ", ((Object)value.Instance).name, "#", null, null, null, null }; int runtimeId = value.RuntimeId; obj2[3] = runtimeId.ToString(); obj2[4] = ": "; obj2[5] = value.GraphSupport.ToString(); obj2[6] = "."; failure = string.Concat(obj2); return false; } } } failure = string.Empty; return true; } private void RecordStageTiming(WorkStage stage, double milliseconds) { switch (stage) { case WorkStage.Prepare: windowMaxPrepareMilliseconds = Math.Max(windowMaxPrepareMilliseconds, milliseconds); lifetimeMaxPrepareMilliseconds = Math.Max(lifetimeMaxPrepareMilliseconds, milliseconds); break; case WorkStage.Refresh: windowMaxRefreshMilliseconds = Math.Max(windowMaxRefreshMilliseconds, milliseconds); lifetimeMaxRefreshMilliseconds = Math.Max(lifetimeMaxRefreshMilliseconds, milliseconds); break; case WorkStage.Solve: windowMaxSolveMilliseconds = Math.Max(windowMaxSolveMilliseconds, milliseconds); lifetimeMaxSolveMilliseconds = Math.Max(lifetimeMaxSolveMilliseconds, milliseconds); break; case WorkStage.Reconcile: windowMaxReconcileMilliseconds = Math.Max(windowMaxReconcileMilliseconds, milliseconds); lifetimeMaxReconcileMilliseconds = Math.Max(lifetimeMaxReconcileMilliseconds, milliseconds); break; case WorkStage.Maintenance: windowMaxMaintenanceMilliseconds = Math.Max(windowMaxMaintenanceMilliseconds, milliseconds); lifetimeMaxMaintenanceMilliseconds = Math.Max(lifetimeMaxMaintenanceMilliseconds, milliseconds); break; } } internal void LogStats(float realtimeSinceStartup) { if (!diagnosticsEnabled || !Launch.InformationLoggingEnabled) { return; } RuntimeStats stats = GetStats(); ComparisonTotals lifetime = stats.Benchmark.Lifetime; ComparisonTotals window = stats.Benchmark.Window; IntegrityMode runtimeMode = Launch.RuntimeMode; bool flag = stats.PrepareQueue > 0 || stats.RefreshQueue > 0 || stats.SolveQueue > 0 || stats.SolvePhase != "None" || stats.ReconcilePhase != "None"; bool flag2 = stats.Nodes != lastLoggedNodes || stats.Edges != lastLoggedEdges || stats.TerrainAnchors != lastLoggedTerrainAnchors || stats.StaticAnchors != lastLoggedStaticAnchors || stats.Benchmark.CurrentStabilityMismatchNodes != lastLoggedStableMismatches || stats.Benchmark.CurrentVisualMismatchNodes != lastLoggedVisualMismatches; bool flag3 = runtimeMode == IntegrityMode.Observe && (window.Comparisons > 0 || window.StabilityMismatches > 0 || window.VisualMismatches > 0); bool flag4 = runtimeMode == IntegrityMode.Replace && (stats.WindowReplacementRequests > 0 || stats.WindowReplacementInvalidSupport > 0 || stats.WindowReplacementExceptions > 0 || stats.WindowReplacementCircuitTrips > 0 || stats.ReplacementFaulted); bool flag5 = profilingEnabled && (stats.Profiler.ReplacementLookup.WindowCalls > 0 || stats.Profiler.VanillaSupport.WindowCalls > 0 || stats.Profiler.WearUpdater.WindowCalls > 0); bool flag6 = realtimeSinceStartup >= nextIdleHeartbeatTime; if (config.LogIdleStatistics.Value || flag || flag2 || flag3 || flag4 || flag5 || flag6) { string value = (stats.ReplacementFaulted ? "Faulted" : (stats.ReplacementArmed ? "Armed" : "Warming")); double num = ((stats.ReplacementRequests <= 0) ? 0.0 : (100.0 * (double)stats.ReplacementHits / (double)stats.ReplacementRequests)); statsBuilder.Length = 0; statsBuilder.Append("BetterBuild stats: mode="); statsBuilder.Append(runtimeMode); statsBuilder.Append(", nodes="); statsBuilder.Append(stats.Nodes); statsBuilder.Append(", prepared="); statsBuilder.Append(stats.PreparedNodes); statsBuilder.Append(", ready="); statsBuilder.Append(stats.ReadyNodes); statsBuilder.Append(", comparable="); statsBuilder.Append(stats.ComparableNodes); statsBuilder.Append(", edges="); statsBuilder.Append(stats.Edges); statsBuilder.Append(", anchors="); statsBuilder.Append(stats.TerrainAnchors); statsBuilder.Append('/'); statsBuilder.Append(stats.StaticAnchors); statsBuilder.Append(", queues="); statsBuilder.Append(stats.PrepareQueue); statsBuilder.Append('/'); statsBuilder.Append(stats.RefreshQueue); statsBuilder.Append('/'); statsBuilder.Append(stats.SolveQueue); statsBuilder.Append(", phase="); statsBuilder.Append(stats.SolvePhase); statsBuilder.Append(", reconcile="); statsBuilder.Append(stats.ReconcilePhase); statsBuilder.Append(", reconcileRemaining="); statsBuilder.Append(stats.ReconcileScanRemaining); statsBuilder.Append('/'); statsBuilder.Append(stats.ReconcilePruneRemaining); statsBuilder.Append(", reconciliations="); statsBuilder.Append(stats.Reconciliations); statsBuilder.Append("(zone="); statsBuilder.Append(stats.ZoneChangeReconciliations); statsBuilder.Append(",periodic="); statsBuilder.Append(stats.PeriodicReconciliations); statsBuilder.Append(",requested="); statsBuilder.Append(stats.RequestedReconciliations); statsBuilder.Append(",last="); statsBuilder.Append(stats.LastReconcileReason); statsBuilder.Append(')'); statsBuilder.Append(", pruned="); statsBuilder.Append(stats.ReconciledPrunedNodes); statsBuilder.Append(", replace="); statsBuilder.Append(value); statsBuilder.Append(", islands="); statsBuilder.Append(stats.SolvedIslands); statsBuilder.Append(", solvedNodes="); statsBuilder.Append(stats.SolvedNodes); statsBuilder.Append(", relax="); statsBuilder.Append(stats.SupportRelaxations); statsBuilder.Append(", zdo="); statsBuilder.Append(stats.ZdoWrites); statsBuilder.Append("(eps="); statsBuilder.Append(stats.ZdoWritesSkippedEpsilon); statsBuilder.Append(",notOwner="); statsBuilder.Append(stats.ZdoWritesSkippedNotOwner); statsBuilder.Append(",budget="); statsBuilder.Append(stats.ZdoWritesDeferredBudget); statsBuilder.Append(')'); statsBuilder.Append(", releasedCaches="); statsBuilder.Append(stats.VanillaCachesReleased); statsBuilder.Append(", allocations(nodes/remove/nodeLists/cellLists)="); statsBuilder.Append(stats.NodeAllocations); statsBuilder.Append('/'); statsBuilder.Append(stats.NodeRemovals); statsBuilder.Append('/'); statsBuilder.Append(stats.AllocatedNodeLists); statsBuilder.Append('/'); statsBuilder.Append(stats.SpatialAllocatedLists); statsBuilder.Append(", nodePools(link/dependent/discarded)="); statsBuilder.Append(stats.PooledLinkLists); statsBuilder.Append('/'); statsBuilder.Append(stats.PooledDependentLists); statsBuilder.Append('/'); statsBuilder.Append(stats.DiscardedNodeLists); statsBuilder.Append(", spatial(cells/pool/discarded/owners)="); statsBuilder.Append(stats.SpatialCells); statsBuilder.Append('/'); statsBuilder.Append(stats.SpatialPooledLists); statsBuilder.Append('/'); statsBuilder.Append(stats.SpatialDiscardedLists); statsBuilder.Append('/'); statsBuilder.Append(stats.ColliderOwnerCacheEntries); statsBuilder.Append(", staticCache="); statsBuilder.Append(stats.StaticColliderCacheEntries); statsBuilder.Append("(hit/miss="); statsBuilder.Append(stats.NegativeColliderCacheHits); statsBuilder.Append('/'); statsBuilder.Append(stats.NegativeColliderCacheMisses); statsBuilder.Append(')'); statsBuilder.Append(", graphEst="); statsBuilder.Append(((double)stats.EstimatedGraphBytes / 1024.0).ToString("F1")); statsBuilder.Append("KiB"); statsBuilder.Append(", overlap="); statsBuilder.Append(stats.OverlapRetries); statsBuilder.Append('/'); statsBuilder.Append(stats.OverlapOverflows); statsBuilder.Append(" cap="); statsBuilder.Append(stats.OverlapCapacity); statsBuilder.Append(", work="); statsBuilder.Append(stats.LastWorkMilliseconds.ToString("F3")); statsBuilder.Append("ms, maxWindow="); statsBuilder.Append(stats.WindowMaximumWorkMilliseconds.ToString("F3")); statsBuilder.Append("ms, maxLifetime="); statsBuilder.Append(stats.MaximumWorkMilliseconds.ToString("F3")); statsBuilder.Append("ms, stageMaxWindow(p/r/s/c/m)="); statsBuilder.Append(stats.WindowMaxPrepareMilliseconds.ToString("F3")); statsBuilder.Append('/'); statsBuilder.Append(stats.WindowMaxRefreshMilliseconds.ToString("F3")); statsBuilder.Append('/'); statsBuilder.Append(stats.WindowMaxSolveMilliseconds.ToString("F3")); statsBuilder.Append('/'); statsBuilder.Append(stats.WindowMaxReconcileMilliseconds.ToString("F3")); statsBuilder.Append('/'); statsBuilder.Append(stats.WindowMaxMaintenanceMilliseconds.ToString("F3")); statsBuilder.Append("ms"); switch (runtimeMode) { case IntegrityMode.Replace: { long value2 = stats.WindowReplacementMissNotArmed + stats.WindowReplacementMissNotReady + stats.WindowReplacementMissOutsideArea + stats.WindowReplacementMissFaulted; double num2 = ((stats.WindowReplacementRequests <= 0) ? 0.0 : (100.0 * (double)stats.WindowReplacementHits / (double)stats.WindowReplacementRequests)); statsBuilder.Append(", replaceWindow="); statsBuilder.Append(stats.WindowReplacementRequests); statsBuilder.Append('/'); statsBuilder.Append(stats.WindowReplacementHits); statsBuilder.Append('('); statsBuilder.Append(num2.ToString("F1")); statsBuilder.Append("%), windowMisses="); statsBuilder.Append(value2); statsBuilder.Append("(arm="); statsBuilder.Append(stats.WindowReplacementMissNotArmed); statsBuilder.Append(",ready="); statsBuilder.Append(stats.WindowReplacementMissNotReady); statsBuilder.Append(",outside="); statsBuilder.Append(stats.WindowReplacementMissOutsideArea); statsBuilder.Append(",fault="); statsBuilder.Append(stats.WindowReplacementMissFaulted); statsBuilder.Append("), replaceLifetime="); statsBuilder.Append(stats.ReplacementRequests); statsBuilder.Append('/'); statsBuilder.Append(stats.ReplacementHits); statsBuilder.Append('('); statsBuilder.Append(num.ToString("F1")); statsBuilder.Append("%), invalid="); statsBuilder.Append(stats.ReplacementInvalidSupport); statsBuilder.Append(", exceptions="); statsBuilder.Append(stats.ReplacementExceptions); statsBuilder.Append(", circuitTrips="); statsBuilder.Append(stats.ReplacementCircuitTrips); if (stats.ReplacementFaulted) { statsBuilder.Append(", faultReason="); statsBuilder.Append(stats.ReplacementFaultReason); } break; } case IntegrityMode.Observe: statsBuilder.Append(", comparedUnique="); statsBuilder.Append(stats.Benchmark.UniqueComparedNodes); statsBuilder.Append(", waitingVanilla="); statsBuilder.Append(Math.Max(0, stats.ComparableNodes - stats.Benchmark.UniqueComparedNodes)); statsBuilder.Append(", compareCoverage="); statsBuilder.Append((stats.ComparableNodes <= 0) ? "0.0%" : ((100.0 * (double)stats.Benchmark.UniqueComparedNodes / (double)stats.ComparableNodes).ToString("F1") + "%")); statsBuilder.Append(", currentStableMismatch="); statsBuilder.Append(stats.Benchmark.CurrentStabilityMismatchNodes); statsBuilder.Append(", currentVisualMismatch="); statsBuilder.Append(stats.Benchmark.CurrentVisualMismatchNodes); statsBuilder.Append(", windowChanged="); statsBuilder.Append(window.Comparisons); statsBuilder.Append(", windowStableMismatch="); statsBuilder.Append(window.StabilityMismatches); statsBuilder.Append(", windowVisualMismatch="); statsBuilder.Append(window.VisualMismatches); statsBuilder.Append(", windowAvgNorm="); statsBuilder.Append(window.AverageNormalizedDifference.ToString("F3")); statsBuilder.Append(", windowMaxNorm="); statsBuilder.Append(window.MaximumNormalizedDifference.ToString("F3")); statsBuilder.Append(", lifetimeChanged="); statsBuilder.Append(lifetime.Comparisons); statsBuilder.Append(", lifetimeStableMismatch="); statsBuilder.Append(lifetime.StabilityMismatches); statsBuilder.Append(", lifetimeAvgNorm="); statsBuilder.Append(lifetime.AverageNormalizedDifference.ToString("F3")); statsBuilder.Append(", lifetimeMaxNorm="); statsBuilder.Append(lifetime.MaximumNormalizedDifference.ToString("F3")); break; } if (profilingEnabled) { AppendProfiler(statsBuilder, stats.Profiler); } log.LogInfo((object)statsBuilder.ToString()); if (runtimeMode == IntegrityMode.Observe && config.LogMaterialBreakdown.Value && !string.IsNullOrEmpty(stats.Benchmark.MaterialSummary)) { log.LogInfo((object)("BetterBuild materials: " + stats.Benchmark.MaterialSummary)); } if (runtimeMode == IntegrityMode.Observe && !string.IsNullOrEmpty(stats.Benchmark.TopDifferences)) { log.LogInfo((object)("BetterBuild top differences: " + stats.Benchmark.TopDifferences)); } lastLoggedNodes = stats.Nodes; lastLoggedEdges = stats.Edges; lastLoggedTerrainAnchors = stats.TerrainAnchors; lastLoggedStaticAnchors = stats.StaticAnchors; lastLoggedStableMismatches = stats.Benchmark.CurrentStabilityMismatchNodes; lastLoggedVisualMismatches = stats.Benchmark.CurrentVisualMismatchNodes; float num3 = Math.Max(0f, config.IdleHeartbeatSeconds.Value); nextIdleHeartbeatTime = ((num3 > 0f) ? (realtimeSinceStartup + num3) : float.PositiveInfinity); } ResetDiagnosticWindow(); } private static void AppendProfiler(StringBuilder builder, ProfilerSnapshot snapshot) { builder.Append(", profiler lookup="); AppendTiming(builder, snapshot.ReplacementLookup); builder.Append(", vanillaSupport="); AppendTiming(builder, snapshot.VanillaSupport); builder.Append(", wearUpdater="); AppendTiming(builder, snapshot.WearUpdater); builder.Append(", managed="); builder.Append(((double)snapshot.ManagedBytes / 1048576.0).ToString("F1")); builder.Append("MiB, gc="); builder.Append(snapshot.Gen0Collections); builder.Append('/'); builder.Append(snapshot.Gen1Collections); builder.Append('/'); builder.Append(snapshot.Gen2Collections); } private static void AppendTiming(StringBuilder builder, TimingSnapshot timing) { builder.Append(timing.WindowCalls); builder.Append(" calls/"); builder.Append(timing.WindowMilliseconds.ToString("F3")); builder.Append("ms avg="); builder.Append(timing.WindowAverageMicroseconds.ToString("F2")); builder.Append("us max="); builder.Append((timing.WindowMaximumMilliseconds * 1000.0).ToString("F2")); builder.Append("us"); } private void ResetDiagnosticWindow() { windowMaximumWorkMilliseconds = 0.0; windowMaxPrepareMilliseconds = 0.0; windowMaxRefreshMilliseconds = 0.0; windowMaxSolveMilliseconds = 0.0; windowMaxReconcileMilliseconds = 0.0; windowMaxMaintenanceMilliseconds = 0.0; windowReplacementRequests = 0L; windowReplacementHits = 0L; windowReplacementMissNotArmed = 0L; windowReplacementMissNotReady = 0L; windowReplacementMissOutsideArea = 0L; windowReplacementMissFaulted = 0L; windowReplacementInvalidSupport = 0L; windowReplacementExceptions = 0L; windowReplacementCircuitTrips = 0L; } private void UpdateActiveAreaSchedule(float realtimeSinceStartup) { //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_0077: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Unknown result type (might be due to invalid IL or missing references) if (reconcilePhase != ReconcilePhase.None) { return; } bool flag = false; if (!dedicatedServer && realtimeSinceStartup >= nextReferenceZoneCheckTime) { nextReferenceZoneCheckTime = realtimeSinceStartup + 0.25f; if (TryGetReferenceZone(out var zone) && (!hasReferenceZone || !((Vector2Int)(ref zone)).Equals(lastReferenceZone))) { hasReferenceZone = true; lastReferenceZone = zone; flag = true; } } if (flag || realtimeSinceStartup >= nextReconcileTime) { StartReconciliation(flag ? ReconcileReason.ZoneChange : ReconcileReason.PeriodicSafety); } } private void UpdateMaintenanceSchedule(float realtimeSinceStartup) { if (cachedApplySupportToZdo && !ownerSweepActive && realtimeSinceStartup >= nextOwnershipSweepTime) { ownerSweepActive = activeNodeIds.Count > 0; ownerSweepIndex = 0; if (!ownerSweepActive) { nextOwnershipSweepTime = realtimeSinceStartup + cachedOwnershipRecheckSeconds; } } else if (!cachedApplySupportToZdo) { ownerSweepActive = false; ownerSweepIndex = 0; } bool flag = cachedReleaseVanillaCache && Launch.RuntimeMode == IntegrityMode.Replace && replacementArmed && !replacementFaulted; if (flag && !cacheReleaseSweepActive && realtimeSinceStartup >= nextCacheReleaseSweepTime) { cacheReleaseSweepActive = activeNodeIds.Count > 0; cacheReleaseSweepIndex = 0; if (!cacheReleaseSweepActive) { nextCacheReleaseSweepTime = realtimeSinceStartup + 5f; } } else if (!flag) { cacheReleaseSweepActive = false; cacheReleaseSweepIndex = 0; } } private bool HasPendingMaintenance() { return ownerSyncQueue.Count > 0 || ownerSweepActive || cacheReleaseSweepActive; } private bool ProcessMaintenanceStep() { while (ownerSyncQueue.Count > 0) { int key = ownerSyncQueue.Dequeue(); if (!nodes.TryGetValue(key, out var value) || !value.IsAlive) { continue; } value.OwnerSyncQueued = false; if (value.IsReady && value.SupportValid) { SynchronizeOwnerIfNeeded(value, forceCheck: true); } return true; } if (ownerSweepActive) { if (ownerSweepIndex >= activeNodeIds.Count) { ownerSweepActive = false; ownerSweepIndex = 0; nextOwnershipSweepTime = currentRealtimeSinceStartup + cachedOwnershipRecheckSeconds; return true; } int key2 = activeNodeIds[ownerSweepIndex++]; if (nodes.TryGetValue(key2, out var value2) && value2.IsAlive && value2.IsReady && value2.SupportValid) { SynchronizeOwnerIfNeeded(value2, forceCheck: false); } return true; } if (cacheReleaseSweepActive) { ResetCacheReleaseBudgetIfNeeded(); if (cacheReleasesThisFrame >= cachedMaximumVanillaCacheReleasesPerFrame) { cacheReleaseSweepActive = false; nextCacheReleaseSweepTime = currentRealtimeSinceStartup + 0.05f; return false; } if (cacheReleaseSweepIndex >= activeNodeIds.Count) { cacheReleaseSweepActive = false; cacheReleaseSweepIndex = 0; nextCacheReleaseSweepTime = currentRealtimeSinceStartup + 5f; return true; } int key3 = activeNodeIds[cacheReleaseSweepIndex++]; if (!nodes.TryGetValue(key3, out var value3) || !value3.IsAlive || value3.VanillaCacheReleased || !value3.IsReady || !value3.SupportValid || value3.GeometryDirty || value3.ContactsDirty || value3.PrepareQueued || value3.RefreshQueued || value3.SolveQueued || currentRealtimeSinceStartup < value3.CacheReleaseEligibleTime || currentRealtimeSinceStartup < value3.LastVanillaFallbackTime + cachedVanillaCacheReleaseFallbackCooldownSeconds) { return true; } if (WearNTearAccess.ReleaseVanillaSupportCache(value3.Instance)) { value3.VanillaCacheReleased = true; cacheReleasesThisFrame++; if (diagnosticsEnabled) { vanillaCachesReleased++; } } return true; } return false; } private void QueueOwnerSync(IntegrityNode node) { if (cachedApplySupportToZdo && node != null && node.IsAlive && !node.OwnerSyncQueued) { node.OwnerSyncQueued = true; ownerSyncQueue.Enqueue(node.RuntimeId); } } private void ResetCacheReleaseBudgetIfNeeded() { int frameCount = Time.frameCount; if (frameCount != cacheReleaseBudgetFrame) { cacheReleaseBudgetFrame = frameCount; cacheReleasesThisFrame = 0; } } private void RequestActiveAreaReconciliation(bool immediate, ReconcileReason reason) { if (Launch.RuntimeMode != IntegrityMode.Vanilla) { if (reconcilePhase != ReconcilePhase.None) { reconcileRestartRequested = true; reconcileRestartReason = reason; } else if (immediate) { StartReconciliation(reason); } else { nextReconcileTime = Math.Min(nextReconcileTime, Time.realtimeSinceStartup + 0.05f); } } } private void StartReconciliation(ReconcileReason reason) { if (reconcilePhase == ReconcilePhase.None && !((Object)(object)ZNetScene.instance == (Object)null) && !((Object)(object)ZoneSystem.instance == (Object)null)) { reconcileInstances = WearNTear.GetAllInstances(); if (reason == ReconcileReason.ZoneChange || reason == ReconcileReason.WorldStart) { staticColliderCache.Clear(); } reconcileInstanceIndex = 0; reconcileNodeIndex = 0; reconcileGraphChanged = false; reconcileRestartRequested = false; reconcileRestartReason = ReconcileReason.None; reconcileReason = reason; reconcilePhase = ReconcilePhase.ScanInstances; } } private bool ProcessReconciliationStep() { if (reconcilePhase == ReconcilePhase.ScanInstances) { List list = reconcileInstances; if (list != null && reconcileInstanceIndex < list.Count) { WearNTear instance = list[reconcileInstanceIndex++]; Register(instance); return true; } reconcilePhase = ReconcilePhase.PruneNodes; return true; } if (reconcilePhase == ReconcilePhase.PruneNodes) { if (reconcileNodeIndex < activeNodeIds.Count) { int num = activeNodeIds[reconcileNodeIndex]; if (!nodes.TryGetValue(num, out var value)) { reconcileNodeIndex++; return true; } if (!value.IsAlive || !ShouldManageNode(value)) { if (RemoveNode(num, markNearby: false, mutateImmediately: false) && diagnosticsEnabled) { reconciledPrunedNodes++; } } else { reconcileNodeIndex++; } return true; } FinishReconciliation(); return true; } return false; } private void FinishReconciliation() { reconcileInstances = null; reconcileInstanceIndex = 0; reconcileNodeIndex = 0; reconcilePhase = ReconcilePhase.None; lastCompletedReconcileReason = reconcileReason; if (diagnosticsEnabled) { completedReconciliations++; if (reconcileReason == ReconcileReason.ZoneChange) { zoneChangeReconciliations++; } else if (reconcileReason == ReconcileReason.PeriodicSafety) { periodicReconciliations++; } else { requestedReconciliations++; } } if (reconcileGraphChanged) { MutatedGraph(); } reconcileGraphChanged = false; nextReconcileTime = currentRealtimeSinceStartup + cachedReconcileSeconds; if (reconcileRestartRequested) { reconcileRestartRequested = false; ReconcileReason reason = ((reconcileRestartReason == ReconcileReason.None) ? ReconcileReason.RestartRequested : reconcileRestartReason); reconcileRestartReason = ReconcileReason.None; StartReconciliation(reason); } } private void CancelReconciliation() { reconcilePhase = ReconcilePhase.None; reconcileInstances = null; reconcileInstanceIndex = 0; reconcileNodeIndex = 0; reconcileGraphChanged = false; reconcileRestartRequested = false; reconcileReason = ReconcileReason.None; reconcileRestartReason = ReconcileReason.None; } private bool ShouldManageInstance(WearNTear instance, out ZNetView nview) { nview = null; if ((Object)(object)ZNetScene.instance == (Object)null || !WearNTearAccess.TryGetRuntimeNView(instance, out nview)) { return false; } if (dedicatedServer) { return true; } return !IsOutsideActiveArea(instance); } private bool ShouldManageNode(IntegrityNode node) { if (node == null || !node.IsAlive || (Object)(object)node.NView == (Object)null || node.NView.GetZDO() == null || (Object)(object)ZNetScene.instance == (Object)null) { return false; } if (dedicatedServer) { return true; } return !IsOutsideActiveArea(node.Instance); } private static bool IsOutsideActiveArea(WearNTear instance) { //IL_002e: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)instance == (Object)null || (Object)(object)ZNetScene.instance == (Object)null) { return true; } try { return ZNetScene.instance.OutsideActiveArea(((Component)instance).transform.position); } catch { return false; } } private static bool IsDedicatedServer() { try { return (Object)(object)ZNet.instance != (Object)null && ZNet.instance.IsDedicated(); } catch { return false; } } private static Vector2Int GetZoneCoordinate(Vector3 position) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0018: 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) //IL_0037: Unknown result type (might be due to invalid IL or missing references) return new Vector2Int(Mathf.FloorToInt((position.x + 32f) / 64f), Mathf.FloorToInt((position.z + 32f) / 64f)); } private static bool TryGetReferenceZone(out Vector2Int zone) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Unknown result type (might be due to invalid IL or missing references) zone = default(Vector2Int); if ((Object)(object)ZNet.instance == (Object)null || (Object)(object)ZoneSystem.instance == (Object)null) { return false; } try { zone = GetZoneCoordinate(ZNet.instance.GetReferencePosition()); return true; } catch { return false; } } private bool HasPendingWork() { return reconcilePhase != ReconcilePhase.None || prepareQueue.Count > 0 || currentRefreshNodeId != 0 || refreshQueue.Count > 0 || solvePhase != SolvePhase.None || solveQueue.Count > 0 || HasPendingMaintenance(); } private bool IsGraphSettled() { return reconcilePhase == ReconcilePhase.None && prepareQueue.Count == 0 && currentRefreshNodeId == 0 && refreshQueue.Count == 0 && solvePhase == SolvePhase.None && solveQueue.Count == 0; } private bool ProcessPrepare() { //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_00a1: 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_00b6: Unknown result type (might be due to invalid IL or missing references) int num = prepareQueue.Dequeue(); if (!nodes.TryGetValue(num, out var value) || !value.IsAlive || !value.PrepareQueued) { return false; } if (!ShouldManageNode(value)) { RemoveNode(num, markNearby: false, mutateImmediately: true); return true; } value.PrepareQueued = false; try { Bounds queryBounds = value.QueryBounds; bool isPrepared = value.IsPrepared; RemoveColliderMappings(value); value.PrepareGeometry(cachedContactPadding); RegisterColliderMappings(value); spatialHash.AddOrUpdate(value.RuntimeId, value.QueryBounds); if (isPrepared) { MarkNearbyContactsDirty(queryBounds, value.RuntimeId); } MarkNearbyContactsDirty(value.QueryBounds, value.RuntimeId); QueueRefresh(value); return true; } catch (Exception exception) { HandleIntegrityException(num, exception); return true; } } private bool ProcessRefreshStep() { IntegrityNode value; if (currentRefreshNodeId == 0) { while (refreshQueue.Count > 0) { int num = refreshQueue.Dequeue(); if (!nodes.TryGetValue(num, out value) || !value.IsAlive || !value.RefreshQueued) { continue; } if (!ShouldManageNode(value)) { RemoveNode(num, markNearby: false, mutateImmediately: true); return true; } value.RefreshQueued = false; if (!value.IsPrepared || value.GeometryDirty) { QueuePrepare(value); return true; } if (!value.RequiresSupport) { pendingLinks.Clear(); currentPendingAnchor = AnchorKind.None; CommitCurrentRefresh(value); return true; } currentRefreshNodeId = num; currentRefreshColliderIndex = 0; currentPendingAnchor = AnchorKind.None; pendingLinks.Clear(); break; } } if (currentRefreshNodeId == 0) { return false; } if (!nodes.TryGetValue(currentRefreshNodeId, out value) || !value.IsAlive) { CancelCurrentRefresh(); return false; } if (!ShouldManageNode(value)) { int id = currentRefreshNodeId; CancelCurrentRefresh(); RemoveNode(id, markNearby: false, mutateImmediately: true); return true; } try { while (currentRefreshColliderIndex < value.Colliders.Length) { Collider val = value.Colliders[currentRefreshColliderIndex++]; if ((Object)(object)val == (Object)null || val.isTrigger || (Object)(object)val.attachedRigidbody != (Object)null) { continue; } if (ScanCollider(value, val)) { currentRefreshColliderIndex = value.Colliders.Length; } return true; } CommitCurrentRefresh(value); CancelCurrentRefresh(); return true; } catch (Exception exception) { int id2 = currentRefreshNodeId; CancelCurrentRefresh(); HandleIntegrityException(id2, exception); return true; } } private bool ScanCollider(IntegrityNode target, Collider ownerCollider) { int num = contactDetector.QueryCollider(ownerCollider, cachedContactPadding, cachedMaximumOverlapResults); try { for (int i = 0; i < num; i++) { Collider result = contactDetector.GetResult(i); if ((Object)(object)result == (Object)null || result.isTrigger || (Object)(object)result.attachedRigidbody != (Object)null || IsColliderOwnedByTarget(result, target.RuntimeId)) { continue; } if (contactDetector.IsTerrain(result)) { currentPendingAnchor = AnchorKind.Terrain; pendingLinks.Clear(); return true; } bool belongsToWearNTear; IntegrityNode integrityNode = ResolveColliderOwner(result, out belongsToWearNTear); if (integrityNode == null) { if (!belongsToWearNTear) { currentPendingAnchor = AnchorKind.StaticWorld; pendingLinks.Clear(); return true; } } else if (integrityNode.RuntimeId != target.RuntimeId && integrityNode.CanTransmitSupport) { StructuralContact contact = contactDetector.CreateDirectionalContact(target, integrityNode, result); AddOrMergePendingLink(target, integrityNode.RuntimeId, contact); } } } finally { contactDetector.ClearResults(num); } return false; } private bool IsColliderOwnedByTarget(Collider collider, int targetId) { if ((Object)(object)collider == (Object)null) { return false; } int instanceID = ((Object)collider).GetInstanceID(); ColliderOwnerCacheEntry value; return colliderOwners.TryGetValue(instanceID, out value) && (Object)(object)value.Collider == (Object)(object)collider && value.OwnerId == targetId; } private void AddOrMergePendingLink(IntegrityNode target, int sourceId, StructuralContact contact) { for (int i = 0; i < pendingLinks.Count; i++) { StructuralLink value = pendingLinks[i]; if (value.OtherId == sourceId) { value.Contact = value.Contact.MergeBest(contact, target.Material); pendingLinks[i] = value; return; } } pendingLinks.Add(new StructuralLink(sourceId, contact)); } private void CommitCurrentRefresh(IntegrityNode target) { if (currentPendingAnchor != AnchorKind.None) { pendingLinks.Clear(); } LinkCommitResult linkCommitResult = target.ReplaceLinks(pendingLinks, currentPendingAnchor, removedSourceBuffer, addedSourceBuffer); for (int i = 0; i < removedSourceBuffer.Count; i++) { if (nodes.TryGetValue(removedSourceBuffer[i], out var value)) { value.RemoveDependent(target.RuntimeId); } } for (int j = 0; j < addedSourceBuffer.Count; j++) { if (nodes.TryGetValue(addedSourceBuffer[j], out var value2)) { value2.AddDependent(target.RuntimeId); } } bool flag = QueueSolve(target); if (linkCommitResult != LinkCommitResult.None) { MutatedGraph(); } else if (flag) { DelaySolves(); } } private IntegrityNode ResolveColliderOwner(Collider collider, out bool belongsToWearNTear) { belongsToWearNTear = false; int instanceID = ((Object)collider).GetInstanceID(); if (staticColliderCache.TryGetValue(instanceID, out var value) && (Object)(object)value == (Object)(object)collider) { if (diagnosticsEnabled) { negativeColliderCacheHits++; } return null; } if (colliderOwners.TryGetValue(instanceID, out var value2) && (Object)(object)value2.Collider == (Object)(object)collider && nodes.TryGetValue(value2.OwnerId, out var value3) && value3.IsAlive) { belongsToWearNTear = true; return value3; } WearNTear componentInParent = ((Component)collider).GetComponentInParent(); if ((Object)(object)componentInParent == (Object)null) { if (staticColliderCache.Count < 32768) { staticColliderCache[instanceID] = collider; } if (diagnosticsEnabled) { negativeColliderCacheMisses++; } return null; } belongsToWearNTear = true; Register(componentInParent); int instanceID2 = ((Object)componentInParent).GetInstanceID(); if (!nodes.TryGetValue(instanceID2, out var value4)) { return null; } staticColliderCache.Remove(instanceID); colliderOwners[instanceID] = new ColliderOwnerCacheEntry { Collider = collider, OwnerId = instanceID2 }; return value4; } private bool ProcessSolveStep() { if (solvePhase == SolvePhase.None && !StartNextSolve()) { return false; } if (solveGraphRevision != graphRevision) { int key = solveSeedId; CancelActiveSolve(); if (nodes.TryGetValue(key, out var value)) { QueueSolve(value); } return true; } return solvePhase switch { SolvePhase.Collect => ProcessSolveCollect(), SolvePhase.Initialize => ProcessSolveInitialize(), SolvePhase.Relax => ProcessSolveRelax(), SolvePhase.Commit => ProcessSolveCommit(), _ => false, }; } private bool StartNextSolve() { while (solveQueue.Count > 0) { int num = solveQueue.Dequeue(); if (nodes.TryGetValue(num, out var value) && value.IsAlive && value.SolveQueued) { if (ShouldManageNode(value)) { value.SolveQueued = false; solveSeedId = num; solveGraphRevision = graphRevision; solvePhase = SolvePhase.Collect; solveIsland.Clear(); solveCollectQueue.Clear(); solveVisited.Clear(); relaxationQueue.Clear(); solveInitializeIndex = 0; solveCommitIndex = 0; solveVisited.Add(num); solveCollectQueue.Enqueue(num); return true; } RemoveNode(num, markNearby: false, mutateImmediately: true); } } return false; } private bool ProcessSolveCollect() { if (solveCollectQueue.Count == 0) { int num = cachedMaximumIslandNodes; if (solveIsland.Count > num) { log.LogWarning((object)("Integrity island " + solveIsland.Count + " exceeds configured limit " + num + ". Vanilla fallback remains active for this island.")); CancelActiveSolve(); return true; } solvePhase = SolvePhase.Initialize; return true; } int num2 = solveCollectQueue.Dequeue(); if (!nodes.TryGetValue(num2, out var value) || !value.IsAlive) { return true; } if (!ShouldManageNode(value)) { RemoveNode(num2, markNearby: false, mutateImmediately: true); CancelActiveSolve(); return true; } if (!value.IsPrepared || value.GeometryDirty || value.ContactsDirty || value.PrepareQueued || value.RefreshQueued) { QueueSolve(value); CancelActiveSolve(); return true; } solveIsland.Add(num2); int num3 = cachedMaximumIslandNodes; if (solveIsland.Count > num3) { log.LogWarning((object)("Integrity island exceeded configured limit " + num3 + " during collection. Vanilla fallback remains active.")); CancelActiveSolve(); return true; } for (int i = 0; i < value.Links.Count; i++) { int otherId = value.Links[i].OtherId; if (solveVisited.Add(otherId)) { solveCollectQueue.Enqueue(otherId); } } for (int j = 0; j < value.Dependents.Count; j++) { int item = value.Dependents[j]; if (solveVisited.Add(item)) { solveCollectQueue.Enqueue(item); } } return true; } private bool ProcessSolveInitialize() { if (solveInitializeIndex >= solveIsland.Count) { solvePhase = SolvePhase.Relax; return true; } IntegrityNode integrityNode = nodes[solveIsland[solveInitializeIndex++]]; integrityNode.IsReady = false; integrityNode.RelaxQueued = true; integrityNode.WorkingSupport = 0f; relaxationQueue.Enqueue(integrityNode.RuntimeId); return true; } private bool ProcessSolveRelax() { if (relaxationQueue.Count == 0) { solvePhase = SolvePhase.Commit; return true; } int key = relaxationQueue.Dequeue(); if (!nodes.TryGetValue(key, out var value) || !value.IsAlive) { return true; } value.RelaxQueued = false; float num = CalculateSupport(value); if (diagnosticsEnabled) { supportRelaxations++; } if (num <= value.WorkingSupport + 0.001f) { return true; } value.WorkingSupport = num; for (int i = 0; i < value.Dependents.Count; i++) { if (nodes.TryGetValue(value.Dependents[i], out var value2) && !value2.RelaxQueued) { value2.RelaxQueued = true; relaxationQueue.Enqueue(value2.RuntimeId); } } return true; } private float CalculateSupport(IntegrityNode target) { //IL_01c5: Unknown result type (might be due to invalid IL or missing references) //IL_01ca: Unknown result type (might be due to invalid IL or missing references) //IL_01ce: 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_0232: Unknown result type (might be due to invalid IL or missing references) //IL_0234: Unknown result type (might be due to invalid IL or missing references) if (!target.RequiresSupport || target.IsAnchor) { return target.Material.MaxSupport; } float num = 0f; for (int i = 0; i < target.Links.Count; i++) { StructuralLink structuralLink = target.Links[i]; if (nodes.TryGetValue(structuralLink.OtherId, out var value) && value.IsAlive && value.CanTransmitSupport) { float workingSupport = value.WorkingSupport; float num2 = structuralLink.Contact.DirectRetainedFraction(target.Material); num = Mathf.Max(num, workingSupport * num2); } } for (int j = 0; j < target.Links.Count; j++) { StructuralLink structuralLink2 = target.Links[j]; if (!nodes.TryGetValue(structuralLink2.OtherId, out var value2) || !value2.CanTransmitSupport || value2.WorkingSupport <= 0f) { continue; } for (int k = 0; k < structuralLink2.Contact.PointCount; k++) { SupportPointData point = GetPoint(structuralLink2.Contact, k); float num3 = value2.WorkingSupport * point.RetainedFraction(target.Material); for (int l = j; l < target.Links.Count; l++) { StructuralLink structuralLink3 = target.Links[l]; if (!nodes.TryGetValue(structuralLink3.OtherId, out var value3) || !value3.CanTransmitSupport || value3.WorkingSupport <= 0f) { continue; } int num4 = ((l == j) ? (k + 1) : 0); for (int m = num4; m < structuralLink3.Contact.PointCount; m++) { SupportPointData point2 = GetPoint(structuralLink3.Contact, m); Vector3 relativePoint = point.RelativePoint; Vector3 relativePoint2 = point2.RelativePoint; relativePoint.y = 0f; relativePoint2.y = 0f; float sqrMagnitude = ((Vector3)(ref relativePoint)).sqrMagnitude; float sqrMagnitude2 = ((Vector3)(ref relativePoint2)).sqrMagnitude; if (!(sqrMagnitude <= 1E-06f) && !(sqrMagnitude2 <= 1E-06f)) { float num5 = -0.17364818f * Mathf.Sqrt(sqrMagnitude * sqrMagnitude2); if (!(Vector3.Dot(relativePoint, relativePoint2) > num5)) { float num6 = value3.WorkingSupport * point2.RetainedFraction(target.Material); num = Mathf.Max(num, (num3 + num6) * 0.5f); } } } } } } return Mathf.Min(num, target.Material.MaxSupport); } private static SupportPointData GetPoint(StructuralContact contact, int index) { return (index == 0) ? contact.PointA : contact.PointB; } private bool ProcessSolveCommit() { if (solveCommitIndex >= solveIsland.Count) { if (diagnosticsEnabled) { solvedIslands++; solvedNodes += solveIsland.Count; } CancelActiveSolve(); return true; } IntegrityNode integrityNode = nodes[solveIsland[solveCommitIndex++]]; integrityNode.GraphSupport = Mathf.Clamp(integrityNode.WorkingSupport, 0f, Math.Max(0f, integrityNode.Material.MaxSupport)); integrityNode.GraphStable = !integrityNode.RequiresSupport || integrityNode.GraphSupport + 0.001f >= integrityNode.Material.MinSupport; integrityNode.SupportValid = IsFiniteSupport(integrityNode.GraphSupport, integrityNode.Material); integrityNode.IsReady = integrityNode.SupportValid; integrityNode.SolveQueued = false; integrityNode.RelaxQueued = false; integrityNode.OwnerSyncEstablished = false; integrityNode.NextOwnershipCheckTime = 0f; integrityNode.CacheReleaseEligibleTime = currentRealtimeSinceStartup + cachedVanillaCacheReleaseStableSeconds; QueueOwnerSync(integrityNode); return true; } private bool QueuePrepare(IntegrityNode node) { if (node == null || !node.IsAlive || node.PrepareQueued) { return false; } node.GeometryDirty = true; node.ContactsDirty = true; node.IsReady = false; node.SupportValid = false; node.PrepareQueued = true; node.VanillaCacheReleased = false; node.OwnerSyncEstablished = false; node.NextOwnershipCheckTime = 0f; prepareQueue.Enqueue(node.RuntimeId); DelaySolves(); return true; } private bool QueueRefresh(IntegrityNode node) { if (node == null || !node.IsAlive || node.RefreshQueued) { return false; } node.ContactsDirty = true; node.IsReady = false; node.SupportValid = false; node.RefreshQueued = true; node.VanillaCacheReleased = false; node.OwnerSyncEstablished = false; node.NextOwnershipCheckTime = 0f; refreshQueue.Enqueue(node.RuntimeId); DelaySolves(); return true; } private bool QueueSolve(IntegrityNode node) { if (node == null || !node.IsAlive) { return false; } node.IsReady = false; node.SupportValid = false; bool result = false; if (!node.SolveQueued) { node.SolveQueued = true; solveQueue.Enqueue(node.RuntimeId); result = true; } DelaySolves(); return result; } private void MarkNearbyContactsDirty(Bounds bounds, int excludedId) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) spatialHash.Query(bounds, queryBuffer); foreach (int item in queryBuffer) { if (item != excludedId && nodes.TryGetValue(item, out var value)) { QueueRefresh(value); } } } private void RemoveFromActiveNodeList(IntegrityNode node) { int num = node.ActiveListIndex; if (num < 0 || num >= activeNodeIds.Count || activeNodeIds[num] != node.RuntimeId) { num = activeNodeIds.IndexOf(node.RuntimeId); if (num < 0) { node.ActiveListIndex = -1; return; } } if (reconcilePhase == ReconcilePhase.PruneNodes && num < reconcileNodeIndex) { reconcileNodeIndex--; } if (ownerSweepActive && num < ownerSweepIndex) { ownerSweepIndex--; } if (cacheReleaseSweepActive && num < cacheReleaseSweepIndex) { cacheReleaseSweepIndex--; } int index = activeNodeIds.Count - 1; int num2 = activeNodeIds[index]; activeNodeIds[num] = num2; activeNodeIds.RemoveAt(index); node.ActiveListIndex = -1; if (num < activeNodeIds.Count && nodes.TryGetValue(num2, out var value)) { value.ActiveListIndex = num; } } private void RegisterColliderMappings(IntegrityNode node) { for (int i = 0; i < node.Colliders.Length; i++) { Collider val = node.Colliders[i]; if (!((Object)(object)val == (Object)null)) { colliderOwners[((Object)val).GetInstanceID()] = new ColliderOwnerCacheEntry { Collider = val, OwnerId = node.RuntimeId }; } } } private void RemoveColliderMappings(IntegrityNode node) { for (int i = 0; i < node.Colliders.Length; i++) { Collider val = node.Colliders[i]; if (!((Object)(object)val == (Object)null)) { int instanceID = ((Object)val).GetInstanceID(); if (colliderOwners.TryGetValue(instanceID, out var value) && (Object)(object)value.Collider == (Object)(object)val) { colliderOwners.Remove(instanceID); } } } } private void CancelCurrentRefresh() { currentRefreshNodeId = 0; currentRefreshColliderIndex = 0; currentPendingAnchor = AnchorKind.None; pendingLinks.Clear(); } private void CancelActiveSolve() { for (int i = 0; i < solveIsland.Count; i++) { if (nodes.TryGetValue(solveIsland[i], out var value)) { value.RelaxQueued = false; } } solvePhase = SolvePhase.None; solveSeedId = 0; solveGraphRevision = 0; solveInitializeIndex = 0; solveCommitIndex = 0; solveIsland.Clear(); solveCollectQueue.Clear(); solveVisited.Clear(); relaxationQueue.Clear(); } private void MutatedGraph() { graphRevision++; if (solvePhase != SolvePhase.None) { for (int i = 0; i < solveIsland.Count; i++) { if (nodes.TryGetValue(solveIsland[i], out var value)) { value.IsReady = false; } } } DelaySolves(); } private void DelaySolves() { solveNotBefore = currentRealtimeSinceStartup + cachedSolveDebounceSeconds; } private void RefreshRuntimeOptions(float realtimeSinceStartup) { currentRealtimeSinceStartup = realtimeSinceStartup; cachedWorkBudgetMilliseconds = Math.Max(0.1, Math.Min(25.0, config.WorkBudgetMilliseconds.Value)); cachedContactPadding = Mathf.Clamp(config.ContactPadding.Value, 0f, 1f); cachedMaximumOverlapResults = Math.Max(128, Math.Min(16384, config.MaximumOverlapResults.Value)); cachedMaximumIslandNodes = Math.Max(100, Math.Min(500000, config.MaximumIslandNodes.Value)); cachedSolveDebounceSeconds = (float)Mathf.Clamp(config.SolveDebounceMilliseconds.Value, 0, 5000) / 1000f; cachedReconcileSeconds = Mathf.Clamp(config.ActiveAreaReconcileSeconds.Value, 30f, 600f); if (dedicatedServer) { cachedReconcileSeconds = Math.Max(cachedReconcileSeconds, 120f); } cachedRequireInitialStableGraph = config.RequireInitialStableGraphBeforeReplace.Value; cachedReleaseVanillaCache = config.ReleaseVanillaSupportCache.Value; cachedApplySupportToZdo = config.ApplySupportToZdo.Value; cachedNetworkAbsoluteEpsilon = Mathf.Clamp(config.NetworkWriteEpsilon.Value, 0.0001f, 100f); cachedNetworkNormalizedEpsilon = Mathf.Clamp01(config.NetworkNormalizedWriteEpsilon.Value); cachedOwnershipRecheckSeconds = Mathf.Clamp(config.OwnershipRecheckSeconds.Value, 0.5f, 60f); cachedMaximumSupportZdoWritesPerFrame = Mathf.Clamp(config.MaximumSupportZdoWritesPerFrame.Value, 1, 4096); cachedMaximumPooledNodeLists = Mathf.Clamp(config.MaximumPooledNodeLists.Value, 0, 65536); cachedMaximumRetainedNodeListCapacity = Mathf.Clamp(config.MaximumRetainedNodeListCapacity.Value, 6, 512); cachedMaximumPooledSpatialCellLists = Mathf.Clamp(config.MaximumPooledSpatialCellLists.Value, 0, 65536); cachedVanillaCacheReleaseStableSeconds = Mathf.Clamp(config.VanillaCacheReleaseStableSeconds.Value, 5f, 600f); cachedVanillaCacheReleaseFallbackCooldownSeconds = Mathf.Clamp(config.VanillaCacheReleaseFallbackCooldownSeconds.Value, 5f, 600f); cachedMaximumVanillaCacheReleasesPerFrame = Mathf.Clamp(config.MaximumVanillaCacheReleasesPerFrame.Value, 1, 1024); linkListPool.SetLimits(cachedMaximumPooledNodeLists, cachedMaximumRetainedNodeListCapacity); dependentListPool.SetLimits(cachedMaximumPooledNodeLists, cachedMaximumRetainedNodeListCapacity); spatialHash.SetPoolLimit(cachedMaximumPooledSpatialCellLists); nextOwnershipSweepTime = Math.Min(nextOwnershipSweepTime, realtimeSinceStartup + cachedOwnershipRecheckSeconds); nextCacheReleaseSweepTime = Math.Min(nextCacheReleaseSweepTime, realtimeSinceStartup + 5f); runtimeOptionsDirty = false; } private void ResetZdoWriteBudgetIfNeeded() { int frameCount = Time.frameCount; if (frameCount != zdoWriteBudgetFrame) { zdoWriteBudgetFrame = frameCount; zdoWritesThisFrame = 0; } } private float GetSpatialCellSize() { return Mathf.Clamp(config.SpatialCellSize.Value, 0.5f, 64f); } private RuntimeStats GetStats() { RuntimeStats result = new RuntimeStats { Nodes = nodes.Count, PrepareQueue = prepareQueue.Count, RefreshQueue = refreshQueue.Count + ((currentRefreshNodeId != 0) ? 1 : 0), SolveQueue = solveQueue.Count + ((solvePhase != SolvePhase.None) ? 1 : 0), SolvePhase = solvePhase.ToString(), ReconcilePhase = reconcilePhase.ToString(), ReconcileScanRemaining = ((reconcilePhase == ReconcilePhase.ScanInstances && reconcileInstances != null) ? Math.Max(0, reconcileInstances.Count - reconcileInstanceIndex) : 0), ReconcilePruneRemaining = ((reconcilePhase == ReconcilePhase.PruneNodes) ? Math.Max(0, activeNodeIds.Count - reconcileNodeIndex) : 0), Reconciliations = completedReconciliations, ZoneChangeReconciliations = zoneChangeReconciliations, PeriodicReconciliations = periodicReconciliations, RequestedReconciliations = requestedReconciliations, LastReconcileReason = lastCompletedReconcileReason.ToString(), ReconciledPrunedNodes = reconciledPrunedNodes, ReplacementArmed = replacementArmed, ReplacementFaulted = replacementFaulted, ReplacementFaultReason = replacementFaultReason, ReplacementRequests = replacementRequests, ReplacementHits = replacementHits, ReplacementMissNotArmed = replacementMissNotArmed, ReplacementMissNotReady = replacementMissNotReady, ReplacementMissOutsideArea = replacementMissOutsideArea, ReplacementMissFaulted = replacementMissFaulted, ReplacementInvalidSupport = replacementInvalidSupport, ReplacementExceptions = replacementExceptions, ReplacementCircuitTrips = replacementCircuitTrips, WindowReplacementRequests = windowReplacementRequests, WindowReplacementHits = windowReplacementHits, WindowReplacementMissNotArmed = windowReplacementMissNotArmed, WindowReplacementMissNotReady = windowReplacementMissNotReady, WindowReplacementMissOutsideArea = windowReplacementMissOutsideArea, WindowReplacementMissFaulted = windowReplacementMissFaulted, WindowReplacementInvalidSupport = windowReplacementInvalidSupport, WindowReplacementExceptions = windowReplacementExceptions, WindowReplacementCircuitTrips = windowReplacementCircuitTrips, SolvedIslands = solvedIslands, SolvedNodes = solvedNodes, SupportRelaxations = supportRelaxations, ZdoWrites = zdoWrites, ZdoWritesSkippedEpsilon = zdoWritesSkippedEpsilon, ZdoWritesSkippedNotOwner = zdoWritesSkippedNotOwner, ZdoWritesDeferredBudget = zdoWritesDeferredBudget, VanillaCachesReleased = vanillaCachesReleased, NodeAllocations = nodeAllocations, NodeRemovals = nodeRemovals, PooledLinkLists = linkListPool.Count, PooledDependentLists = dependentListPool.Count, AllocatedNodeLists = linkListPool.Allocated + dependentListPool.Allocated, DiscardedNodeLists = linkListPool.Discarded + dependentListPool.Discarded, SpatialCells = spatialHash.CellCount, SpatialPooledLists = spatialHash.PooledListCount, SpatialAllocatedLists = spatialHash.AllocatedListCount, SpatialDiscardedLists = spatialHash.DiscardedListCount, ColliderOwnerCacheEntries = colliderOwners.Count, StaticColliderCacheEntries = staticColliderCache.Count, NegativeColliderCacheHits = negativeColliderCacheHits, NegativeColliderCacheMisses = negativeColliderCacheMisses, OverlapCapacity = contactDetector.OverlapCapacity, OverlapRetries = contactDetector.OverlapRetries, OverlapOverflows = contactDetector.OverlapOverflows, LastWorkMilliseconds = lastWorkMilliseconds, MaximumWorkMilliseconds = maximumWorkMilliseconds, WindowMaximumWorkMilliseconds = windowMaximumWorkMilliseconds, WindowMaxPrepareMilliseconds = windowMaxPrepareMilliseconds, WindowMaxRefreshMilliseconds = windowMaxRefreshMilliseconds, WindowMaxSolveMilliseconds = windowMaxSolveMilliseconds, WindowMaxReconcileMilliseconds = windowMaxReconcileMilliseconds, WindowMaxMaintenanceMilliseconds = windowMaxMaintenanceMilliseconds, LifetimeMaxPrepareMilliseconds = lifetimeMaxPrepareMilliseconds, LifetimeMaxRefreshMilliseconds = lifetimeMaxRefreshMilliseconds, LifetimeMaxSolveMilliseconds = lifetimeMaxSolveMilliseconds, LifetimeMaxReconcileMilliseconds = lifetimeMaxReconcileMilliseconds, LifetimeMaxMaintenanceMilliseconds = lifetimeMaxMaintenanceMilliseconds }; if (Launch.RuntimeMode == IntegrityMode.Observe) { result.Benchmark = benchmark.SnapshotAndResetWindow(Mathf.Clamp(config.TopDifferencesPerReport.Value, 0, 20)); } if (profilingEnabled) { result.Profiler = profiler.SnapshotAndResetWindow(); } long num = (long)nodes.Count * 256L; num += (long)activeNodeIds.Capacity * 4L; num += (long)nodes.Count * 40L; num += (long)colliderOwners.Count * 40L; num += staticColliderCache.Count * (40L + (long)IntPtr.Size); num += spatialHash.EstimateManagedBytes(); foreach (IntegrityNode value in nodes.Values) { if (value.IsPrepared) { result.PreparedNodes++; } if (value.IsReady) { result.ReadyNodes++; if (value.RequiresSupport) { result.ComparableNodes++; } } result.Edges += value.Links.Count; num += 96; num += (long)value.Links.Capacity * 56L; num += (long)value.Dependents.Capacity * 4L; num += value.Colliders.Length * IntPtr.Size; if (value.Anchor == AnchorKind.Terrain) { result.TerrainAnchors++; } else if (value.Anchor == AnchorKind.StaticWorld) { result.StaticAnchors++; } } result.EstimatedGraphBytes = num; return result; } private static bool IsFiniteSupport(float support, MaterialProfile material) { if (float.IsNaN(support) || float.IsInfinity(support) || support < 0f) { return false; } float num = Math.Max(0f, material.MaxSupport); return support <= num + 0.1f; } private static float NormalizeSupport(float support, MaterialProfile material) { float num = material.MaxSupport - material.MinSupport; if (num <= 0.0001f) { return (support >= material.MinSupport) ? 1f : 0f; } return Mathf.Clamp01((support - material.MinSupport) / num); } private void HandleIntegrityException(int id, Exception exception) { string text = "Integrity processing failed for node " + id + "."; if (Launch.RuntimeMode == IntegrityMode.Replace && config.FallbackToVanillaOnError.Value) { DisableReplacementForSession(text, exception); } else { log.LogError((object)(text + " Exception: " + exception)); } } } internal static class MaterialProfiles { private static readonly Dictionary Profiles = new Dictionary(); private static BetterBuildConfig config; internal static void Initialize(BetterBuildConfig settings) { config = settings; Profiles.Clear(); } internal static void Invalidate() { Profiles.Clear(); } internal static MaterialProfile Get(WearNTear instance) { return Get(instance, WearNTearAccess.GetNView(instance)); } internal static MaterialProfile Get(WearNTear instance, ZNetView nview) { //IL_0002: 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_000a: 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) MaterialType materialType = WearNTearAccess.GetMaterialType(instance); long key = CreateProfileKey(instance, nview, materialType); if (!Profiles.TryGetValue(key, out var value)) { if (!WearNTearAccess.TryReadVanillaMaterialProfile(instance, out var profile)) { profile = GetKnownFallback(materialType); } value = ApplyPreset(profile); Profiles[key] = value; } return value; } private static long CreateProfileKey(WearNTear instance, ZNetView nview, MaterialType type) { //IL_005d: Unknown result type (might be due to invalid IL or missing references) int num = 0; ZDO val = null; if ((Object)(object)nview != (Object)null && nview.IsValid()) { val = nview.GetZDO(); } if (val != null) { num = val.GetPrefab(); } else if ((Object)(object)instance != (Object)null) { num = ((Object)((Component)instance).gameObject).name.GetHashCode(); } return ((long)num << 32) ^ (long)(ulong)type; } private static MaterialProfile ApplyPreset(MaterialProfile source) { float num = 1f; float num2 = 1f; float num3 = 1f; float num4 = 1f; switch ((config != null) ? config.MaterialPreset.Value : MaterialBalancePreset.VanillaCompatible) { case MaterialBalancePreset.Forgiving: num = 1.05f; num2 = 0.9f; num3 = 0.9f; num4 = 0.92f; break; case MaterialBalancePreset.Generous: num = 1.1f; num2 = 0.8f; num3 = 0.75f; num4 = 0.82f; break; case MaterialBalancePreset.Custom: num = ClampMultiplier(config.CustomMaxSupportMultiplier.Value); num2 = ClampMultiplier(config.CustomMinSupportMultiplier.Value); num3 = ClampMultiplier(config.CustomHorizontalLossMultiplier.Value); num4 = ClampMultiplier(config.CustomVerticalLossMultiplier.Value); break; } return new MaterialProfile(Mathf.Max(0f, source.MaxSupport * num), Mathf.Max(0f, source.MinSupport * num2), Mathf.Max(0f, source.HorizontalLossPerMeter * num3), Mathf.Max(0f, source.VerticalLossPerMeter * num4)); } private static float ClampMultiplier(float value) { return Mathf.Clamp(value, 0.05f, 10f); } private static MaterialProfile GetKnownFallback(MaterialType type) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_0004: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Expected I4, but got Unknown return (int)type switch { 0 => new MaterialProfile(100f, 10f, 0.2f, 0.125f), 1 => new MaterialProfile(1000f, 100f, 1f, 0.125f), 2 => new MaterialProfile(1500f, 20f, 1f / 13f, 1f / 13f), 3 => new MaterialProfile(140f, 10f, 1f / 6f, 0.1f), 4 => new MaterialProfile(1500f, 100f, 0.5f, 0.125f), 5 => new MaterialProfile(2000f, 100f, 1f / 3f, 0.1f), 6 => new MaterialProfile(5000f, 100f, 0.25f, 1f / 15f), _ => new MaterialProfile(100f, 10f, 0.2f, 0.125f), }; } } internal sealed class PerformanceProfiler { private sealed class TimingAccumulator { private long lifetimeCalls; private long lifetimeTicks; private long lifetimeMaximumTicks; private long windowCalls; private long windowTicks; private long windowMaximumTicks; internal void Add(long ticks) { lifetimeCalls++; lifetimeTicks += ticks; if (ticks > lifetimeMaximumTicks) { lifetimeMaximumTicks = ticks; } windowCalls++; windowTicks += ticks; if (ticks > windowMaximumTicks) { windowMaximumTicks = ticks; } } internal TimingSnapshot Snapshot() { return new TimingSnapshot(lifetimeCalls, TicksToMilliseconds(lifetimeTicks), TicksToMilliseconds(lifetimeMaximumTicks), windowCalls, TicksToMilliseconds(windowTicks), TicksToMilliseconds(windowMaximumTicks)); } internal void ResetWindow() { windowCalls = 0L; windowTicks = 0L; windowMaximumTicks = 0L; } internal void Reset() { lifetimeCalls = 0L; lifetimeTicks = 0L; lifetimeMaximumTicks = 0L; ResetWindow(); } private static double TicksToMilliseconds(long ticks) { return (ticks <= 0) ? 0.0 : ((double)ticks * 1000.0 / (double)Stopwatch.Frequency); } } private readonly TimingAccumulator replacementLookup = new TimingAccumulator(); private readonly TimingAccumulator vanillaSupport = new TimingAccumulator(); private readonly TimingAccumulator wearUpdater = new TimingAccumulator(); private int lastGc0; private int lastGc1; private int lastGc2; private bool gcBaselineReady; internal void Reset() { replacementLookup.Reset(); vanillaSupport.Reset(); wearUpdater.Reset(); gcBaselineReady = false; lastGc0 = 0; lastGc1 = 0; lastGc2 = 0; } internal void RecordSupportCall(bool vanillaPath, long elapsedTicks) { if (elapsedTicks >= 0) { if (vanillaPath) { vanillaSupport.Add(elapsedTicks); } else { replacementLookup.Add(elapsedTicks); } } } internal void RecordWearUpdater(long elapsedTicks) { if (elapsedTicks >= 0) { wearUpdater.Add(elapsedTicks); } } internal ProfilerSnapshot SnapshotAndResetWindow() { long num = 0L; int gc = 0; int gc2 = 0; int gc3 = 0; try { num = GC.GetTotalMemory(forceFullCollection: false); int num2 = GC.CollectionCount(0); int num3 = GC.CollectionCount(1); int num4 = GC.CollectionCount(2); if (gcBaselineReady) { gc = Math.Max(0, num2 - lastGc0); gc2 = Math.Max(0, num3 - lastGc1); gc3 = Math.Max(0, num4 - lastGc2); } lastGc0 = num2; lastGc1 = num3; lastGc2 = num4; gcBaselineReady = true; } catch { num = 0L; } ProfilerSnapshot result = new ProfilerSnapshot(replacementLookup.Snapshot(), vanillaSupport.Snapshot(), wearUpdater.Snapshot(), num, gc, gc2, gc3); replacementLookup.ResetWindow(); vanillaSupport.ResetWindow(); wearUpdater.ResetWindow(); return result; } } internal struct TimingSnapshot { internal long LifetimeCalls; internal double LifetimeMilliseconds; internal double LifetimeMaximumMilliseconds; internal long WindowCalls; internal double WindowMilliseconds; internal double WindowMaximumMilliseconds; internal double WindowAverageMicroseconds => (WindowCalls <= 0) ? 0.0 : (WindowMilliseconds * 1000.0 / (double)WindowCalls); internal double LifetimeAverageMicroseconds => (LifetimeCalls <= 0) ? 0.0 : (LifetimeMilliseconds * 1000.0 / (double)LifetimeCalls); internal TimingSnapshot(long lifetimeCalls, double lifetimeMilliseconds, double lifetimeMaximumMilliseconds, long windowCalls, double windowMilliseconds, double windowMaximumMilliseconds) { LifetimeCalls = lifetimeCalls; LifetimeMilliseconds = lifetimeMilliseconds; LifetimeMaximumMilliseconds = lifetimeMaximumMilliseconds; WindowCalls = windowCalls; WindowMilliseconds = windowMilliseconds; WindowMaximumMilliseconds = windowMaximumMilliseconds; } } internal struct ProfilerSnapshot { internal TimingSnapshot ReplacementLookup; internal TimingSnapshot VanillaSupport; internal TimingSnapshot WearUpdater; internal long ManagedBytes; internal int Gen0Collections; internal int Gen1Collections; internal int Gen2Collections; internal ProfilerSnapshot(TimingSnapshot replacementLookup, TimingSnapshot vanillaSupport, TimingSnapshot wearUpdater, long managedBytes, int gc0, int gc1, int gc2) { ReplacementLookup = replacementLookup; VanillaSupport = vanillaSupport; WearUpdater = wearUpdater; ManagedBytes = managedBytes; Gen0Collections = gc0; Gen1Collections = gc1; Gen2Collections = gc2; } } internal struct RuntimeStats { internal int Nodes; internal int PreparedNodes; internal int ReadyNodes; internal int ComparableNodes; internal int Edges; internal int TerrainAnchors; internal int StaticAnchors; internal int PrepareQueue; internal int RefreshQueue; internal int SolveQueue; internal string SolvePhase; internal string ReconcilePhase; internal string LastReconcileReason; internal int ReconcileScanRemaining; internal int ReconcilePruneRemaining; internal long Reconciliations; internal long ZoneChangeReconciliations; internal long PeriodicReconciliations; internal long RequestedReconciliations; internal long ReconciledPrunedNodes; internal bool ReplacementArmed; internal bool ReplacementFaulted; internal string ReplacementFaultReason; internal long ReplacementRequests; internal long ReplacementHits; internal long ReplacementMissNotArmed; internal long ReplacementMissNotReady; internal long ReplacementMissOutsideArea; internal long ReplacementMissFaulted; internal long ReplacementInvalidSupport; internal long ReplacementExceptions; internal long ReplacementCircuitTrips; internal long WindowReplacementRequests; internal long WindowReplacementHits; internal long WindowReplacementMissNotArmed; internal long WindowReplacementMissNotReady; internal long WindowReplacementMissOutsideArea; internal long WindowReplacementMissFaulted; internal long WindowReplacementInvalidSupport; internal long WindowReplacementExceptions; internal long WindowReplacementCircuitTrips; internal long SolvedIslands; internal long SolvedNodes; internal long SupportRelaxations; internal long ZdoWrites; internal long ZdoWritesSkippedEpsilon; internal long ZdoWritesSkippedNotOwner; internal long ZdoWritesDeferredBudget; internal long VanillaCachesReleased; internal long NodeAllocations; internal long NodeRemovals; internal int PooledLinkLists; internal int PooledDependentLists; internal long AllocatedNodeLists; internal long DiscardedNodeLists; internal int SpatialCells; internal int SpatialPooledLists; internal long SpatialAllocatedLists; internal long SpatialDiscardedLists; internal int ColliderOwnerCacheEntries; internal int StaticColliderCacheEntries; internal long NegativeColliderCacheHits; internal long NegativeColliderCacheMisses; internal int OverlapCapacity; internal long OverlapRetries; internal long OverlapOverflows; internal long EstimatedGraphBytes; internal double LastWorkMilliseconds; internal double MaximumWorkMilliseconds; internal double WindowMaximumWorkMilliseconds; internal double WindowMaxPrepareMilliseconds; internal double WindowMaxRefreshMilliseconds; internal double WindowMaxSolveMilliseconds; internal double WindowMaxReconcileMilliseconds; internal double WindowMaxMaintenanceMilliseconds; internal double LifetimeMaxPrepareMilliseconds; internal double LifetimeMaxRefreshMilliseconds; internal double LifetimeMaxSolveMilliseconds; internal double LifetimeMaxReconcileMilliseconds; internal double LifetimeMaxMaintenanceMilliseconds; internal BenchmarkSnapshot Benchmark; internal ProfilerSnapshot Profiler; } internal sealed class SpatialHash { private struct CellRange : IEquatable { internal readonly int MinX; internal readonly int MinY; internal readonly int MinZ; internal readonly int MaxX; internal readonly int MaxY; internal readonly int MaxZ; internal CellRange(int minX, int minY, int minZ, int maxX, int maxY, int maxZ) { MinX = minX; MinY = minY; MinZ = minZ; MaxX = maxX; MaxY = maxY; MaxZ = maxZ; } public bool Equals(CellRange other) { return MinX == other.MinX && MinY == other.MinY && MinZ == other.MinZ && MaxX == other.MaxX && MaxY == other.MaxY && MaxZ == other.MaxZ; } } private struct CellKey : IEquatable { internal readonly int X; internal readonly int Y; internal readonly int Z; internal CellKey(int x, int y, int z) { X = x; Y = y; Z = z; } public bool Equals(CellKey other) { return X == other.X && Y == other.Y && Z == other.Z; } public override bool Equals(object obj) { return obj is CellKey && Equals((CellKey)obj); } public override int GetHashCode() { int x = X; x = (x * 397) ^ Y; return (x * 397) ^ Z; } } private readonly Dictionary> cells = new Dictionary>(); private readonly Dictionary nodeRanges = new Dictionary(); private readonly Stack> listPool = new Stack>(); private long allocatedLists; private long discardedLists; private int maximumPooledLists = 2048; private float cellSize; internal int CellCount => cells.Count; internal int NodeCount => nodeRanges.Count; internal int PooledListCount => listPool.Count; internal long AllocatedListCount => allocatedLists; internal long DiscardedListCount => discardedLists; internal SpatialHash(float initialCellSize) { cellSize = Math.Max(0.5f, initialCellSize); } internal long EstimateManagedBytes() { long num = 0L; foreach (List value in cells.Values) { num += 32 + (long)value.Capacity * 4L; } num += (long)cells.Count * 40L; num += (long)nodeRanges.Count * 40L; return num + (long)listPool.Count * 8L; } internal void SetCellSize(float value) { cellSize = Math.Max(0.5f, value); } internal void SetPoolLimit(int value) { maximumPooledLists = Math.Max(0, value); TrimPool(maximumPooledLists); } internal void TrimPool(int targetCount) { int num = Math.Max(0, Math.Min(targetCount, maximumPooledLists)); while (listPool.Count > num) { listPool.Pop(); discardedLists++; } } internal void Clear() { foreach (List value in cells.Values) { ReturnList(value); } cells.Clear(); nodeRanges.Clear(); } internal void AddOrUpdate(int nodeId, Bounds bounds) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) CellRange cellRange = ToRange(bounds); if (nodeRanges.TryGetValue(nodeId, out var value)) { if (value.Equals(cellRange)) { return; } RemoveFromRange(nodeId, value); } nodeRanges[nodeId] = cellRange; AddToRange(nodeId, cellRange); } internal void Remove(int nodeId) { if (nodeRanges.TryGetValue(nodeId, out var value)) { RemoveFromRange(nodeId, value); nodeRanges.Remove(nodeId); } } internal void Query(Bounds bounds, HashSet results) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) results.Clear(); CellRange cellRange = ToRange(bounds); for (int i = cellRange.MinX; i <= cellRange.MaxX; i++) { for (int j = cellRange.MinY; j <= cellRange.MaxY; j++) { for (int k = cellRange.MinZ; k <= cellRange.MaxZ; k++) { if (cells.TryGetValue(new CellKey(i, j, k), out var value)) { for (int l = 0; l < value.Count; l++) { results.Add(value[l]); } } } } } } private void AddToRange(int nodeId, CellRange range) { for (int i = range.MinX; i <= range.MaxX; i++) { for (int j = range.MinY; j <= range.MaxY; j++) { for (int k = range.MinZ; k <= range.MaxZ; k++) { CellKey key = new CellKey(i, j, k); if (!cells.TryGetValue(key, out var value)) { value = RentList(); cells.Add(key, value); } value.Add(nodeId); } } } } private void RemoveFromRange(int nodeId, CellRange range) { for (int i = range.MinX; i <= range.MaxX; i++) { for (int j = range.MinY; j <= range.MaxY; j++) { for (int k = range.MinZ; k <= range.MaxZ; k++) { CellKey key = new CellKey(i, j, k); if (!cells.TryGetValue(key, out var value)) { continue; } for (int num = value.Count - 1; num >= 0; num--) { if (value[num] == nodeId) { int index = value.Count - 1; value[num] = value[index]; value.RemoveAt(index); break; } } if (value.Count == 0) { cells.Remove(key); ReturnList(value); } } } } } private List RentList() { if (listPool.Count > 0) { return listPool.Pop(); } allocatedLists++; return new List(4); } private void ReturnList(List list) { list.Clear(); if (list.Capacity > 64) { list.Capacity = 16; } if (listPool.Count >= maximumPooledLists) { discardedLists++; } else { listPool.Push(list); } } private CellRange ToRange(Bounds bounds) { //IL_0004: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) CellKey cellKey = ToCell(((Bounds)(ref bounds)).min); CellKey cellKey2 = ToCell(((Bounds)(ref bounds)).max); return new CellRange(cellKey.X, cellKey.Y, cellKey.Z, cellKey2.X, cellKey2.Y, cellKey2.Z); } private CellKey ToCell(Vector3 position) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) return new CellKey(Mathf.FloorToInt(position.x / cellSize), Mathf.FloorToInt(position.y / cellSize), Mathf.FloorToInt(position.z / cellSize)); } } internal struct SupportPointData { internal float X; internal float Y; internal float Z; internal float Distance; internal Vector3 RelativePoint => new Vector3(X, Y, Z); internal bool IsValid => Distance > 0f; internal SupportPointData(Vector3 relativePoint, float distance) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Unknown result type (might be due to invalid IL or missing references) X = relativePoint.x; Y = relativePoint.y; Z = relativePoint.z; Distance = Mathf.Max(0.1f, distance); } internal float RetainedFraction(MaterialProfile material) { return Mathf.Max(0f, 1f - material.VerticalLossPerMeter * Distance); } internal bool ApproximatelyEquals(SupportPointData other) { return Mathf.Abs(X - other.X) <= 0.002f && Mathf.Abs(Y - other.Y) <= 0.002f && Mathf.Abs(Z - other.Z) <= 0.002f && Mathf.Abs(Distance - other.Distance) <= 0.002f; } } internal struct StructuralContact { internal float DirectDistance; internal float DirectVerticalBlend; internal byte PointCount; internal SupportPointData PointA; internal SupportPointData PointB; internal StructuralContact(float directDistance, float directVerticalBlend, bool hasSupportPoint, SupportPointData supportPoint) { DirectDistance = Mathf.Max(0.1f, directDistance); DirectVerticalBlend = Mathf.Clamp01(directVerticalBlend); PointCount = (byte)(hasSupportPoint ? 1 : 0); PointA = supportPoint; PointB = default(SupportPointData); } internal float DirectRetainedFraction(MaterialProfile material) { float num = Mathf.Lerp(material.HorizontalLossPerMeter, material.VerticalLossPerMeter, DirectVerticalBlend); return Mathf.Max(0f, 1f - num * DirectDistance); } internal StructuralContact MergeBest(StructuralContact other, MaterialProfile targetMaterial) { StructuralContact result = this; if (other.DirectRetainedFraction(targetMaterial) > DirectRetainedFraction(targetMaterial) + 0.0001f) { result.DirectDistance = other.DirectDistance; result.DirectVerticalBlend = other.DirectVerticalBlend; } if (other.PointCount > 0) { result.AddPoint(other.PointA, targetMaterial); } if (other.PointCount > 1) { result.AddPoint(other.PointB, targetMaterial); } return result; } private void AddPoint(SupportPointData candidate, MaterialProfile material) { if (!candidate.IsValid) { return; } if (PointCount == 0) { PointA = candidate; PointCount = 1; return; } if (PointA.ApproximatelyEquals(candidate)) { if (candidate.RetainedFraction(material) > PointA.RetainedFraction(material)) { PointA = candidate; } return; } if (PointCount == 1) { PointB = candidate; PointCount = 2; return; } if (PointB.ApproximatelyEquals(candidate)) { if (candidate.RetainedFraction(material) > PointB.RetainedFraction(material)) { PointB = candidate; } return; } float num = SeparationScore(PointA, PointB, material); float num2 = SeparationScore(candidate, PointB, material); float num3 = SeparationScore(PointA, candidate, material); if (num2 > num && num2 >= num3) { PointA = candidate; } else if (num3 > num) { PointB = candidate; } } private static float SeparationScore(SupportPointData first, SupportPointData second, MaterialProfile material) { //IL_0003: 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_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) Vector3 relativePoint = first.RelativePoint; Vector3 relativePoint2 = second.RelativePoint; relativePoint.y = 0f; relativePoint2.y = 0f; float num = ((((Vector3)(ref relativePoint)).sqrMagnitude <= 1E-06f || ((Vector3)(ref relativePoint2)).sqrMagnitude <= 1E-06f) ? 0f : Vector3.Angle(relativePoint, relativePoint2)); float num2 = first.RetainedFraction(material) + second.RetainedFraction(material); return num * 10f + num2; } internal bool ApproximatelyEquals(StructuralContact other) { if (Mathf.Abs(DirectDistance - other.DirectDistance) > 0.002f || Mathf.Abs(DirectVerticalBlend - other.DirectVerticalBlend) > 0.002f || PointCount != other.PointCount) { return false; } if (PointCount > 0 && !PointA.ApproximatelyEquals(other.PointA)) { return false; } return PointCount <= 1 || PointB.ApproximatelyEquals(other.PointB); } } internal struct StructuralLink { internal int OtherId; internal StructuralContact Contact; internal StructuralLink(int otherId, StructuralContact contact) { OtherId = otherId; Contact = contact; } } internal enum ZdoWriteResult : byte { Written, SkippedDisabled, SkippedNotOwner, SkippedEpsilon, SkippedBudget, Failed } internal static class WearNTearAccess { private static readonly Collider[] EmptyColliders = (Collider[])(object)new Collider[0]; private static FieldInfo supportField; private static FieldInfo nviewField; private static FieldInfo collidersField; private static FieldInfo boundsField; private static FieldInfo supportCollidersField; private static FieldInfo supportPositionsField; private static FieldInfo supportValuesField; private static MethodInfo setupCollidersMethod; private static MethodInfo materialPropertiesMethod; private static int zdoSupportHash; private static bool hasZdoSupportHash; private static ManualLogSource log; private static BetterBuildConfig config; private static bool initialized; private static bool warnedZdo; [ThreadStatic] private static object[] materialArguments; internal static void Initialize(ManualLogSource logger, BetterBuildConfig settings) { if (initialized) { return; } log = logger; config = settings; supportField = AccessTools.Field(typeof(WearNTear), "m_support"); nviewField = AccessTools.Field(typeof(WearNTear), "m_nview"); collidersField = AccessTools.Field(typeof(WearNTear), "m_colliders"); boundsField = AccessTools.Field(typeof(WearNTear), "m_bounds"); supportCollidersField = AccessTools.Field(typeof(WearNTear), "m_supportColliders"); supportPositionsField = AccessTools.Field(typeof(WearNTear), "m_supportPositions"); supportValuesField = AccessTools.Field(typeof(WearNTear), "m_supportValue"); setupCollidersMethod = AccessTools.Method(typeof(WearNTear), "SetupColliders", (Type[])null, (Type[])null); materialPropertiesMethod = AccessTools.Method(typeof(WearNTear), "GetMaterialProperties", (Type[])null, (Type[])null); Type type = typeof(WearNTear).Assembly.GetType("ZDOVars"); if (type != null) { FieldInfo fieldInfo = AccessTools.Field(type, "s_support"); if (fieldInfo != null) { zdoSupportHash = (int)fieldInfo.GetValue(null); hasZdoSupportHash = true; } } if (setupCollidersMethod == null) { throw new MissingMethodException("WearNTear.SetupColliders was not found."); } if (materialPropertiesMethod == null) { throw new MissingMethodException("WearNTear.GetMaterialProperties was not found."); } initialized = true; } internal static bool IsRuntimeInstance(WearNTear instance) { ZNetView nview; return TryGetRuntimeNView(instance, out nview); } internal static bool TryGetRuntimeNView(WearNTear instance, out ZNetView nview) { nview = null; if ((Object)(object)instance == (Object)null || (Object)(object)((Component)instance).gameObject == (Object)null) { return false; } nview = GetNView(instance); return (Object)(object)nview != (Object)null && nview.GetZDO() != null; } internal static ZNetView GetNView(WearNTear instance) { if ((Object)(object)instance == (Object)null) { return null; } ZNetView val = (ZNetView)((nviewField == null) ? null : /*isinst with value type is only supported in some contexts*/); return ((Object)(object)val != (Object)null) ? val : ((Component)instance).GetComponent(); } internal static Collider[] GetOrCreateStructuralColliders(WearNTear instance) { if ((Object)(object)instance == (Object)null) { return EmptyColliders; } Collider[] array = ((collidersField == null) ? null : (collidersField.GetValue(instance) as Collider[])); if (array == null) { setupCollidersMethod.Invoke(instance, null); array = ((collidersField == null) ? null : (collidersField.GetValue(instance) as Collider[])); } return array ?? EmptyColliders; } internal static bool CanTransmitSupport(WearNTear instance) { return (Object)(object)instance != (Object)null && instance.m_supports; } internal static bool RequiresSupport(WearNTear instance) { return (Object)(object)instance != (Object)null && instance.m_noSupportWear; } internal static bool ForceCorrectComCalculation(WearNTear instance) { return (Object)(object)instance != (Object)null && instance.m_forceCorrectCOMCalculation; } internal static MaterialType GetMaterialType(WearNTear instance) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) return (MaterialType)((!((Object)(object)instance == (Object)null)) ? ((int)instance.m_materialType) : 0); } internal static Vector3 GetCenterOfMass(WearNTear instance) { //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0026: 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_0012: 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) if ((Object)(object)instance == (Object)null) { return Vector3.zero; } return GetCenterOfMass(instance, ((Component)instance).transform.position); } internal static Vector3 GetCenterOfMass(WearNTear instance, Vector3 originPosition) { //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0031: 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_0012: 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 ((Object)(object)instance == (Object)null) { return Vector3.zero; } return originPosition + ((Component)instance).transform.rotation * instance.m_comOffset; } internal static bool TryReadVanillaMaterialProfile(WearNTear instance, out MaterialProfile profile) { profile = default(MaterialProfile); if ((Object)(object)instance == (Object)null || materialPropertiesMethod == null) { return false; } try { object[] array = materialArguments; if (array == null) { array = (materialArguments = new object[4]); } array[0] = 0f; array[1] = 0f; array[2] = 0f; array[3] = 0f; materialPropertiesMethod.Invoke(instance, array); profile = new MaterialProfile((float)array[0], (float)array[1], (float)array[2], (float)array[3]); return profile.MaxSupport > 0f; } catch (Exception ex) { if (log != null && config != null && config.VerboseLogging.Value) { log.LogWarning((object)("Could not read vanilla material properties for " + ((Object)instance).name + ": " + ex.Message)); } return false; } } internal static float ReadSupport(WearNTear instance) { if ((Object)(object)instance == (Object)null || supportField == null) { return 0f; } object value = supportField.GetValue(instance); return (value is float) ? ((float)value) : 0f; } internal static void WriteSupportField(WearNTear instance, float support) { if ((Object)(object)instance != (Object)null && supportField != null) { supportField.SetValue(instance, support); } } internal static ZdoWriteResult WriteSupportToZdo(WearNTear instance, ZNetView nview, float support, MaterialProfile material, float absoluteEpsilon, float normalizedEpsilon, bool force, bool allowNonCriticalWrite) { if ((Object)(object)instance == (Object)null) { return ZdoWriteResult.SkippedDisabled; } try { if ((Object)(object)nview == (Object)null || !nview.IsValid() || !nview.IsOwner()) { return ZdoWriteResult.SkippedNotOwner; } ZDO zDO = nview.GetZDO(); if (zDO == null || !hasZdoSupportHash) { WarnZdoOnce(); return ZdoWriteResult.Failed; } float num = zDO.GetFloat(zdoSupportHash, float.NaN); float num2 = Mathf.Clamp(absoluteEpsilon, 0.0001f, 100f); float num3 = Mathf.Clamp01(normalizedEpsilon); float num4 = Mathf.Max(0.0001f, material.MaxSupport - material.MinSupport); float num5 = Mathf.Max(num2, num3 * num4); bool flag = false; if (!float.IsNaN(num)) { bool flag2 = num + 0.001f >= material.MinSupport; bool flag3 = support + 0.001f >= material.MinSupport; flag = flag2 != flag3; if (!force && !flag && Mathf.Abs(num - support) <= num5) { return ZdoWriteResult.SkippedEpsilon; } } if (!force && !flag && !allowNonCriticalWrite) { return ZdoWriteResult.SkippedBudget; } zDO.Set(zdoSupportHash, support); return ZdoWriteResult.Written; } catch (Exception ex) { if (!warnedZdo && log != null) { warnedZdo = true; log.LogWarning((object)("Could not write graph support to ZDO: " + ex.Message)); } return ZdoWriteResult.Failed; } } internal static bool ReleaseVanillaSupportCache(WearNTear instance) { if ((Object)(object)instance == (Object)null || config == null || !config.ReleaseVanillaSupportCache.Value) { return false; } try { ClearAndRelease((supportCollidersField == null) ? null : (supportCollidersField.GetValue(instance) as List)); ClearAndRelease((supportPositionsField == null) ? null : (supportPositionsField.GetValue(instance) as List)); ClearAndRelease((supportValuesField == null) ? null : (supportValuesField.GetValue(instance) as List)); if (collidersField != null) { collidersField.SetValue(instance, null); } if (boundsField != null) { boundsField.SetValue(instance, null); } return true; } catch { return false; } } private static void ClearAndRelease(List list) { if (list != null) { list.Clear(); if (list.Capacity > 8) { list.Capacity = 0; } } } private static void WarnZdoOnce() { if (!warnedZdo && log != null) { warnedZdo = true; log.LogWarning((object)"The Valheim support ZDO key was not found. Graph support remains local."); } } } } namespace BalrondBetterBuild.Patches { [HarmonyPatch] internal static class WearNTearPatches { private struct UpdateSupportPatchState { internal bool SuppressedVanillaCacheInvalidation; internal bool TimingEnabled; internal bool VanillaPath; internal long StartTicks; } [ThreadStatic] private static int suppressClearCacheDirty; [HarmonyPatch(typeof(WearNTear), "Awake")] [HarmonyPostfix] private static void AwakePostfix(WearNTear __instance) { if (Launch.WorldSessionActive && Launch.Integrity != null) { Launch.Integrity.Register(__instance); } } [HarmonyPatch(typeof(WearNTear), "OnPlaced")] [HarmonyPostfix] private static void OnPlacedPostfix(WearNTear __instance) { if (Launch.WorldSessionActive && Launch.Integrity != null) { Launch.Integrity.MarkGeometryDirty(__instance); } } [HarmonyPatch(typeof(WearNTear), "OnDestroy")] [HarmonyPrefix] private static void OnDestroyPrefix(WearNTear __instance) { if (Launch.WorldSessionActive && Launch.Integrity != null) { Launch.Integrity.Unregister(__instance); } } [HarmonyPatch(typeof(WearNTear), "ClearCachedSupport")] [HarmonyPostfix] private static void ClearCachedSupportPostfix(WearNTear __instance) { if (suppressClearCacheDirty == 0 && Launch.WorldSessionActive && Launch.Integrity != null) { Launch.Integrity.MarkSupportDirty(__instance); } } [HarmonyPatch(typeof(WearNTear), "RPC_HealthChanged")] [HarmonyPrefix] private static void HealthChangedPrefix() { suppressClearCacheDirty++; } [HarmonyPatch(typeof(WearNTear), "RPC_HealthChanged")] [HarmonyFinalizer] private static Exception HealthChangedFinalizer(Exception __exception) { suppressClearCacheDirty = Math.Max(0, suppressClearCacheDirty - 1); return __exception; } [HarmonyPatch(typeof(WearNTear), "UpdateSupport")] [HarmonyPrefix] private static bool UpdateSupportPrefix(WearNTear __instance, ref float ___m_support, ref UpdateSupportPatchState __state) { __state = default(UpdateSupportPatchState); __state.TimingEnabled = Launch.ProfilingEnabled && Launch.Integrity != null; if (__state.TimingEnabled) { __state.StartTicks = Stopwatch.GetTimestamp(); } if (!Launch.WorldSessionActive || Launch.Integrity == null) { __state.VanillaPath = true; return true; } if (Launch.RuntimeMode == IntegrityMode.Replace) { try { if (Launch.Integrity.TryGetCachedSupport(__instance, out var support)) { ___m_support = support; __state.VanillaPath = false; return false; } } catch (Exception ex) { Launch instance = Launch.Instance; if ((Object)(object)instance != (Object)null && instance.Settings != null && instance.Settings.FallbackToVanillaOnError.Value) { Launch.Integrity.DisableReplacementForSession("UpdateSupport replacement failed for " + ((Object)__instance).name + ".", ex); } else { Launch.LogError("BalrondBetterBuild replacement failed for " + ((Object)__instance).name + ": " + ex); } } } suppressClearCacheDirty++; __state.SuppressedVanillaCacheInvalidation = true; __state.VanillaPath = true; return true; } [HarmonyPatch(typeof(WearNTear), "UpdateSupport")] [HarmonyFinalizer] private static Exception UpdateSupportFinalizer(Exception __exception, UpdateSupportPatchState __state) { if (__state.SuppressedVanillaCacheInvalidation) { suppressClearCacheDirty = Math.Max(0, suppressClearCacheDirty - 1); } if (__state.TimingEnabled && Launch.Integrity != null) { Launch.Integrity.RecordUpdateSupportTiming(__state.VanillaPath, Stopwatch.GetTimestamp() - __state.StartTicks); } return __exception; } [HarmonyPatch(typeof(WearNTear), "UpdateSupport")] [HarmonyPostfix] private static void UpdateSupportPostfix(WearNTear __instance, float ___m_support) { if (Launch.WorldSessionActive && Launch.RuntimeMode == IntegrityMode.Observe && Launch.Integrity != null) { Launch.Integrity.RecordVanillaResult(__instance, ___m_support); } } } [HarmonyPatch] internal static class WearNTearUpdaterPatches { private static MethodBase TargetMethod() { Type type = typeof(WearNTear).Assembly.GetType("WearNTearUpdater"); return (type == null) ? null : AccessTools.Method(type, "Update", (Type[])null, (Type[])null); } private static void Prefix(ref long __state) { __state = ((Launch.ProfilingEnabled && Launch.Integrity != null) ? Stopwatch.GetTimestamp() : 0); } private static Exception Finalizer(Exception __exception, long __state) { if (__state != 0L && Launch.Integrity != null) { Launch.Integrity.RecordWearUpdaterTiming(Stopwatch.GetTimestamp() - __state); } return __exception; } } [HarmonyPatch] internal static class ZNetScenePatches { [HarmonyPatch(typeof(ZNetScene), "Awake")] [HarmonyPostfix] private static void AwakePostfix() { Launch.NotifyZNetSceneAwake(); } } } namespace BalrondBetterBuild.Core { internal struct MaterialProfile { internal float MaxSupport; internal float MinSupport; internal float HorizontalLossPerMeter; internal float VerticalLossPerMeter; internal MaterialProfile(float maxSupport, float minSupport, float horizontalLossPerMeter, float verticalLossPerMeter) { MaxSupport = maxSupport; MinSupport = minSupport; HorizontalLossPerMeter = horizontalLossPerMeter; VerticalLossPerMeter = verticalLossPerMeter; } } } namespace BalrondBetterBuild.Config { internal enum MaterialBalancePreset { VanillaCompatible, Forgiving, Generous, Custom } internal sealed class BetterBuildConfig { internal ConfigEntry LockConfiguration { get; private set; } internal ConfigEntry Mode { get; private set; } internal ConfigEntry WorkBudgetMilliseconds { get; private set; } internal ConfigEntry SpatialCellSize { get; private set; } internal ConfigEntry MaximumIslandNodes { get; private set; } internal ConfigEntry SolveDebounceMilliseconds { get; private set; } internal ConfigEntry ActiveAreaReconcileSeconds { get; private set; } internal ConfigEntry RequireInitialStableGraphBeforeReplace { get; private set; } internal ConfigEntry MaximumPooledNodeLists { get; private set; } internal ConfigEntry MaximumRetainedNodeListCapacity { get; private set; } internal ConfigEntry MaximumPooledSpatialCellLists { get; private set; } internal ConfigEntry ContactPadding { get; private set; } internal ConfigEntry MaximumOverlapResults { get; private set; } internal ConfigEntry MaterialPreset { get; private set; } internal ConfigEntry CustomMaxSupportMultiplier { get; private set; } internal ConfigEntry CustomMinSupportMultiplier { get; private set; } internal ConfigEntry CustomHorizontalLossMultiplier { get; private set; } internal ConfigEntry CustomVerticalLossMultiplier { get; private set; } internal ConfigEntry ApplySupportToZdo { get; private set; } internal ConfigEntry NetworkWriteEpsilon { get; private set; } internal ConfigEntry NetworkNormalizedWriteEpsilon { get; private set; } internal ConfigEntry OwnershipRecheckSeconds { get; private set; } internal ConfigEntry MaximumSupportZdoWritesPerFrame { get; private set; } internal ConfigEntry ReleaseVanillaSupportCache { get; private set; } internal ConfigEntry VanillaCacheReleaseStableSeconds { get; private set; } internal ConfigEntry VanillaCacheReleaseFallbackCooldownSeconds { get; private set; } internal ConfigEntry MaximumVanillaCacheReleasesPerFrame { get; private set; } internal ConfigEntry FallbackToVanillaOnError { get; private set; } internal ConfigEntry Diagnostics { get; private set; } internal ConfigEntry EnableInformationLogging { get; private set; } internal ConfigEntry StatsIntervalSeconds { get; private set; } internal ConfigEntry DifferenceWarning { get; private set; } internal ConfigEntry NormalizedDifferenceWarning { get; private set; } internal ConfigEntry VisualDifferenceThreshold { get; private set; } internal ConfigEntry TopDifferencesPerReport { get; private set; } internal ConfigEntry LogMaterialBreakdown { get; private set; } internal ConfigEntry ComparisonChangeEpsilon { get; private set; } internal ConfigEntry LogIdleStatistics { get; private set; } internal ConfigEntry IdleHeartbeatSeconds { get; private set; } internal ConfigEntry DetailedTimingDiagnostics { get; private set; } internal ConfigEntry VerboseLogging { get; private set; } internal BetterBuildConfig(Launch plugin) { LockConfiguration = plugin.SyncedConfig("0 General", "Lock Configuration", defaultValue: true, "When enabled, the server enforces synchronized BalrondBetterBuild settings.", synchronizedSetting: true); Mode = plugin.SyncedConfig("0 General", "Integrity Mode", IntegrityMode.Replace, "Vanilla: original solver. Observe: calculate both and keep vanilla gameplay. Replace: use the cached event-driven solver when ready. New test configurations default to Replace; existing cfg files retain their saved value.", synchronizedSetting: true); WorkBudgetMilliseconds = plugin.SyncedConfig("1 Performance", "Work Budget Milliseconds", 2f, "Maximum contact, graph and relaxation work performed per frame.", synchronizedSetting: true); SpatialCellSize = plugin.SyncedConfig("1 Performance", "Spatial Cell Size", 4f, "Cell size used by the structural spatial hash.", synchronizedSetting: true); MaximumIslandNodes = plugin.SyncedConfig("1 Performance", "Maximum Island Nodes", 100000, "Safety limit for one connected structural island.", synchronizedSetting: true); SolveDebounceMilliseconds = plugin.SyncedConfig("1 Performance", "Solve Debounce Milliseconds", 150, "Delay after topology changes before an island solve begins. Prevents repeated solves while a location streams in.", synchronizedSetting: true); ActiveAreaReconcileSeconds = plugin.SyncedConfig("1 Performance", "Active Area Reconcile Seconds", 180f, "Low-frequency stale-reference safety sweep. Zone changes, teleports and lifecycle events trigger immediate reconciliation; stationary clients are clamped to at least 30 seconds and dedicated servers to at least 120 seconds.", synchronizedSetting: true); RequireInitialStableGraphBeforeReplace = plugin.SyncedConfig("1 Performance", "Require Initial Stable Graph Before Replace", defaultValue: true, "Keep vanilla support active until the initial active-area graph has finished preparing, refreshing and solving.", synchronizedSetting: true); MaximumPooledNodeLists = plugin.SyncedConfig("1 Performance", "Maximum Pooled Node Lists", 2048, "Maximum number of cleared per-node link/dependent lists retained for reuse after streaming or teleportation. Lower values release more memory; higher values reduce future allocations.", synchronizedSetting: false); MaximumRetainedNodeListCapacity = plugin.SyncedConfig("1 Performance", "Maximum Retained Node List Capacity", 16, "Maximum capacity retained by a pooled per-node list. Lists that grew larger are trimmed before returning to the pool.", synchronizedSetting: false); MaximumPooledSpatialCellLists = plugin.SyncedConfig("1 Performance", "Maximum Pooled Spatial Cell Lists", 2048, "Maximum number of empty spatial-hash cell lists kept for reuse after leaving a large location.", synchronizedSetting: false); ContactPadding = plugin.SyncedConfig("2 Contacts", "Support Probe Expansion", 0.15f, "Per-collider expansion. Valheim uses 0.15 m on each side of the support probe.", synchronizedSetting: true); MaximumOverlapResults = plugin.SyncedConfig("2 Contacts", "Maximum Overlap Results", 4096, "Maximum cached Physics.OverlapBoxNonAlloc result capacity for extremely dense locations.", synchronizedSetting: true); MaterialPreset = plugin.SyncedConfig("3 Materials", "Material Balance Preset", MaterialBalancePreset.VanillaCompatible, "VanillaCompatible uses current game material values. Forgiving and Generous reduce structural losses. Custom uses the multipliers below.", synchronizedSetting: true); CustomMaxSupportMultiplier = plugin.SyncedConfig("3 Materials", "Custom Max Support Multiplier", 1f, "Custom preset multiplier for material maximum support.", synchronizedSetting: true); CustomMinSupportMultiplier = plugin.SyncedConfig("3 Materials", "Custom Minimum Support Multiplier", 1f, "Custom preset multiplier for minimum support. Values below 1 are more forgiving.", synchronizedSetting: true); CustomHorizontalLossMultiplier = plugin.SyncedConfig("3 Materials", "Custom Horizontal Loss Multiplier", 1f, "Custom preset multiplier for horizontal loss. Values below 1 allow longer spans.", synchronizedSetting: true); CustomVerticalLossMultiplier = plugin.SyncedConfig("3 Materials", "Custom Vertical Loss Multiplier", 1f, "Custom preset multiplier for vertical loss. Values below 1 allow taller structures.", synchronizedSetting: true); ApplySupportToZdo = plugin.SyncedConfig("4 Networking", "Write Support To ZDO", defaultValue: true, "The current ZDO owner writes committed support into Valheim's original support field for multiplayer synchronization.", synchronizedSetting: true); NetworkWriteEpsilon = plugin.SyncedConfig("4 Networking", "Network Absolute Write Epsilon", 0.01f, "Absolute minimum support change required before writing a new ZDO value. The normalized epsilon below is also applied and the larger threshold wins.", synchronizedSetting: true); NetworkNormalizedWriteEpsilon = plugin.SyncedConfig("4 Networking", "Network Normalized Write Epsilon", 0.0025f, "Minimum support change as a fraction of the material support range. 0.0025 equals 0.25 percent. Stability-threshold crossings are always written.", synchronizedSetting: true); OwnershipRecheckSeconds = plugin.SyncedConfig("4 Networking", "Ownership Recheck Seconds", 15f, "How often the budgeted ownership maintenance sweep rechecks ZDO ownership. Structural changes still request immediate synchronization; lower values react faster but perform more ZNetView checks.", synchronizedSetting: true); MaximumSupportZdoWritesPerFrame = plugin.SyncedConfig("4 Networking", "Maximum Support ZDO Writes Per Frame", 32, "Maximum non-critical support synchronization writes per frame. Stability-threshold crossings and ownership changes bypass this budget; excess non-critical updates are deferred without allocation.", synchronizedSetting: true); ReleaseVanillaSupportCache = plugin.SyncedConfig("4 Networking", "Release Vanilla Support Cache (Experimental)", defaultValue: false, "In Replace mode, release redundant vanilla support caches only after the node has remained stable for the configured delay. Cooldowns and per-frame limits prevent rebuild/allocation thrashing.", synchronizedSetting: true); VanillaCacheReleaseStableSeconds = plugin.SyncedConfig("4 Networking", "Vanilla Cache Release Stable Seconds", 60f, "When experimental cache release is enabled, a node must remain solved and ready for this long before vanilla support caches may be released.", synchronizedSetting: true); VanillaCacheReleaseFallbackCooldownSeconds = plugin.SyncedConfig("4 Networking", "Vanilla Cache Release Fallback Cooldown Seconds", 60f, "After any fallback to Vanilla, wait this long before releasing that node's vanilla caches again. Prevents allocation/rebuild thrashing.", synchronizedSetting: true); MaximumVanillaCacheReleasesPerFrame = plugin.SyncedConfig("4 Networking", "Maximum Vanilla Cache Releases Per Frame", 16, "Maximum number of eligible vanilla support caches released in one frame. The operation is maintenance-only and disabled unless experimental cache release is enabled.", synchronizedSetting: true); FallbackToVanillaOnError = plugin.SyncedConfig("4 Networking", "Fallback To Vanilla On Error", defaultValue: true, "Open a local session circuit breaker and safely use Vanilla if replacement processing throws an exception.", synchronizedSetting: true); Diagnostics = plugin.SyncedConfig("9 Diagnostics", "Runtime Diagnostics Level", DiagnosticsLevel.Off, "Off: no periodic statistics and no hot-path diagnostic counters. Summary: compact graph and replacement statistics. Profiling: Summary plus direct UpdateSupport, WearNTearUpdater, GC and managed-memory measurements.", synchronizedSetting: false); EnableInformationLogging = plugin.SyncedConfig("9 Diagnostics", "Enable Information Logging", defaultValue: false, "Master switch for BalrondBetterBuild informational messages and statistics. Errors and safety warnings remain enabled. This does not suppress Valheim or other mods' Unity logs such as Placed or Spawned.", synchronizedSetting: false); StatsIntervalSeconds = plugin.SyncedConfig("9 Diagnostics", "Statistics Interval Seconds", 0f, "Local interval for graph statistics when diagnostics and information logging are enabled. Set to 0 to disable periodic reports.", synchronizedSetting: false); DifferenceWarning = plugin.SyncedConfig("9 Diagnostics", "Difference Warning", 15f, "Local raw Observe-mode support difference threshold used by verbose logging.", synchronizedSetting: false); NormalizedDifferenceWarning = plugin.SyncedConfig("9 Diagnostics", "Normalized Difference Warning", 0.2f, "Local normalized support difference threshold used by verbose logging. Range 0-1.", synchronizedSetting: false); VisualDifferenceThreshold = plugin.SyncedConfig("9 Diagnostics", "Visual Difference Threshold", 0.2f, "Local threshold for counting a visible integrity-color mismatch. Range 0-1.", synchronizedSetting: false); TopDifferencesPerReport = plugin.SyncedConfig("9 Diagnostics", "Top Differences Per Report", 5, "Number of unique WearNTear elements included in the compact top-difference report. Range 0-20.", synchronizedSetting: false); LogMaterialBreakdown = plugin.SyncedConfig("9 Diagnostics", "Log Material Breakdown", defaultValue: true, "Log a compact current unique-node comparison summary per MaterialType in Observe mode.", synchronizedSetting: false); ComparisonChangeEpsilon = plugin.SyncedConfig("9 Diagnostics", "Comparison Change Epsilon", 0.001f, "Observe mode records a new diagnostic sample only when vanilla or graph support changes by at least this amount.", synchronizedSetting: false); LogIdleStatistics = plugin.SyncedConfig("9 Diagnostics", "Log Idle Statistics", defaultValue: false, "When disabled, unchanged idle reports are suppressed. A low-frequency heartbeat can still be emitted.", synchronizedSetting: false); IdleHeartbeatSeconds = plugin.SyncedConfig("9 Diagnostics", "Idle Heartbeat Seconds", 0f, "Maximum time between idle diagnostic heartbeats when idle logging is disabled. Set to 0 to suppress idle heartbeats entirely.", synchronizedSetting: false); DetailedTimingDiagnostics = plugin.SyncedConfig("9 Diagnostics", "Detailed Stage Timing", defaultValue: false, "When Runtime Diagnostics Level is Profiling, track maximum prepare, refresh, solve, reconciliation and network-sync step times.", synchronizedSetting: false); VerboseLogging = plugin.SyncedConfig("9 Diagnostics", "Verbose Logging", defaultValue: false, "Log large per-piece differences and additional graph details.", synchronizedSetting: false); } } internal enum DiagnosticsLevel { Off, Summary, Profiling } public enum IntegrityMode { Vanilla, Observe, Replace } } namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [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 ServerSync { [PublicAPI] internal abstract class OwnConfigEntryBase { public object? LocalBaseValue; public bool SynchronizedConfig = true; public abstract ConfigEntryBase BaseConfig { get; } } [PublicAPI] internal class SyncedConfigEntry(ConfigEntry sourceConfig) : OwnConfigEntryBase() { public readonly ConfigEntry SourceConfig = sourceConfig; public override ConfigEntryBase BaseConfig => (ConfigEntryBase)(object)SourceConfig; public T Value { get { return SourceConfig.Value; } set { SourceConfig.Value = value; } } public void AssignLocalValue(T value) { if (LocalBaseValue == null) { Value = value; } else { LocalBaseValue = value; } } } internal abstract class CustomSyncedValueBase { public object? LocalBaseValue; public readonly string Identifier; public readonly Type Type; private object? boxedValue; protected bool localIsOwner; public readonly int Priority; public object? BoxedValue { get { return boxedValue; } set { boxedValue = value; this.ValueChanged?.Invoke(); } } public event Action? ValueChanged; protected CustomSyncedValueBase(ConfigSync configSync, string identifier, Type type, int priority) { Priority = priority; Identifier = identifier; Type = type; configSync.AddCustomValue(this); localIsOwner = configSync.IsSourceOfTruth; configSync.SourceOfTruthChanged += delegate(bool truth) { localIsOwner = truth; }; } } [PublicAPI] internal sealed class CustomSyncedValue : CustomSyncedValueBase { public T Value { get { return (T)base.BoxedValue; } set { base.BoxedValue = value; } } public CustomSyncedValue(ConfigSync configSync, string identifier, T value = default(T), int priority = 0) : base(configSync, identifier, typeof(T), priority) { Value = value; } public void AssignLocalValue(T value) { if (localIsOwner) { Value = value; } else { LocalBaseValue = value; } } } internal class ConfigurationManagerAttributes { [UsedImplicitly] public bool? ReadOnly = false; } [PublicAPI] internal class ConfigSync { [HarmonyPatch(typeof(ZRpc), "HandlePackage")] private static class SnatchCurrentlyHandlingRPC { public static ZRpc? currentRpc; [HarmonyPrefix] private static void Prefix(ZRpc __instance) { currentRpc = __instance; } } [HarmonyPatch(typeof(ZNet), "Awake")] internal static class RegisterRPCPatch { [HarmonyPostfix] private static void Postfix(ZNet __instance) { isServer = __instance.IsServer(); foreach (ConfigSync configSync2 in configSyncs) { ZRoutedRpc.instance.Register(configSync2.Name + " ConfigSync", (Action)configSync2.RPC_FromOtherClientConfigSync); if (isServer) { configSync2.InitialSyncDone = true; Debug.Log((object)("Registered '" + configSync2.Name + " ConfigSync' RPC - waiting for incoming connections")); } } if (isServer) { ((MonoBehaviour)__instance).StartCoroutine(WatchAdminListChanges()); } static void SendAdmin(List peers, bool isAdmin) { ZPackage package = ConfigsToPackage(null, null, new PackageEntry[1] { new PackageEntry { section = "Internal", key = "lockexempt", type = typeof(bool), value = isAdmin } }); ConfigSync configSync = configSyncs.First(); if (configSync != null) { ((MonoBehaviour)ZNet.instance).StartCoroutine(configSync.sendZPackage(peers, package)); } } static IEnumerator WatchAdminListChanges() { MethodInfo listContainsId = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null); SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance); List CurrentList = new List(adminList.GetList()); while (true) { yield return (object)new WaitForSeconds(30f); if (!adminList.GetList().SequenceEqual(CurrentList)) { CurrentList = new List(adminList.GetList()); List adminPeer = ZNet.instance.GetPeers().Where(delegate(ZNetPeer p) { string hostName = p.m_rpc.GetSocket().GetHostName(); return ((object)listContainsId == null) ? adminList.Contains(hostName) : ((bool)listContainsId.Invoke(ZNet.instance, new object[2] { adminList, hostName })); }).ToList(); List nonAdminPeer = ZNet.instance.GetPeers().Except(adminPeer).ToList(); SendAdmin(nonAdminPeer, isAdmin: false); SendAdmin(adminPeer, isAdmin: true); } } } } } [HarmonyPatch(typeof(ZNet), "OnNewConnection")] private static class RegisterClientRPCPatch { [HarmonyPostfix] private static void Postfix(ZNet __instance, ZNetPeer peer) { if (__instance.IsServer()) { return; } foreach (ConfigSync configSync in configSyncs) { peer.m_rpc.Register(configSync.Name + " ConfigSync", (Action)configSync.RPC_FromServerConfigSync); } } } private class ParsedConfigs { public readonly Dictionary configValues = new Dictionary(); public readonly Dictionary customValues = new Dictionary(); } [HarmonyPatch(typeof(ZNet), "Shutdown")] private class ResetConfigsOnShutdown { [HarmonyPostfix] private static void Postfix() { ProcessingServerUpdate = true; foreach (ConfigSync configSync in configSyncs) { configSync.resetConfigsFromServer(); configSync.IsSourceOfTruth = true; configSync.InitialSyncDone = false; } ProcessingServerUpdate = false; } } [HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")] private class SendConfigsAfterLogin { private class BufferingSocket : ZPlayFabSocket, ISocket { public volatile bool finished = false; public volatile int versionMatchQueued = -1; public readonly List Package = new List(); public readonly ISocket Original; public BufferingSocket(ISocket original) { Original = original; ((ZPlayFabSocket)this)..ctor(); } public bool IsConnected() { return Original.IsConnected(); } public ZPackage Recv() { return Original.Recv(); } public int GetSendQueueSize() { return Original.GetSendQueueSize(); } public int GetCurrentSendRate() { return Original.GetCurrentSendRate(); } public bool IsHost() { return Original.IsHost(); } public void Dispose() { Original.Dispose(); } public bool GotNewData() { return Original.GotNewData(); } public void Close() { Original.Close(); } public string GetEndPointString() { return Original.GetEndPointString(); } public void GetAndResetStats(out int totalSent, out int totalRecv) { Original.GetAndResetStats(ref totalSent, ref totalRecv); } public void GetConnectionQuality(out float localQuality, out float remoteQuality, out int ping, out float outByteSec, out float inByteSec) { Original.GetConnectionQuality(ref localQuality, ref remoteQuality, ref ping, ref outByteSec, ref inByteSec); } public ISocket Accept() { return Original.Accept(); } public int GetHostPort() { return Original.GetHostPort(); } public bool Flush() { return Original.Flush(); } public string GetHostName() { return Original.GetHostName(); } public void VersionMatch() { if (finished) { Original.VersionMatch(); } else { versionMatchQueued = Package.Count; } } public void Send(ZPackage pkg) { //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Expected O, but got Unknown int pos = pkg.GetPos(); pkg.SetPos(0); int num = pkg.ReadInt(); if ((num == StringExtensionMethods.GetStableHashCode("PeerInfo") || num == StringExtensionMethods.GetStableHashCode("RoutedRPC") || num == StringExtensionMethods.GetStableHashCode("ZDOData")) && !finished) { ZPackage val = new ZPackage(pkg.GetArray()); val.SetPos(pos); Package.Add(val); } else { pkg.SetPos(pos); Original.Send(pkg); } } } [HarmonyPriority(800)] [HarmonyPrefix] private static void Prefix(ref Dictionary? __state, ZNet __instance, ZRpc rpc) { //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Invalid comparison between Unknown and I4 if (!__instance.IsServer()) { return; } BufferingSocket bufferingSocket = new BufferingSocket(rpc.GetSocket()); AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc, bufferingSocket); object? obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc }); ZNetPeer val = (ZNetPeer)((obj is ZNetPeer) ? obj : null); if (val != null && (int)ZNet.m_onlineBackend > 0) { FieldInfo fieldInfo = AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket"); object? value = fieldInfo.GetValue(val); ZPlayFabSocket val2 = (ZPlayFabSocket)((value is ZPlayFabSocket) ? value : null); if (val2 != null) { typeof(ZPlayFabSocket).GetField("m_remotePlayerId").SetValue(bufferingSocket, val2.m_remotePlayerId); } fieldInfo.SetValue(val, bufferingSocket); } if (__state == null) { __state = new Dictionary(); } __state[Assembly.GetExecutingAssembly()] = bufferingSocket; } [HarmonyPostfix] private static void Postfix(Dictionary __state, ZNet __instance, ZRpc rpc) { ZNetPeer peer; if (__instance.IsServer()) { object obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc }); peer = (ZNetPeer)((obj is ZNetPeer) ? obj : null); if (peer == null) { SendBufferedData(); } else { ((MonoBehaviour)__instance).StartCoroutine(sendAsync()); } } void SendBufferedData() { if (rpc.GetSocket() is BufferingSocket bufferingSocket) { AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc, bufferingSocket.Original); object? obj2 = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc }); ZNetPeer val = (ZNetPeer)((obj2 is ZNetPeer) ? obj2 : null); if (val != null) { AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket").SetValue(val, bufferingSocket.Original); } } BufferingSocket bufferingSocket2 = __state[Assembly.GetExecutingAssembly()]; bufferingSocket2.finished = true; for (int i = 0; i < bufferingSocket2.Package.Count; i++) { if (i == bufferingSocket2.versionMatchQueued) { bufferingSocket2.Original.VersionMatch(); } bufferingSocket2.Original.Send(bufferingSocket2.Package[i]); } if (bufferingSocket2.Package.Count == bufferingSocket2.versionMatchQueued) { bufferingSocket2.Original.VersionMatch(); } } IEnumerator sendAsync() { foreach (ConfigSync configSync in configSyncs) { List entries = new List(); if (configSync.CurrentVersion != null) { entries.Add(new PackageEntry { section = "Internal", key = "serverversion", type = typeof(string), value = configSync.CurrentVersion }); } MethodInfo listContainsId = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null); SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance); entries.Add(new PackageEntry { section = "Internal", key = "lockexempt", type = typeof(bool), value = (((object)listContainsId == null) ? ((object)adminList.Contains(rpc.GetSocket().GetHostName())) : listContainsId.Invoke(ZNet.instance, new object[2] { adminList, rpc.GetSocket().GetHostName() })) }); ZPackage package = ConfigsToPackage(configSync.allConfigs.Select((OwnConfigEntryBase c) => c.BaseConfig), configSync.allCustomValues, entries, partial: false); yield return ((MonoBehaviour)__instance).StartCoroutine(configSync.sendZPackage(new List { peer }, package)); } SendBufferedData(); } } } private class PackageEntry { public string section = null; public string key = null; public Type type = null; public object? value; } [HarmonyPatch(typeof(ConfigEntryBase), "GetSerializedValue")] private static class PreventSavingServerInfo { [HarmonyPrefix] private static bool Prefix(ConfigEntryBase __instance, ref string __result) { OwnConfigEntryBase ownConfigEntryBase = configData(__instance); if (ownConfigEntryBase == null || isWritableConfig(ownConfigEntryBase)) { return true; } __result = TomlTypeConverter.ConvertToString(ownConfigEntryBase.LocalBaseValue, __instance.SettingType); return false; } } [HarmonyPatch(typeof(ConfigEntryBase), "SetSerializedValue")] private static class PreventConfigRereadChangingValues { [HarmonyPrefix] private static bool Prefix(ConfigEntryBase __instance, string value) { OwnConfigEntryBase ownConfigEntryBase = configData(__instance); if (ownConfigEntryBase == null || ownConfigEntryBase.LocalBaseValue == null) { return true; } try { ownConfigEntryBase.LocalBaseValue = TomlTypeConverter.ConvertToValue(value, __instance.SettingType); } catch (Exception ex) { Debug.LogWarning((object)$"Config value of setting \"{__instance.Definition}\" could not be parsed and will be ignored. Reason: {ex.Message}; Value: {value}"); } return false; } } private class InvalidDeserializationTypeException : Exception { public string expected = null; public string received = null; public string field = ""; } public static bool ProcessingServerUpdate; public readonly string Name; public string? DisplayName; public string? CurrentVersion; public string? MinimumRequiredVersion; public bool ModRequired = false; private bool? forceConfigLocking; private bool isSourceOfTruth = true; private static readonly HashSet configSyncs; private readonly HashSet allConfigs = new HashSet(); private HashSet allCustomValues = new HashSet(); private static bool isServer; private static bool lockExempt; private OwnConfigEntryBase? lockedConfig = null; private const byte PARTIAL_CONFIGS = 1; private const byte FRAGMENTED_CONFIG = 2; private const byte COMPRESSED_CONFIG = 4; private readonly Dictionary> configValueCache = new Dictionary>(); private readonly List> cacheExpirations = new List>(); private static long packageCounter; public bool IsLocked { get { bool? flag = forceConfigLocking; bool num; if (!flag.HasValue) { if (lockedConfig == null) { goto IL_0052; } num = ((IConvertible)lockedConfig.BaseConfig.BoxedValue).ToInt32(CultureInfo.InvariantCulture) != 0; } else { num = flag == true; } if (!num) { goto IL_0052; } int result = ((!lockExempt) ? 1 : 0); goto IL_0053; IL_0052: result = 0; goto IL_0053; IL_0053: return (byte)result != 0; } set { forceConfigLocking = value; } } public bool IsAdmin => lockExempt || isSourceOfTruth; public bool IsSourceOfTruth { get { return isSourceOfTruth; } private set { if (value != isSourceOfTruth) { isSourceOfTruth = value; this.SourceOfTruthChanged?.Invoke(value); } } } public bool InitialSyncDone { get; private set; } = false; public event Action? SourceOfTruthChanged; private event Action? lockedConfigChanged; static ConfigSync() { ProcessingServerUpdate = false; configSyncs = new HashSet(); lockExempt = false; packageCounter = 0L; RuntimeHelpers.RunClassConstructor(typeof(VersionCheck).TypeHandle); } public ConfigSync(string name) { Name = name; configSyncs.Add(this); new VersionCheck(this); } public SyncedConfigEntry AddConfigEntry(ConfigEntry configEntry) { OwnConfigEntryBase ownConfigEntryBase = configData((ConfigEntryBase)(object)configEntry); SyncedConfigEntry syncedEntry = ownConfigEntryBase as SyncedConfigEntry; if (syncedEntry == null) { syncedEntry = new SyncedConfigEntry(configEntry); AccessTools.DeclaredField(typeof(ConfigDescription), "k__BackingField").SetValue(((ConfigEntryBase)configEntry).Description, new object[1] { new ConfigurationManagerAttributes() }.Concat(((ConfigEntryBase)configEntry).Description.Tags ?? Array.Empty()).Concat(new SyncedConfigEntry[1] { syncedEntry }).ToArray()); configEntry.SettingChanged += delegate { if (!ProcessingServerUpdate && syncedEntry.SynchronizedConfig) { Broadcast(ZRoutedRpc.Everybody, (ConfigEntryBase)configEntry); } }; allConfigs.Add(syncedEntry); } return syncedEntry; } public SyncedConfigEntry AddLockingConfigEntry(ConfigEntry lockingConfig) where T : IConvertible { if (lockedConfig != null) { throw new Exception("Cannot initialize locking ConfigEntry twice"); } lockedConfig = AddConfigEntry(lockingConfig); lockingConfig.SettingChanged += delegate { this.lockedConfigChanged?.Invoke(); }; return (SyncedConfigEntry)lockedConfig; } internal void AddCustomValue(CustomSyncedValueBase customValue) { if (allCustomValues.Select((CustomSyncedValueBase v) => v.Identifier).Concat(new string[1] { "serverversion" }).Contains(customValue.Identifier)) { throw new Exception("Cannot have multiple settings with the same name or with a reserved name (serverversion)"); } allCustomValues.Add(customValue); allCustomValues = new HashSet(allCustomValues.OrderByDescending((CustomSyncedValueBase v) => v.Priority)); customValue.ValueChanged += delegate { if (!ProcessingServerUpdate) { Broadcast(ZRoutedRpc.Everybody, customValue); } }; } private void RPC_FromServerConfigSync(ZRpc rpc, ZPackage package) { lockedConfigChanged += serverLockedSettingChanged; IsSourceOfTruth = false; if (HandleConfigSyncRPC(0L, package, clientUpdate: false)) { InitialSyncDone = true; } } private void RPC_FromOtherClientConfigSync(long sender, ZPackage package) { HandleConfigSyncRPC(sender, package, clientUpdate: true); } private bool HandleConfigSyncRPC(long sender, ZPackage package, bool clientUpdate) { //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Expected O, but got Unknown //IL_0250: Unknown result type (might be due to invalid IL or missing references) //IL_0257: Expected O, but got Unknown //IL_01ea: Unknown result type (might be due to invalid IL or missing references) //IL_01f1: Expected O, but got Unknown try { if (isServer && IsLocked) { ZRpc? currentRpc = SnatchCurrentlyHandlingRPC.currentRpc; object obj; if (currentRpc == null) { obj = null; } else { ISocket socket = currentRpc.GetSocket(); obj = ((socket != null) ? socket.GetHostName() : null); } string text = (string)obj; if (text != null) { MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null); SyncedList val = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance); if (!(((object)methodInfo == null) ? val.Contains(text) : ((bool)methodInfo.Invoke(ZNet.instance, new object[2] { val, text })))) { return false; } } } cacheExpirations.RemoveAll(delegate(KeyValuePair kv) { if (kv.Key < DateTimeOffset.Now.Ticks) { configValueCache.Remove(kv.Value); return true; } return false; }); byte b = package.ReadByte(); if ((b & 2) != 0) { long num = package.ReadLong(); string text2 = sender.ToString() + num; if (!configValueCache.TryGetValue(text2, out SortedDictionary value)) { value = new SortedDictionary(); configValueCache[text2] = value; cacheExpirations.Add(new KeyValuePair(DateTimeOffset.Now.AddSeconds(60.0).Ticks, text2)); } int key = package.ReadInt(); int num2 = package.ReadInt(); value.Add(key, package.ReadByteArray()); if (value.Count < num2) { return false; } configValueCache.Remove(text2); package = new ZPackage(value.Values.SelectMany((byte[] a) => a).ToArray()); b = package.ReadByte(); } ProcessingServerUpdate = true; if ((b & 4) != 0) { byte[] buffer = package.ReadByteArray(); MemoryStream stream = new MemoryStream(buffer); MemoryStream memoryStream = new MemoryStream(); using (DeflateStream deflateStream = new DeflateStream(stream, CompressionMode.Decompress)) { deflateStream.CopyTo(memoryStream); } package = new ZPackage(memoryStream.ToArray()); b = package.ReadByte(); } if ((b & 1) == 0) { resetConfigsFromServer(); } ParsedConfigs parsedConfigs = ReadConfigsFromPackage(package); ConfigFile val2 = null; bool saveOnConfigSet = false; foreach (KeyValuePair configValue in parsedConfigs.configValues) { if (!isServer && configValue.Key.LocalBaseValue == null) { configValue.Key.LocalBaseValue = configValue.Key.BaseConfig.BoxedValue; } if (val2 == null) { val2 = configValue.Key.BaseConfig.ConfigFile; saveOnConfigSet = val2.SaveOnConfigSet; val2.SaveOnConfigSet = false; } configValue.Key.BaseConfig.BoxedValue = configValue.Value; } if (val2 != null) { val2.SaveOnConfigSet = saveOnConfigSet; val2.Save(); } foreach (KeyValuePair customValue in parsedConfigs.customValues) { if (!isServer) { CustomSyncedValueBase key2 = customValue.Key; if (key2.LocalBaseValue == null) { key2.LocalBaseValue = customValue.Key.BoxedValue; } } customValue.Key.BoxedValue = customValue.Value; } Debug.Log((object)string.Format("Received {0} configs and {1} custom values from {2} for mod {3}", parsedConfigs.configValues.Count, parsedConfigs.customValues.Count, (isServer || clientUpdate) ? $"client {sender}" : "the server", DisplayName ?? Name)); if (!isServer) { serverLockedSettingChanged(); } return true; } finally { ProcessingServerUpdate = false; } } private ParsedConfigs ReadConfigsFromPackage(ZPackage package) { ParsedConfigs parsedConfigs = new ParsedConfigs(); Dictionary dictionary = allConfigs.Where((OwnConfigEntryBase c) => c.SynchronizedConfig).ToDictionary((OwnConfigEntryBase c) => c.BaseConfig.Definition.Section + "_" + c.BaseConfig.Definition.Key, (OwnConfigEntryBase c) => c); Dictionary dictionary2 = allCustomValues.ToDictionary((CustomSyncedValueBase c) => c.Identifier, (CustomSyncedValueBase c) => c); int num = package.ReadInt(); for (int num2 = 0; num2 < num; num2++) { string text = package.ReadString(); string text2 = package.ReadString(); string text3 = package.ReadString(); Type type = Type.GetType(text3); if (text3 == "" || type != null) { object obj; try { obj = ((text3 == "") ? null : ReadValueWithTypeFromZPackage(package, type)); } catch (InvalidDeserializationTypeException ex) { Debug.LogWarning((object)("Got unexpected struct internal type " + ex.received + " for field " + ex.field + " struct " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + ex.expected)); continue; } OwnConfigEntryBase value2; if (text == "Internal") { CustomSyncedValueBase value; if (text2 == "serverversion") { if (obj?.ToString() != CurrentVersion) { Debug.LogWarning((object)("Received server version is not equal: server version = " + (obj?.ToString() ?? "null") + "; local version = " + (CurrentVersion ?? "unknown"))); } } else if (text2 == "lockexempt") { if (obj is bool flag) { lockExempt = flag; } } else if (dictionary2.TryGetValue(text2, out value)) { if ((text3 == "" && (!value.Type.IsValueType || Nullable.GetUnderlyingType(value.Type) != null)) || GetZPackageTypeString(value.Type) == text3) { parsedConfigs.customValues[value] = obj; continue; } Debug.LogWarning((object)("Got unexpected type " + text3 + " for internal value " + text2 + " for mod " + (DisplayName ?? Name) + ", expecting " + value.Type.AssemblyQualifiedName)); } } else if (dictionary.TryGetValue(text + "_" + text2, out value2)) { Type type2 = configType(value2.BaseConfig); if ((text3 == "" && (!type2.IsValueType || Nullable.GetUnderlyingType(type2) != null)) || GetZPackageTypeString(type2) == text3) { parsedConfigs.configValues[value2] = obj; continue; } Debug.LogWarning((object)("Got unexpected type " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + type2.AssemblyQualifiedName)); } else { Debug.LogWarning((object)("Received unknown config entry " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ". This may happen if client and server versions of the mod do not match.")); } continue; } Debug.LogWarning((object)("Got invalid type " + text3 + ", abort reading of received configs")); return new ParsedConfigs(); } return parsedConfigs; } private static bool isWritableConfig(OwnConfigEntryBase config) { ConfigSync configSync = configSyncs.FirstOrDefault((ConfigSync cs) => cs.allConfigs.Contains(config)); if (configSync == null) { return true; } return configSync.IsSourceOfTruth || !config.SynchronizedConfig || config.LocalBaseValue == null || (!configSync.IsLocked && (config != configSync.lockedConfig || lockExempt)); } private void serverLockedSettingChanged() { foreach (OwnConfigEntryBase allConfig in allConfigs) { configAttribute(allConfig.BaseConfig).ReadOnly = !isWritableConfig(allConfig); } } private void resetConfigsFromServer() { ConfigFile val = null; bool saveOnConfigSet = false; foreach (OwnConfigEntryBase item in allConfigs.Where((OwnConfigEntryBase config) => config.LocalBaseValue != null)) { if (val == null) { val = item.BaseConfig.ConfigFile; saveOnConfigSet = val.SaveOnConfigSet; val.SaveOnConfigSet = false; } item.BaseConfig.BoxedValue = item.LocalBaseValue; item.LocalBaseValue = null; } if (val != null) { val.SaveOnConfigSet = saveOnConfigSet; } foreach (CustomSyncedValueBase item2 in allCustomValues.Where((CustomSyncedValueBase config) => config.LocalBaseValue != null)) { item2.BoxedValue = item2.LocalBaseValue; item2.LocalBaseValue = null; } lockedConfigChanged -= serverLockedSettingChanged; serverLockedSettingChanged(); } private IEnumerator distributeConfigToPeers(ZNetPeer peer, ZPackage package) { ZRoutedRpc rpc = ZRoutedRpc.instance; if (rpc == null) { yield break; } byte[] data = package.GetArray(); if (data != null && data.LongLength > 250000) { int fragments = (int)(1 + (data.LongLength - 1) / 250000); long packageIdentifier = ++packageCounter; int fragment = 0; while (fragment < fragments) { foreach (bool item in waitForQueue()) { yield return item; } if (peer.m_socket.IsConnected()) { ZPackage fragmentedPackage = new ZPackage(); fragmentedPackage.Write((byte)2); fragmentedPackage.Write(packageIdentifier); fragmentedPackage.Write(fragment); fragmentedPackage.Write(fragments); fragmentedPackage.Write(data.Skip(250000 * fragment).Take(250000).ToArray()); SendPackage(fragmentedPackage); if (fragment != fragments - 1) { yield return true; } int num = fragment + 1; fragment = num; continue; } break; } yield break; } foreach (bool item2 in waitForQueue()) { yield return item2; } SendPackage(package); void SendPackage(ZPackage pkg) { string text = Name + " ConfigSync"; if (isServer) { peer.m_rpc.Invoke(text, new object[1] { pkg }); } else { rpc.InvokeRoutedRPC(peer.m_server ? 0 : peer.m_uid, text, new object[1] { pkg }); } } IEnumerable waitForQueue() { float timeout = Time.time + 30f; while (peer.m_socket.GetSendQueueSize() > 20000) { if (Time.time > timeout) { Debug.Log((object)$"Disconnecting {peer.m_uid} after 30 seconds config sending timeout"); peer.m_rpc.Invoke("Error", new object[1] { (object)(ConnectionStatus)5 }); ZNet.instance.Disconnect(peer); break; } yield return false; } } } private IEnumerator sendZPackage(long target, ZPackage package) { if (!Object.op_Implicit((Object)(object)ZNet.instance)) { return Enumerable.Empty().GetEnumerator(); } List list = (List)AccessTools.DeclaredField(typeof(ZRoutedRpc), "m_peers").GetValue(ZRoutedRpc.instance); if (target != ZRoutedRpc.Everybody) { list = list.Where((ZNetPeer p) => p.m_uid == target).ToList(); } return sendZPackage(list, package); } private IEnumerator sendZPackage(List peers, ZPackage package) { if (!Object.op_Implicit((Object)(object)ZNet.instance)) { yield break; } byte[] rawData = package.GetArray(); if (rawData != null && rawData.LongLength > 10000) { ZPackage compressedPackage = new ZPackage(); compressedPackage.Write((byte)4); MemoryStream output = new MemoryStream(); using (DeflateStream deflateStream = new DeflateStream(output, CompressionLevel.Optimal)) { deflateStream.Write(rawData, 0, rawData.Length); } compressedPackage.Write(output.ToArray()); package = compressedPackage; } List> writers = (from p in peers where p.IsReady() select distributeConfigToPeers(p, package)).ToList(); writers.RemoveAll((IEnumerator writer) => !writer.MoveNext()); while (writers.Count > 0) { yield return null; writers.RemoveAll((IEnumerator writer) => !writer.MoveNext()); } } private void Broadcast(long target, params ConfigEntryBase[] configs) { if (!IsLocked || isServer) { ZPackage package = ConfigsToPackage(configs); ZNet instance = ZNet.instance; if (instance != null) { ((MonoBehaviour)instance).StartCoroutine(sendZPackage(target, package)); } } } private void Broadcast(long target, params CustomSyncedValueBase[] customValues) { if (!IsLocked || isServer) { ZPackage package = ConfigsToPackage(null, customValues); ZNet instance = ZNet.instance; if (instance != null) { ((MonoBehaviour)instance).StartCoroutine(sendZPackage(target, package)); } } } private static OwnConfigEntryBase? configData(ConfigEntryBase config) { return config.Description.Tags?.OfType().SingleOrDefault(); } public static SyncedConfigEntry? ConfigData(ConfigEntry config) { return ((ConfigEntryBase)config).Description.Tags?.OfType>().SingleOrDefault(); } private static T configAttribute(ConfigEntryBase config) { return config.Description.Tags.OfType().First(); } private static Type configType(ConfigEntryBase config) { return configType(config.SettingType); } private static Type configType(Type type) { return type.IsEnum ? Enum.GetUnderlyingType(type) : type; } private static ZPackage ConfigsToPackage(IEnumerable? configs = null, IEnumerable? customValues = null, IEnumerable? packageEntries = null, bool partial = true) { //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Expected O, but got Unknown List list = configs?.Where((ConfigEntryBase config) => configData(config).SynchronizedConfig).ToList() ?? new List(); List list2 = customValues?.ToList() ?? new List(); ZPackage val = new ZPackage(); val.Write((byte)(partial ? 1 : 0)); val.Write(list.Count + list2.Count + (packageEntries?.Count() ?? 0)); foreach (PackageEntry item in packageEntries ?? Array.Empty()) { AddEntryToPackage(val, item); } foreach (CustomSyncedValueBase item2 in list2) { AddEntryToPackage(val, new PackageEntry { section = "Internal", key = item2.Identifier, type = item2.Type, value = item2.BoxedValue }); } foreach (ConfigEntryBase item3 in list) { AddEntryToPackage(val, new PackageEntry { section = item3.Definition.Section, key = item3.Definition.Key, type = configType(item3), value = item3.BoxedValue }); } return val; } private static void AddEntryToPackage(ZPackage package, PackageEntry entry) { package.Write(entry.section); package.Write(entry.key); package.Write((entry.value == null) ? "" : GetZPackageTypeString(entry.type)); AddValueToZPackage(package, entry.value); } private static string GetZPackageTypeString(Type type) { return type.AssemblyQualifiedName; } private static void AddValueToZPackage(ZPackage package, object? value) { Type type = value?.GetType(); if (value is Enum) { value = ((IConvertible)value).ToType(Enum.GetUnderlyingType(value.GetType()), CultureInfo.InvariantCulture); } else { if (value is ICollection collection) { package.Write(collection.Count); { foreach (object item in collection) { AddValueToZPackage(package, item); } return; } } if ((object)type != null && type.IsValueType && !type.IsPrimitive) { FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); package.Write(fields.Length); FieldInfo[] array = fields; foreach (FieldInfo fieldInfo in array) { package.Write(GetZPackageTypeString(fieldInfo.FieldType)); AddValueToZPackage(package, fieldInfo.GetValue(value)); } return; } } ZRpc.Serialize(new object[1] { value }, ref package); } private static object ReadValueWithTypeFromZPackage(ZPackage package, Type type) { if ((object)type != null && type.IsValueType && !type.IsPrimitive && !type.IsEnum) { FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); int num = package.ReadInt(); if (num != fields.Length) { throw new InvalidDeserializationTypeException { received = $"(field count: {num})", expected = $"(field count: {fields.Length})" }; } object uninitializedObject = FormatterServices.GetUninitializedObject(type); FieldInfo[] array = fields; foreach (FieldInfo fieldInfo in array) { string text = package.ReadString(); if (text != GetZPackageTypeString(fieldInfo.FieldType)) { throw new InvalidDeserializationTypeException { received = text, expected = GetZPackageTypeString(fieldInfo.FieldType), field = fieldInfo.Name }; } fieldInfo.SetValue(uninitializedObject, ReadValueWithTypeFromZPackage(package, fieldInfo.FieldType)); } return uninitializedObject; } if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<, >)) { int num2 = package.ReadInt(); IDictionary dictionary = (IDictionary)Activator.CreateInstance(type); Type type2 = typeof(KeyValuePair<, >).MakeGenericType(type.GenericTypeArguments); FieldInfo field = type2.GetField("key", BindingFlags.Instance | BindingFlags.NonPublic); FieldInfo field2 = type2.GetField("value", BindingFlags.Instance | BindingFlags.NonPublic); for (int j = 0; j < num2; j++) { object obj = ReadValueWithTypeFromZPackage(package, type2); dictionary.Add(field.GetValue(obj), field2.GetValue(obj)); } return dictionary; } if (type != typeof(List) && type.IsGenericType) { Type type3 = typeof(ICollection<>).MakeGenericType(type.GenericTypeArguments[0]); if ((object)type3 != null && type3.IsAssignableFrom(type)) { int num3 = package.ReadInt(); object obj2 = Activator.CreateInstance(type); MethodInfo method = type3.GetMethod("Add"); for (int k = 0; k < num3; k++) { method.Invoke(obj2, new object[1] { ReadValueWithTypeFromZPackage(package, type.GenericTypeArguments[0]) }); } return obj2; } } ParameterInfo parameterInfo = (ParameterInfo)FormatterServices.GetUninitializedObject(typeof(ParameterInfo)); AccessTools.DeclaredField(typeof(ParameterInfo), "ClassImpl").SetValue(parameterInfo, type); List source = new List(); ZRpc.Deserialize(new ParameterInfo[2] { null, parameterInfo }, package, ref source); return source.First(); } } [PublicAPI] [HarmonyPatch] internal class VersionCheck { private static readonly HashSet versionChecks; private static readonly Dictionary notProcessedNames; public string Name; private string? displayName; private string? currentVersion; private string? minimumRequiredVersion; public bool ModRequired = true; private string? ReceivedCurrentVersion; private string? ReceivedMinimumRequiredVersion; private readonly List ValidatedClients = new List(); private ConfigSync? ConfigSync; public string DisplayName { get { return displayName ?? Name; } set { displayName = value; } } public string CurrentVersion { get { return currentVersion ?? "0.0.0"; } set { currentVersion = value; } } public string MinimumRequiredVersion { get { return minimumRequiredVersion ?? (ModRequired ? CurrentVersion : "0.0.0"); } set { minimumRequiredVersion = value; } } private static void PatchServerSync() { //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Expected O, but got Unknown Patches patchInfo = PatchProcessor.GetPatchInfo((MethodBase)AccessTools.DeclaredMethod(typeof(ZNet), "Awake", (Type[])null, (Type[])null)); if (patchInfo != null && patchInfo.Postfixes.Count((Patch p) => p.PatchMethod.DeclaringType == typeof(ConfigSync.RegisterRPCPatch)) > 0) { return; } Harmony val = new Harmony("org.bepinex.helpers.ServerSync"); foreach (Type item in from t in typeof(ConfigSync).GetNestedTypes(BindingFlags.NonPublic).Concat(new Type[1] { typeof(VersionCheck) }) where t.IsClass select t) { val.PatchAll(item); } } static VersionCheck() { versionChecks = new HashSet(); notProcessedNames = new Dictionary(); typeof(ThreadingHelper).GetMethod("StartSyncInvoke").Invoke(ThreadingHelper.Instance, new object[1] { new Action(PatchServerSync) }); } public VersionCheck(string name) { Name = name; ModRequired = true; versionChecks.Add(this); } public VersionCheck(ConfigSync configSync) { ConfigSync = configSync; Name = ConfigSync.Name; versionChecks.Add(this); } public void Initialize() { ReceivedCurrentVersion = null; ReceivedMinimumRequiredVersion = null; if (ConfigSync != null) { Name = ConfigSync.Name; DisplayName = ConfigSync.DisplayName; CurrentVersion = ConfigSync.CurrentVersion; MinimumRequiredVersion = ConfigSync.MinimumRequiredVersion; ModRequired = ConfigSync.ModRequired; } } private bool IsVersionOk() { if (ReceivedMinimumRequiredVersion == null || ReceivedCurrentVersion == null) { return !ModRequired; } bool flag = new Version(CurrentVersion) >= new Version(ReceivedMinimumRequiredVersion); bool flag2 = new Version(ReceivedCurrentVersion) >= new Version(MinimumRequiredVersion); return flag && flag2; } private string ErrorClient() { if (ReceivedMinimumRequiredVersion == null) { return DisplayName + " is not installed on the server."; } return (new Version(CurrentVersion) >= new Version(ReceivedMinimumRequiredVersion)) ? (DisplayName + " may not be higher than version " + ReceivedCurrentVersion + ". You have version " + CurrentVersion + ".") : (DisplayName + " needs to be at least version " + ReceivedMinimumRequiredVersion + ". You have version " + CurrentVersion + "."); } private string ErrorServer(ZRpc rpc) { return "Disconnect: The client (" + rpc.GetSocket().GetHostName() + ") doesn't have the correct " + DisplayName + " version " + MinimumRequiredVersion; } private string Error(ZRpc? rpc = null) { return (rpc == null) ? ErrorClient() : ErrorServer(rpc); } private static VersionCheck[] GetFailedClient() { return versionChecks.Where((VersionCheck check) => !check.IsVersionOk()).ToArray(); } private static VersionCheck[] GetFailedServer(ZRpc rpc) { return versionChecks.Where((VersionCheck check) => check.ModRequired && !check.ValidatedClients.Contains(rpc)).ToArray(); } private static void Logout() { Game.instance.Logout(true, true); AccessTools.DeclaredField(typeof(ZNet), "m_connectionStatus").SetValue(null, (object)(ConnectionStatus)3); } private static void DisconnectClient(ZRpc rpc) { rpc.Invoke("Error", new object[1] { 3 }); } private static void CheckVersion(ZRpc rpc, ZPackage pkg) { CheckVersion(rpc, pkg, null); } private static void CheckVersion(ZRpc rpc, ZPackage pkg, Action? original) { string text = pkg.ReadString(); string text2 = pkg.ReadString(); string text3 = pkg.ReadString(); bool flag = false; foreach (VersionCheck versionCheck in versionChecks) { if (!(text != versionCheck.Name)) { Debug.Log((object)("Received " + versionCheck.DisplayName + " version " + text3 + " and minimum version " + text2 + " from the " + (ZNet.instance.IsServer() ? "client" : "server") + ".")); versionCheck.ReceivedMinimumRequiredVersion = text2; versionCheck.ReceivedCurrentVersion = text3; if (ZNet.instance.IsServer() && versionCheck.IsVersionOk()) { versionCheck.ValidatedClients.Add(rpc); } flag = true; } } if (flag) { return; } pkg.SetPos(0); if (original != null) { original(rpc, pkg); if (pkg.GetPos() == 0) { notProcessedNames.Add(text, text3); } } } [HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")] [HarmonyPrefix] private static bool RPC_PeerInfo(ZRpc rpc, ZNet __instance) { VersionCheck[] array = (__instance.IsServer() ? GetFailedServer(rpc) : GetFailedClient()); if (array.Length == 0) { return true; } VersionCheck[] array2 = array; foreach (VersionCheck versionCheck in array2) { Debug.LogWarning((object)versionCheck.Error(rpc)); } if (__instance.IsServer()) { DisconnectClient(rpc); } else { Logout(); } return false; } [HarmonyPatch(typeof(ZNet), "OnNewConnection")] [HarmonyPrefix] private static void RegisterAndCheckVersion(ZNetPeer peer, ZNet __instance) { //IL_018e: Unknown result type (might be due to invalid IL or missing references) //IL_0195: Expected O, but got Unknown notProcessedNames.Clear(); IDictionary dictionary = (IDictionary)typeof(ZRpc).GetField("m_functions", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(peer.m_rpc); if (dictionary.Contains(StringExtensionMethods.GetStableHashCode("ServerSync VersionCheck"))) { object obj = dictionary[StringExtensionMethods.GetStableHashCode("ServerSync VersionCheck")]; Action action = (Action)obj.GetType().GetField("m_action", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(obj); peer.m_rpc.Register("ServerSync VersionCheck", (Action)delegate(ZRpc rpc, ZPackage pkg) { CheckVersion(rpc, pkg, action); }); } else { peer.m_rpc.Register("ServerSync VersionCheck", (Action)CheckVersion); } foreach (VersionCheck versionCheck in versionChecks) { versionCheck.Initialize(); if (versionCheck.ModRequired || __instance.IsServer()) { Debug.Log((object)("Sending " + versionCheck.DisplayName + " version " + versionCheck.CurrentVersion + " and minimum version " + versionCheck.MinimumRequiredVersion + " to the " + (__instance.IsServer() ? "client" : "server") + ".")); ZPackage val = new ZPackage(); val.Write(versionCheck.Name); val.Write(versionCheck.MinimumRequiredVersion); val.Write(versionCheck.CurrentVersion); peer.m_rpc.Invoke("ServerSync VersionCheck", new object[1] { val }); } } } [HarmonyPatch(typeof(ZNet), "Disconnect")] [HarmonyPrefix] private static void RemoveDisconnected(ZNetPeer peer, ZNet __instance) { if (!__instance.IsServer()) { return; } foreach (VersionCheck versionCheck in versionChecks) { versionCheck.ValidatedClients.Remove(peer.m_rpc); } } [HarmonyPatch(typeof(FejdStartup), "ShowConnectError")] [HarmonyPostfix] private static void ShowConnectionError(FejdStartup __instance) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Invalid comparison between Unknown and I4 //IL_0186: Unknown result type (might be due to invalid IL or missing references) //IL_018b: Unknown result type (might be due to invalid IL or missing references) //IL_0199: Unknown result type (might be due to invalid IL or missing references) //IL_01de: Unknown result type (might be due to invalid IL or missing references) //IL_01ea: Unknown result type (might be due to invalid IL or missing references) //IL_01f8: Unknown result type (might be due to invalid IL or missing references) //IL_020a: 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_021e: Unknown result type (might be due to invalid IL or missing references) //IL_0229: Unknown result type (might be due to invalid IL or missing references) if (!__instance.m_connectionFailedPanel.activeSelf || (int)ZNet.GetConnectionStatus() != 3) { return; } bool flag = false; VersionCheck[] failedClient = GetFailedClient(); if (failedClient.Length != 0) { string text = string.Join("\n", failedClient.Select((VersionCheck check) => check.Error())); TMP_Text connectionFailedError = __instance.m_connectionFailedError; connectionFailedError.text = connectionFailedError.text + "\n" + text; flag = true; } foreach (KeyValuePair item in notProcessedNames.OrderBy, string>((KeyValuePair kv) => kv.Key)) { if (!__instance.m_connectionFailedError.text.Contains(item.Key)) { TMP_Text connectionFailedError2 = __instance.m_connectionFailedError; connectionFailedError2.text = connectionFailedError2.text + "\nServer expects you to have " + item.Key + " (Version: " + item.Value + ") installed."; flag = true; } } if (flag) { RectTransform component = ((Component)__instance.m_connectionFailedPanel.transform.Find("Image")).GetComponent(); Vector2 sizeDelta = component.sizeDelta; sizeDelta.x = 675f; component.sizeDelta = sizeDelta; __instance.m_connectionFailedError.ForceMeshUpdate(false, false); float num = __instance.m_connectionFailedError.renderedHeight + 105f; RectTransform component2 = ((Component)((Component)component).transform.Find("ButtonOk")).GetComponent(); component2.anchoredPosition = new Vector2(component2.anchoredPosition.x, component2.anchoredPosition.y - (num - component.sizeDelta.y) / 2f); sizeDelta = component.sizeDelta; sizeDelta.y = num; component.sizeDelta = sizeDelta; } } } }