Decompiled source of Valayer of Heimordination Universal v1.1.8

plugins\Valayer.Core.dll

Decompiled 2 days ago
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = "")]
[assembly: AssemblyCompany("Valayer.Core")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.1.8.0")]
[assembly: AssemblyInformationalVersion("1.1.8")]
[assembly: AssemblyProduct("Valayer.Core")]
[assembly: AssemblyTitle("Valayer.Core")]
[assembly: AssemblyVersion("1.1.8.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace Valayer.Core
{
	internal sealed class CoreConfig
	{
		internal ConfigEntry<bool> Enabled { get; private set; }

		internal ConfigEntry<bool> DiagnosticsEnabled { get; private set; }

		internal ConfigEntry<bool> HarmonyInventoryEnabled { get; private set; }

		internal ConfigEntry<bool> WriteJsonReports { get; private set; }

		internal ConfigEntry<float> SlowCallThresholdMs { get; private set; }

		internal ConfigEntry<float> OperationTailSeconds { get; private set; }

		internal ConfigEntry<int> DiagnosticMaximumSessions { get; private set; }

		internal ConfigEntry<int> DiagnosticMaximumOperationReports { get; private set; }

		internal ConfigEntry<bool> ExperimentalDestructionCoordination { get; private set; }

		internal ConfigEntry<bool> DetailedDestructionDiagnostics { get; private set; }

		internal ConfigEntry<bool> ExperimentalDestructionIdentityTracking { get; private set; }

		internal ConfigEntry<bool> ExperimentalDestructionSpatialTracing { get; private set; }

		internal ConfigEntry<int> DestructionMaximumSpatialGroups { get; private set; }

		internal ConfigEntry<int> DestructionMaximumTrackedEvents { get; private set; }

		internal static CoreConfig Bind(ConfigFile config)
		{
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Expected O, but got Unknown
			//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e2: Expected O, but got Unknown
			//IL_0106: Unknown result type (might be due to invalid IL or missing references)
			//IL_0110: Expected O, but got Unknown
			//IL_013b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0145: Expected O, but got Unknown
			//IL_01e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ea: Expected O, but got Unknown
			//IL_0215: Unknown result type (might be due to invalid IL or missing references)
			//IL_021f: Expected O, but got Unknown
			return new CoreConfig
			{
				Enabled = config.Bind<bool>("General", "Enabled", true, "Master switch for general-purpose Valayer infrastructure."),
				DiagnosticsEnabled = config.Bind<bool>("Diagnostics", "Enabled", true, "Measure registered destruction operations without changing gameplay results."),
				HarmonyInventoryEnabled = config.Bind<bool>("Diagnostics", "HarmonyPatchInventory", true, "Record relevant live Harmony owners and patch methods after startup."),
				WriteJsonReports = config.Bind<bool>("Diagnostics", "WriteJsonReports", true, "Write machine-readable reports to Valayer's per-user application-data directory, outside the r2modman profile."),
				SlowCallThresholdMs = config.Bind<float>("Diagnostics", "SlowCallThresholdMs", 4f, new ConfigDescription("Log individual registered calls at or above this duration.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 1000f), Array.Empty<object>())),
				OperationTailSeconds = config.Bind<float>("Diagnostics", "OperationTailSeconds", 2f, new ConfigDescription("Continue attributing asynchronous work after an operation root completes.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 10f), Array.Empty<object>())),
				DiagnosticMaximumSessions = config.Bind<int>("Diagnostics", "MaximumSessions", 8, new ConfigDescription("Maximum retained Valayer diagnostic sessions per profile.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 64), Array.Empty<object>())),
				DiagnosticMaximumOperationReports = config.Bind<int>("Diagnostics", "MaximumOperationReportsPerSession", 256, new ConfigDescription("Maximum retained operation reports in the current diagnostic session.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 10000), Array.Empty<object>())),
				ExperimentalDestructionCoordination = config.Bind<bool>("Destruction", "ExperimentalDestructionCoordination", false, "EXPERIMENTAL and disabled by default: enable the operation-scoped Core realization coordinator. It does not alter authoritative gameplay when disabled."),
				DetailedDestructionDiagnostics = config.Bind<bool>("Diagnostics", "DetailedDestructionDiagnostics", false, "EXPERIMENTAL and disabled by default: collect operation-wide destruction realization metrics."),
				ExperimentalDestructionIdentityTracking = config.Bind<bool>("Diagnostics", "ExperimentalDestructionIdentityTracking", false, "EXPERIMENTAL and disabled by default: trace per-object destruction identities."),
				ExperimentalDestructionSpatialTracing = config.Bind<bool>("Diagnostics", "ExperimentalDestructionSpatialTracing", false, "EXPERIMENTAL and disabled by default: trace destruction spatial footprints."),
				DestructionMaximumSpatialGroups = config.Bind<int>("Destruction", "MaximumSpatialGroups", 256, new ConfigDescription("Bound for experimental destruction spatial groups.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 4096), Array.Empty<object>())),
				DestructionMaximumTrackedEvents = config.Bind<int>("Destruction", "MaximumTrackedEvents", 4096, new ConfigDescription("Bound for experimental destruction realization events.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 100000), Array.Empty<object>()))
			};
		}

		internal void LogEffective(ManualLogSource log)
		{
			log.LogInfo((object)("Effective core config: Enabled=" + Enabled.Value + ", Diagnostics=" + DiagnosticsEnabled.Value + ", HarmonyInventory=" + HarmonyInventoryEnabled.Value + ", JsonReports=" + WriteJsonReports.Value + ", SlowCallMs=" + SlowCallThresholdMs.Value.ToString("0.###") + ", TailSeconds=" + OperationTailSeconds.Value.ToString("0.###") + ", DestructionCoordination(experimental)=" + ExperimentalDestructionCoordination.Value + ", DetailedDestructionDiagnostics=" + DetailedDestructionDiagnostics.Value + ", IdentityTracing=" + ExperimentalDestructionIdentityTracking.Value + ", SpatialTracing=" + ExperimentalDestructionSpatialTracing.Value + "."));
		}
	}
	public static class DestructionRealizationCoordinator
	{
		public struct Summary
		{
			public int VisualEligible;

			public int VisualRealized;

			public int VisualGroups;

			public int AudioEligible;

			public int AudioRealized;

			public int AudioGroups;

			public int YieldEligible;

			public int YieldRealized;

			public int FootprintEvents;

			public float MaximumDistance;
		}

		private sealed class State
		{
			internal int OperationId;

			internal readonly HashSet<long> VisualCells = new HashSet<long>();

			internal readonly HashSet<long> AudioCells = new HashSet<long>();

			internal int VisualEligible;

			internal int VisualRealized;

			internal int AudioEligible;

			internal int AudioRealized;

			internal int YieldEligible;

			internal int YieldRealized;

			internal int FootprintEvents;

			internal float MaximumDistance;
		}

		private static readonly object Gate = new object();

		private static bool _enabled;

		private static int _maximumCells = 256;

		private static int _maximumEvents = 4096;

		private static int _nextOperation;

		private static State _current;

		public static bool Enabled
		{
			get
			{
				lock (Gate)
				{
					return _enabled;
				}
			}
		}

		internal static void Initialize(bool enabled, int maximumCells, int maximumEvents)
		{
			lock (Gate)
			{
				_enabled = enabled;
				_maximumCells = Math.Max(1, Math.Min(4096, maximumCells));
				_maximumEvents = Math.Max(1, Math.Min(100000, maximumEvents));
				_current = null;
			}
		}

		public static int Begin(string owner)
		{
			lock (Gate)
			{
				if (!_enabled || _current != null)
				{
					return 0;
				}
				_current = new State();
				_current.OperationId = ++_nextOperation;
				return _current.OperationId;
			}
		}

		public static void RecordVisual(float x, float y, float z, bool realized)
		{
			lock (Gate)
			{
				if (_enabled && _current != null && _current.VisualEligible + _current.AudioEligible < _maximumEvents)
				{
					_current.VisualEligible++;
					if (realized)
					{
						_current.VisualRealized++;
					}
					AddCell(_current.VisualCells, x, y, z);
					UpdateDistance(_current, x, y, z);
				}
			}
		}

		public static void RecordAudio(float x, float y, float z, bool realized)
		{
			lock (Gate)
			{
				if (_enabled && _current != null && _current.VisualEligible + _current.AudioEligible < _maximumEvents)
				{
					_current.AudioEligible++;
					if (realized)
					{
						_current.AudioRealized++;
					}
					AddCell(_current.AudioCells, x, y, z);
					UpdateDistance(_current, x, y, z);
				}
			}
		}

		public static void RecordYield(int eligible, int realized)
		{
			lock (Gate)
			{
				if (_enabled && _current != null)
				{
					_current.YieldEligible = Math.Min(_maximumEvents, _current.YieldEligible + Math.Max(0, eligible));
					_current.YieldRealized = Math.Min(_maximumEvents, _current.YieldRealized + Math.Max(0, realized));
				}
			}
		}

		public static void RecordFootprint(float x, float y, float z)
		{
			lock (Gate)
			{
				if (_enabled && _current != null && _current.FootprintEvents < _maximumEvents)
				{
					_current.FootprintEvents++;
					UpdateDistance(_current, x, y, z);
				}
			}
		}

		public static Summary End(int operationId)
		{
			lock (Gate)
			{
				if (!_enabled || operationId == 0 || _current == null || _current.OperationId != operationId)
				{
					return default(Summary);
				}
				State current = _current;
				_current = null;
				return new Summary
				{
					VisualEligible = current.VisualEligible,
					VisualRealized = current.VisualRealized,
					VisualGroups = current.VisualCells.Count,
					AudioEligible = current.AudioEligible,
					AudioRealized = current.AudioRealized,
					AudioGroups = current.AudioCells.Count,
					YieldEligible = current.YieldEligible,
					YieldRealized = current.YieldRealized,
					FootprintEvents = current.FootprintEvents,
					MaximumDistance = current.MaximumDistance
				};
			}
		}

		internal static void Shutdown()
		{
			lock (Gate)
			{
				_current = null;
			}
		}

		private static void AddCell(HashSet<long> cells, float x, float y, float z)
		{
			if (cells.Count < _maximumCells)
			{
				int num = (int)Math.Floor(x / 3f);
				int num2 = (int)Math.Floor(y / 3f);
				int num3 = (int)Math.Floor(z / 3f);
				long item = ((long)num * 73856093L) ^ ((long)num2 * 19349663L) ^ ((long)num3 * 83492791L);
				cells.Add(item);
			}
		}

		private static void UpdateDistance(State state, float x, float y, float z)
		{
			float num = x * x + y * y + z * z;
			float num2 = state.MaximumDistance * state.MaximumDistance;
			if (num > num2)
			{
				state.MaximumDistance = (float)Math.Sqrt(num);
			}
		}
	}
	internal static class DiagnosticFiles
	{
		internal sealed class MetricRecord
		{
			internal readonly string Name;

			internal readonly long Calls;

			internal readonly double TotalMs;

			internal readonly double MaxMs;

			internal MetricRecord(string name, long calls, double totalMs, double maxMs)
			{
				Name = name;
				Calls = calls;
				TotalMs = totalMs;
				MaxMs = maxMs;
			}
		}

		internal sealed class PatchRecord
		{
			internal readonly string Target;

			internal readonly string[] Owners;

			internal readonly string[] Prefixes;

			internal readonly string[] Postfixes;

			internal readonly string[] Transpilers;

			internal readonly string[] Finalizers;

			internal PatchRecord(string target, string[] owners, string[] prefixes, string[] postfixes, string[] transpilers, string[] finalizers)
			{
				Target = target;
				Owners = owners;
				Prefixes = prefixes;
				Postfixes = postfixes;
				Transpilers = transpilers;
				Finalizers = finalizers;
			}
		}

		internal static void WriteOperation(int id, string kind, double rootMs, string error, string reason, IEnumerable<MetricRecord> metrics)
		{
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.Append("{\n  \"schema\": 1,\n  \"kind\": \"operation-diagnostics\",");
			stringBuilder.Append("\n  \"operationId\": ").Append(id).Append(',');
			stringBuilder.Append("\n  \"operationKind\": ").Append(Quote(kind)).Append(',');
			stringBuilder.Append("\n  \"rootDurationMs\": ").Append(Number(rootMs)).Append(',');
			stringBuilder.Append("\n  \"reason\": ").Append(Quote(reason)).Append(',');
			stringBuilder.Append("\n  \"error\": ").Append((error == null) ? "null" : Quote(error)).Append(',');
			stringBuilder.Append("\n  \"metrics\": [");
			bool flag = true;
			foreach (MetricRecord metric in metrics)
			{
				if (!flag)
				{
					stringBuilder.Append(',');
				}
				flag = false;
				stringBuilder.Append("\n    {\"name\": ").Append(Quote(metric.Name)).Append(", \"calls\": ")
					.Append(metric.Calls)
					.Append(", \"totalMs\": ")
					.Append(Number(metric.TotalMs))
					.Append(", \"maxMs\": ")
					.Append(Number(metric.MaxMs))
					.Append('}');
			}
			stringBuilder.Append("\n  ]\n}\n");
			Write("operation-" + id.ToString("0000", CultureInfo.InvariantCulture) + ".json", stringBuilder.ToString());
		}

		internal static void WriteHarmonyInventory(IEnumerable<PatchRecord> records)
		{
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.Append("{\n  \"schema\": 1,\n  \"kind\": \"harmony-inventory\",\n  \"records\": [");
			bool flag = true;
			foreach (PatchRecord record in records)
			{
				if (!flag)
				{
					stringBuilder.Append(',');
				}
				flag = false;
				stringBuilder.Append("\n    {\"target\": ").Append(Quote(record.Target)).Append(", \"owners\": ")
					.Append(Array(record.Owners))
					.Append(", \"prefixes\": ")
					.Append(Array(record.Prefixes))
					.Append(", \"postfixes\": ")
					.Append(Array(record.Postfixes))
					.Append(", \"transpilers\": ")
					.Append(Array(record.Transpilers))
					.Append(", \"finalizers\": ")
					.Append(Array(record.Finalizers))
					.Append('}');
			}
			stringBuilder.Append("\n  ]\n}\n");
			Write("harmony-inventory.json", stringBuilder.ToString());
		}

		private static void Write(string name, string contents)
		{
			try
			{
				DiagnosticStorage.WriteText(name, contents);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("Could not write diagnostic report " + name + ": " + ex));
			}
		}

		private static string Array(IEnumerable<string> values)
		{
			return "[" + string.Join(", ", values.Select(Quote).ToArray()) + "]";
		}

		private static string Number(double value)
		{
			return value.ToString("0.######", CultureInfo.InvariantCulture);
		}

		private static string Quote(string value)
		{
			if (value == null)
			{
				return "null";
			}
			return "\"" + value.Replace("\\", "\\\\").Replace("\"", "\\\"").Replace("\r", "\\r")
				.Replace("\n", "\\n") + "\"";
		}
	}
	public static class DiagnosticStorage
	{
		private sealed class WriteRequest
		{
			internal readonly string Name;

			internal readonly string Contents;

			internal WriteRequest(string name, string contents)
			{
				Name = name;
				Contents = contents;
			}
		}

		private static readonly object Gate = new object();

		private static readonly ConcurrentQueue<WriteRequest> Queue = new ConcurrentQueue<WriteRequest>();

		private static readonly AutoResetEvent Wake = new AutoResetEvent(initialState: false);

		private static ManualLogSource _log;

		private static Thread _worker;

		private static volatile bool _stopping;

		private static string _sessionDirectory;

		private static int _maximumSessions;

		private static int _maximumOperationReports;

		public static string SessionDirectory
		{
			get
			{
				lock (Gate)
				{
					return _sessionDirectory;
				}
			}
		}

		internal static void Initialize(ManualLogSource log, int maximumSessions, int maximumOperationReports)
		{
			lock (Gate)
			{
				if (_worker == null)
				{
					_log = log;
					_maximumSessions = Math.Max(1, Math.Min(64, maximumSessions));
					_maximumOperationReports = Math.Max(1, Math.Min(10000, maximumOperationReports));
					string profile = ProfileDirectory();
					string text = Path.Combine(ApplicationRoot(), "profiles", ProfileIdentity(profile));
					Directory.CreateDirectory(text);
					MigrateLegacy(profile, text);
					string path = "session-" + DateTime.UtcNow.ToString("yyyyMMdd-HHmmssfff", CultureInfo.InvariantCulture) + "-" + Guid.NewGuid().ToString("N").Substring(0, 8);
					_sessionDirectory = Path.Combine(text, path);
					Directory.CreateDirectory(_sessionDirectory);
					ApplyRetention(text);
					_stopping = false;
					_worker = new Thread(WorkerLoop)
					{
						IsBackground = true,
						Name = "Valayer-DiagnosticStorage"
					};
					_worker.Start();
					if (_log != null)
					{
						_log.LogInfo((object)("Valayer diagnostics stored outside the profile at: " + _sessionDirectory));
					}
				}
			}
		}

		public static void WriteText(string fileName, string contents)
		{
			if (string.IsNullOrWhiteSpace(fileName) || contents == null)
			{
				return;
			}
			string fileName2 = Path.GetFileName(fileName);
			if (!string.Equals(fileName2, fileName, StringComparison.Ordinal) || fileName2.Length == 0)
			{
				return;
			}
			lock (Gate)
			{
				if (_worker == null || _stopping || string.IsNullOrEmpty(_sessionDirectory))
				{
					return;
				}
				Queue.Enqueue(new WriteRequest(fileName2, contents));
			}
			Wake.Set();
		}

		public static string ReadText(string fileName)
		{
			if (string.IsNullOrWhiteSpace(fileName) || Path.GetFileName(fileName) != fileName)
			{
				return null;
			}
			string path;
			lock (Gate)
			{
				if (string.IsNullOrEmpty(_sessionDirectory))
				{
					return null;
				}
				path = Path.Combine(_sessionDirectory, fileName);
			}
			try
			{
				return File.Exists(path) ? File.ReadAllText(path) : null;
			}
			catch
			{
				return null;
			}
		}

		internal static void Shutdown()
		{
			Thread worker;
			lock (Gate)
			{
				worker = _worker;
				if (worker == null)
				{
					return;
				}
				_stopping = true;
			}
			Wake.Set();
			if (worker != Thread.CurrentThread)
			{
				worker.Join(2000);
			}
			lock (Gate)
			{
				_worker = null;
			}
		}

		private static void WorkerLoop()
		{
			while (true)
			{
				if (Queue.TryDequeue(out var result))
				{
					WriteOne(result);
					continue;
				}
				if (_stopping && Queue.IsEmpty)
				{
					break;
				}
				Wake.WaitOne(250);
			}
		}

		private static void WriteOne(WriteRequest request)
		{
			try
			{
				string sessionDirectory;
				lock (Gate)
				{
					sessionDirectory = _sessionDirectory;
				}
				if (!string.IsNullOrEmpty(sessionDirectory))
				{
					Directory.CreateDirectory(sessionDirectory);
					string text = Path.Combine(sessionDirectory, request.Name);
					string text2 = text + ".writing-" + Guid.NewGuid().ToString("N");
					File.WriteAllText(text2, request.Contents, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
					if (File.Exists(text))
					{
						File.Delete(text);
					}
					File.Move(text2, text);
					if (_log != null)
					{
						_log.LogInfo((object)("Wrote diagnostic report: " + text));
					}
					if (request.Name.StartsWith("operation-", StringComparison.OrdinalIgnoreCase))
					{
						ApplyOperationRetention(sessionDirectory);
					}
				}
			}
			catch (Exception ex)
			{
				if (_log != null)
				{
					_log.LogError((object)("Could not write diagnostic report " + request.Name + ": " + ex));
				}
			}
		}

		private static void MigrateLegacy(string profile, string profileDirectory)
		{
			string[] array = new string[2]
			{
				Path.Combine(profile, "BepInEx", "diagnostics", "foundation.valayer.heimordination"),
				Path.Combine(profile, "BepInEx", "diagnostics", "foundation.valayer.heimordination.superviking")
			};
			string[] array2 = array.Where(Directory.Exists).SelectMany((string path2) => Directory.GetFiles(path2, "*", SearchOption.AllDirectories)).ToArray();
			if (array2.Length == 0)
			{
				return;
			}
			string text = Path.Combine(profileDirectory, "migrated-" + DateTime.UtcNow.ToString("yyyyMMdd-HHmmssfff", CultureInfo.InvariantCulture));
			Directory.CreateDirectory(text);
			int num = 0;
			string[] array3 = array2;
			foreach (string text2 in array3)
			{
				try
				{
					string fileName = Path.GetFileName(text2);
					string text3 = Path.Combine(text, fileName);
					if (File.Exists(text3))
					{
						text3 = Path.Combine(text, Path.GetFileNameWithoutExtension(fileName) + "-" + num + Path.GetExtension(fileName));
					}
					File.Copy(text2, text3, overwrite: false);
					if (File.Exists(text3) && new FileInfo(text3).Length == new FileInfo(text2).Length)
					{
						File.Delete(text2);
						num++;
					}
				}
				catch (Exception ex)
				{
					if (_log != null)
					{
						_log.LogWarning((object)("Could not migrate Valayer diagnostic " + text2 + ": " + ex.Message));
					}
				}
			}
			array3 = array;
			foreach (string path in array3)
			{
				try
				{
					if (Directory.Exists(path) && !Directory.EnumerateFileSystemEntries(path).Any())
					{
						Directory.Delete(path);
					}
				}
				catch
				{
				}
			}
			if (_log != null)
			{
				_log.LogInfo((object)("Migrated " + num + " Valayer diagnostic files from the profile into " + text + "."));
			}
		}

		private static void ApplyRetention(string profileDirectory)
		{
			try
			{
				DirectoryInfo[] source = (from item in new DirectoryInfo(profileDirectory).GetDirectories()
					orderby item.LastWriteTimeUtc descending
					select item).ToArray();
				foreach (DirectoryInfo item in source.Skip(_maximumSessions))
				{
					try
					{
						item.Delete(recursive: true);
					}
					catch (Exception ex)
					{
						if (_log != null)
						{
							_log.LogWarning((object)("Could not prune diagnostic session " + item.FullName + ": " + ex.Message));
						}
					}
				}
				DirectoryInfo directoryInfo = source.FirstOrDefault((DirectoryInfo item) => item.FullName == _sessionDirectory);
				if (directoryInfo != null)
				{
					ApplyOperationRetention(directoryInfo.FullName);
				}
			}
			catch (Exception ex2)
			{
				if (_log != null)
				{
					_log.LogWarning((object)("Could not apply diagnostic session retention: " + ex2.Message));
				}
			}
		}

		private static void ApplyOperationRetention(string directory)
		{
			try
			{
				foreach (FileInfo item in (from item in new DirectoryInfo(directory).GetFiles("operation-*.json")
					orderby item.LastWriteTimeUtc descending
					select item).ToArray().Skip(_maximumOperationReports))
				{
					try
					{
						item.Delete();
					}
					catch
					{
					}
				}
			}
			catch
			{
			}
		}

		private static string ProfileDirectory()
		{
			string fullPath = Path.GetFullPath(Paths.ConfigPath);
			DirectoryInfo directoryInfo = new DirectoryInfo(fullPath);
			if (directoryInfo.Parent == null || directoryInfo.Parent.Parent == null)
			{
				return fullPath;
			}
			return directoryInfo.Parent.Parent.FullName;
		}

		private static string ApplicationRoot()
		{
			string text = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
			if (string.IsNullOrEmpty(text))
			{
				text = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
			}
			if (string.IsNullOrEmpty(text))
			{
				text = Path.Combine(Path.GetTempPath(), "Valayer");
			}
			return Path.Combine(text, "Valayer", "Heimordination");
		}

		private static string ProfileIdentity(string profile)
		{
			using SHA256 sHA = SHA256.Create();
			return BitConverter.ToString(sHA.ComputeHash(Encoding.UTF8.GetBytes(profile.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar).ToUpperInvariant()))).Replace("-", string.Empty).Substring(0, 20)
				.ToLowerInvariant();
		}
	}
	internal static class HarmonyInventory
	{
		private static readonly string[] RelevantTypes = new string[14]
		{
			"MineRock", "MineRock5", "TreeBase", "TreeLog", "Destructible", "TerrainComp", "Heightmap", "ItemDrop", "EffectList", "ZNetView",
			"ZRoutedRpc", "Player", "Character", "Game"
		};

		internal static void Write(ManualLogSource log, bool writeJson)
		{
			if (!Plugin.Settings.HarmonyInventoryEnabled.Value)
			{
				return;
			}
			List<DiagnosticFiles.PatchRecord> list = new List<DiagnosticFiles.PatchRecord>();
			foreach (MethodBase item in Harmony.GetAllPatchedMethods().OrderBy(Describe))
			{
				Patches patchInfo = Harmony.GetPatchInfo(item);
				if (patchInfo == null)
				{
					continue;
				}
				string text = ((item.DeclaringType == null) ? string.Empty : item.DeclaringType.FullName);
				if (RelevantTypes.Contains(text) || text.StartsWith("SuperViking.", StringComparison.Ordinal) || text.StartsWith("Valayer.", StringComparison.Ordinal) || patchInfo.Owners.Any((string owner) => owner.StartsWith("foundation.valayer.", StringComparison.Ordinal)))
				{
					list.Add(new DiagnosticFiles.PatchRecord(Describe(item), patchInfo.Owners.OrderBy((string owner) => owner).ToArray(), DescribePatches(patchInfo.Prefixes), DescribePatches(patchInfo.Postfixes), DescribePatches(patchInfo.Transpilers), DescribePatches(patchInfo.Finalizers)));
				}
			}
			log.LogInfo((object)("Harmony inventory captured " + list.Count + " relevant patched methods."));
			foreach (DiagnosticFiles.PatchRecord item2 in list.Where((DiagnosticFiles.PatchRecord record) => record.Owners.Distinct().Count() > 1))
			{
				log.LogWarning((object)("Harmony overlap: " + item2.Target + " owners=[" + string.Join(", ", item2.Owners) + "]"));
			}
			if (writeJson)
			{
				DiagnosticFiles.WriteHarmonyInventory(list);
			}
		}

		private static string[] DescribePatches(IEnumerable<Patch> patches)
		{
			return patches.Select((Patch patch) => patch.owner + "::" + Describe(patch.PatchMethod)).ToArray();
		}

		private static string Describe(MethodBase method)
		{
			if (method == null)
			{
				return "<null>";
			}
			string text = ((method.DeclaringType == null) ? "<global>" : method.DeclaringType.FullName);
			return text + "." + method.Name + "(" + string.Join(",", (from parameter in method.GetParameters()
				select parameter.ParameterType.FullName).ToArray()) + ")";
		}
	}
	public static class OperationDiagnostics
	{
		private sealed class Metric
		{
			internal long Calls;

			internal double TotalMs;

			internal double MaxMs;
		}

		private sealed class Operation
		{
			internal int Id;

			internal string Kind;

			internal long StartedTimestamp;

			internal long RootCompletedTimestamp;

			internal double RootDurationMs;

			internal string RootError;

			internal int SlowCallLogsEmitted;

			internal long SlowCallLogsSuppressed;

			internal readonly Dictionary<string, Metric> Metrics = new Dictionary<string, Metric>();
		}

		private sealed class TargetSpec
		{
			internal readonly string TypeName;

			internal readonly string[] Methods;

			internal TargetSpec(string typeName, params string[] methods)
			{
				TypeName = typeName;
				Methods = methods;
			}
		}

		private const int MaximumIndividualSlowCallLogs = 32;

		private static readonly TargetSpec[] GeneralTargets = new TargetSpec[13]
		{
			new TargetSpec("MineRock5", "Damage", "RPC_Damage", "DamageArea", "CheckSupport", "UpdateSupport", "UpdateMesh", "SetupColliders"),
			new TargetSpec("MineRock", "Damage", "RPC_Hit"),
			new TargetSpec("TreeBase", "Damage", "RPC_Damage", "SpawnLog"),
			new TargetSpec("TreeLog", "Damage", "RPC_Damage", "Destroy"),
			new TargetSpec("Destructible", "Damage", "RPC_Damage", "Destroy", "CreateDestructionEffects"),
			new TargetSpec("TerrainComp", "DoOperation", "InternalDoOperation", "Save"),
			new TargetSpec("Heightmap", "Poke", "Regenerate", "RebuildCollisionMesh", "RebuildRenderMesh"),
			new TargetSpec("ItemDrop", "Awake", "OnCreateNew", "DropItem"),
			new TargetSpec("EffectList", "Create"),
			new TargetSpec("AudioMan", "RequestPlaySound"),
			new TargetSpec("ZSFX", "Awake", "Play"),
			new TargetSpec("ZNetView", "Awake", "InvokeRPC"),
			new TargetSpec("ZDOMan", "CreateNewZDO")
		};

		private static readonly object Gate = new object();

		private static ManualLogSource _log;

		private static Operation _current;

		private static int _nextId;

		internal static void Initialize(ManualLogSource log)
		{
			_log = log;
		}

		internal static void InstallGeneralTargets(Harmony harmony)
		{
			int num = 0;
			TargetSpec[] generalTargets = GeneralTargets;
			foreach (TargetSpec targetSpec in generalTargets)
			{
				num += RegisterTargets(harmony, targetSpec.TypeName, targetSpec.Methods);
			}
			_log.LogInfo((object)("General destruction diagnostics installed on " + num + " methods."));
		}

		public static int RegisterTargets(Harmony harmony, string typeName, params string[] methodNames)
		{
			//IL_00ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_0106: Unknown result type (might be due to invalid IL or missing references)
			//IL_0111: Expected O, but got Unknown
			//IL_0111: Expected O, but got Unknown
			if (harmony == null)
			{
				throw new ArgumentNullException("harmony");
			}
			if (string.IsNullOrEmpty(typeName))
			{
				throw new ArgumentException("Type name is required.", "typeName");
			}
			Type type = AccessTools.TypeByName(typeName);
			if (type == null)
			{
				if (_log != null)
				{
					_log.LogWarning((object)("Diagnostic type not found: " + typeName));
				}
				return 0;
			}
			int num = 0;
			foreach (string methodName in methodNames.Distinct())
			{
				MethodBase[] array = (from method in type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)
					where method.Name == methodName
					select method).Cast<MethodBase>().ToArray();
				if (array.Length == 0)
				{
					if (_log != null)
					{
						_log.LogWarning((object)("Diagnostic method not found: " + typeName + "." + methodName));
					}
					continue;
				}
				MethodBase[] array2 = array;
				foreach (MethodBase methodBase in array2)
				{
					harmony.Patch(methodBase, new HarmonyMethod(typeof(OperationDiagnostics), "ProfilePrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(OperationDiagnostics), "ProfileFinalizer", (Type[])null), (HarmonyMethod)null);
					num++;
				}
			}
			return num;
		}

		public static int Begin(string kind)
		{
			lock (Gate)
			{
				if (_current != null)
				{
					FinishLocked("superseded by a new operation");
				}
				_current = new Operation
				{
					Id = ++_nextId,
					Kind = (string.IsNullOrEmpty(kind) ? "unspecified" : kind),
					StartedTimestamp = Stopwatch.GetTimestamp()
				};
				if (_log != null)
				{
					_log.LogInfo((object)("Operation #" + _current.Id + " (" + _current.Kind + ") began."));
				}
				return _current.Id;
			}
		}

		public static void CompleteRoot(int operationId, double rootDurationMs, Exception error)
		{
			lock (Gate)
			{
				if (_current != null && _current.Id == operationId)
				{
					_current.RootDurationMs = rootDurationMs;
					_current.RootCompletedTimestamp = Stopwatch.GetTimestamp();
					_current.RootError = ((error == null) ? null : (error.GetType().FullName + ": " + error.Message));
				}
			}
		}

		public static void RecordCount(string name, long count)
		{
			if (string.IsNullOrEmpty(name) || count <= 0 || Volatile.Read(in _current) == null)
			{
				return;
			}
			lock (Gate)
			{
				if (_current != null)
				{
					if (!_current.Metrics.TryGetValue(name, out var value))
					{
						value = new Metric();
						_current.Metrics.Add(name, value);
					}
					value.Calls += count;
				}
			}
		}

		private static void ProfilePrefix(out long __state)
		{
			__state = ((Volatile.Read(in _current) == null) ? 0 : Stopwatch.GetTimestamp());
		}

		internal static string BenchmarkIdlePrefix(int iterations)
		{
			if (iterations < 1 || iterations > 10000000)
			{
				throw new ArgumentOutOfRangeException("iterations");
			}
			if (Volatile.Read(in _current) != null)
			{
				throw new InvalidOperationException("An operation is active.");
			}
			long __state;
			for (int i = 0; i < 10000; i++)
			{
				ProfilePrefix(out __state);
			}
			GC.Collect();
			GC.WaitForPendingFinalizers();
			GC.Collect();
			int num = GC.CollectionCount(0);
			long totalMemory = GC.GetTotalMemory(forceFullCollection: false);
			long timestamp = Stopwatch.GetTimestamp();
			for (int j = 0; j < iterations; j++)
			{
				ProfilePrefix(out __state);
			}
			long timestamp2 = Stopwatch.GetTimestamp();
			long totalMemory2 = GC.GetTotalMemory(forceFullCollection: false);
			int num2 = GC.CollectionCount(0);
			double num3 = (double)(timestamp2 - timestamp) * 1000000000.0 / (double)Stopwatch.Frequency / (double)iterations;
			return "{\"iterations\":" + iterations.ToString(CultureInfo.InvariantCulture) + ",\"nanosecondsPerCall\":" + num3.ToString("0.###", CultureInfo.InvariantCulture) + ",\"managedMemoryDeltaBytes\":" + (totalMemory2 - totalMemory).ToString(CultureInfo.InvariantCulture) + ",\"gen0Collections\":" + (num2 - num).ToString(CultureInfo.InvariantCulture) + "}";
		}

		private static Exception ProfileFinalizer(MethodBase __originalMethod, Exception __exception, long __state)
		{
			if (__state == 0L)
			{
				return __exception;
			}
			double num = ElapsedMs(__state);
			string text = __originalMethod.DeclaringType.FullName + "." + __originalMethod.Name;
			lock (Gate)
			{
				if (_current == null)
				{
					return __exception;
				}
				if (!_current.Metrics.TryGetValue(text, out var value))
				{
					value = new Metric();
					_current.Metrics.Add(text, value);
				}
				value.Calls++;
				value.TotalMs += num;
				value.MaxMs = Math.Max(value.MaxMs, num);
				if (_log != null && Plugin.Settings != null && num >= (double)Plugin.Settings.SlowCallThresholdMs.Value)
				{
					if (_current.SlowCallLogsEmitted < 32)
					{
						_current.SlowCallLogsEmitted++;
						_log.LogInfo((object)("Slow operation call #" + _current.Id + ": " + text + " took " + num.ToString("0.###", CultureInfo.InvariantCulture) + " ms."));
					}
					else
					{
						_current.SlowCallLogsSuppressed++;
					}
				}
			}
			return __exception;
		}

		internal static void FlushCompleted()
		{
			lock (Gate)
			{
				if (_current != null && _current.RootCompletedTimestamp != 0L && Plugin.Settings != null && ElapsedSeconds(_current.RootCompletedTimestamp) >= (double)Plugin.Settings.OperationTailSeconds.Value)
				{
					FinishLocked("tail window complete");
				}
			}
		}

		internal static void FlushNow(string reason)
		{
			lock (Gate)
			{
				if (_current != null)
				{
					FinishLocked(reason);
				}
			}
		}

		private static void FinishLocked(string reason)
		{
			Operation current = _current;
			_current = null;
			if (current == null)
			{
				return;
			}
			if (current.SlowCallLogsSuppressed > 0)
			{
				current.Metrics["Valayer.Diagnostics.SlowCallLogsSuppressed"] = new Metric
				{
					Calls = current.SlowCallLogsSuppressed
				};
			}
			KeyValuePair<string, Metric>[] array = current.Metrics.OrderByDescending((KeyValuePair<string, Metric> pair) => pair.Value.TotalMs).ToArray();
			if (_log != null)
			{
				_log.LogInfo((object)("Operation #" + current.Id + " (" + current.Kind + ") finished (" + reason + "). Root=" + current.RootDurationMs.ToString("0.###", CultureInfo.InvariantCulture) + " ms; groups=" + array.Length + ((current.RootError == null) ? "." : ("; error=" + current.RootError))));
				if (current.SlowCallLogsSuppressed > 0)
				{
					_log.LogInfo((object)("  Suppressed " + current.SlowCallLogsSuppressed + " additional individual slow-call log lines; aggregate metrics remain complete."));
				}
				KeyValuePair<string, Metric>[] array2 = array;
				for (int num = 0; num < array2.Length; num++)
				{
					KeyValuePair<string, Metric> keyValuePair = array2[num];
					_log.LogInfo((object)("  " + keyValuePair.Key + ": calls=" + keyValuePair.Value.Calls + ", total=" + keyValuePair.Value.TotalMs.ToString("0.###", CultureInfo.InvariantCulture) + " ms, max=" + keyValuePair.Value.MaxMs.ToString("0.###", CultureInfo.InvariantCulture) + " ms"));
				}
			}
			if (Plugin.Settings != null && Plugin.Settings.WriteJsonReports.Value)
			{
				DiagnosticFiles.WriteOperation(current.Id, current.Kind, current.RootDurationMs, current.RootError, reason, array.Select((KeyValuePair<string, Metric> pair) => new DiagnosticFiles.MetricRecord(pair.Key, pair.Value.Calls, pair.Value.TotalMs, pair.Value.MaxMs)));
			}
		}

		private static double ElapsedMs(long timestamp)
		{
			return (double)(Stopwatch.GetTimestamp() - timestamp) * 1000.0 / (double)Stopwatch.Frequency;
		}

		private static double ElapsedSeconds(long timestamp)
		{
			return (double)(Stopwatch.GetTimestamp() - timestamp) / (double)Stopwatch.Frequency;
		}
	}
	[BepInPlugin("foundation.valayer.heimordination", "Valayer of Heimordination", "1.1.8")]
	[BepInProcess("valheim.exe")]
	[BepInProcess("valheim_server.exe")]
	public sealed class Plugin : BaseUnityPlugin
	{
		public const string PluginGuid = "foundation.valayer.heimordination";

		public const string PluginName = "Valayer of Heimordination";

		public const string PluginVersion = "1.1.8";

		private Harmony _harmony;

		private bool _startupReportWritten;

		internal static ManualLogSource Log { get; private set; }

		internal static CoreConfig Settings { get; private set; }

		private void Awake()
		{
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Expected O, but got Unknown
			Log = ((BaseUnityPlugin)this).Logger;
			Settings = CoreConfig.Bind(((BaseUnityPlugin)this).Config);
			Settings.LogEffective(Log);
			DiagnosticStorage.Initialize(Log, Settings.DiagnosticMaximumSessions.Value, Settings.DiagnosticMaximumOperationReports.Value);
			DestructionRealizationCoordinator.Initialize(Settings.ExperimentalDestructionCoordination.Value, Settings.DestructionMaximumSpatialGroups.Value, Settings.DestructionMaximumTrackedEvents.Value);
			if (!Settings.Enabled.Value)
			{
				Log.LogInfo((object)"Valayer Core disabled by [General] Enabled.");
				return;
			}
			_harmony = new Harmony("foundation.valayer.heimordination");
			if (Settings.DiagnosticsEnabled.Value)
			{
				OperationDiagnostics.Initialize(Log);
				OperationDiagnostics.InstallGeneralTargets(_harmony);
			}
			Log.LogInfo((object)"Valayer of Heimordination 1.1.8 loaded. Core has no SuperViking or Jotunn runtime dependency.");
		}

		private void Start()
		{
			WriteStartupReport();
		}

		private void Update()
		{
			if (_harmony != null && Settings.DiagnosticsEnabled.Value)
			{
				OperationDiagnostics.FlushCompleted();
				if (!_startupReportWritten)
				{
					WriteStartupReport();
				}
			}
		}

		private void WriteStartupReport()
		{
			if (!_startupReportWritten && _harmony != null && Settings.DiagnosticsEnabled.Value)
			{
				_startupReportWritten = true;
				HarmonyInventory.Write(Log, Settings.WriteJsonReports.Value);
			}
		}

		private void OnDestroy()
		{
			OperationDiagnostics.FlushNow("core shutdown");
			DestructionRealizationCoordinator.Shutdown();
			DiagnosticStorage.Shutdown();
			if (_harmony != null)
			{
				_harmony.UnpatchSelf();
				_harmony = null;
			}
		}
	}
}
namespace Valayer.Core.Temporal
{
	public enum TemporalAuthorityRequestResult
	{
		Accepted,
		RejectedInvalid,
		RejectedStale,
		RejectedRate,
		RejectedCapacity
	}
	public sealed class TemporalAuthorityRequestGate
	{
		private struct RequestKey : IEquatable<RequestKey>
		{
			internal long OwnerId;

			internal int FieldId;

			public bool Equals(RequestKey other)
			{
				if (OwnerId == other.OwnerId)
				{
					return FieldId == other.FieldId;
				}
				return false;
			}

			public override bool Equals(object value)
			{
				if (value is RequestKey)
				{
					return Equals((RequestKey)value);
				}
				return false;
			}

			public override int GetHashCode()
			{
				return (OwnerId.GetHashCode() * 397) ^ FieldId;
			}
		}

		private sealed class RequestState
		{
			internal int Sequence;

			internal bool Active;

			internal float LastAcceptedAt;

			internal float ExpiresAt;
		}

		private readonly Dictionary<RequestKey, RequestState> _states = new Dictionary<RequestKey, RequestState>();

		private readonly List<RequestKey> _removeBuffer = new List<RequestKey>();

		public int TrackedCount => _states.Count;

		public int ActiveCount
		{
			get
			{
				int num = 0;
				foreach (RequestState value in _states.Values)
				{
					if (value.Active)
					{
						num++;
					}
				}
				return num;
			}
		}

		public TemporalAuthorityRequestResult Receive(long authenticatedOwnerId, int fieldId, int sequence, bool active, float now, float activeLifetimeSeconds)
		{
			Expire(now);
			if (authenticatedOwnerId == 0L || fieldId == 0 || !IsFinite(now) || !IsFinite(activeLifetimeSeconds) || activeLifetimeSeconds <= 0f || activeLifetimeSeconds > 10f)
			{
				return TemporalAuthorityRequestResult.RejectedInvalid;
			}
			RequestKey key = new RequestKey
			{
				OwnerId = authenticatedOwnerId,
				FieldId = fieldId
			};
			RequestState value;
			bool flag = _states.TryGetValue(key, out value);
			if (flag && !TemporalFieldRules.ShouldAccept(hasState: true, value.Sequence, sequence))
			{
				return TemporalAuthorityRequestResult.RejectedStale;
			}
			float num = 0.1f;
			if (active && flag && now - value.LastAcceptedAt + 1E-06f < num)
			{
				return TemporalAuthorityRequestResult.RejectedRate;
			}
			if (!flag)
			{
				if (active && ActiveCount >= 32)
				{
					return TemporalAuthorityRequestResult.RejectedCapacity;
				}
				if (_states.Count >= 64 && !EvictOldestInactive())
				{
					return TemporalAuthorityRequestResult.RejectedCapacity;
				}
				value = new RequestState();
				_states.Add(key, value);
			}
			else if (!value.Active && active && ActiveCount >= 32)
			{
				return TemporalAuthorityRequestResult.RejectedCapacity;
			}
			value.Sequence = sequence;
			value.Active = active;
			value.LastAcceptedAt = now;
			value.ExpiresAt = now + (active ? activeLifetimeSeconds : 5f);
			return TemporalAuthorityRequestResult.Accepted;
		}

		public void RemoveOwner(long ownerId)
		{
			_removeBuffer.Clear();
			foreach (RequestKey key in _states.Keys)
			{
				if (key.OwnerId == ownerId)
				{
					_removeBuffer.Add(key);
				}
			}
			for (int i = 0; i < _removeBuffer.Count; i++)
			{
				_states.Remove(_removeBuffer[i]);
			}
		}

		public void RemoveDisconnected(Predicate<long> isConnected)
		{
			if (isConnected == null)
			{
				return;
			}
			_removeBuffer.Clear();
			foreach (RequestKey key in _states.Keys)
			{
				if (!isConnected(key.OwnerId))
				{
					_removeBuffer.Add(key);
				}
			}
			for (int i = 0; i < _removeBuffer.Count; i++)
			{
				_states.Remove(_removeBuffer[i]);
			}
		}

		public void Expire(float now)
		{
			if (!IsFinite(now))
			{
				return;
			}
			_removeBuffer.Clear();
			foreach (KeyValuePair<RequestKey, RequestState> state in _states)
			{
				RequestState value = state.Value;
				if (!(now < value.ExpiresAt))
				{
					if (value.Active)
					{
						value.Active = false;
						value.ExpiresAt = now + 5f;
					}
					else
					{
						_removeBuffer.Add(state.Key);
					}
				}
			}
			for (int i = 0; i < _removeBuffer.Count; i++)
			{
				_states.Remove(_removeBuffer[i]);
			}
		}

		public void Clear()
		{
			_states.Clear();
		}

		private bool EvictOldestInactive()
		{
			bool flag = false;
			RequestKey key = default(RequestKey);
			float num = float.MaxValue;
			foreach (KeyValuePair<RequestKey, RequestState> state in _states)
			{
				if (!state.Value.Active && state.Value.LastAcceptedAt < num)
				{
					flag = true;
					num = state.Value.LastAcceptedAt;
					key = state.Key;
				}
			}
			if (flag)
			{
				return _states.Remove(key);
			}
			return false;
		}

		private static bool IsFinite(float value)
		{
			if (!float.IsNaN(value))
			{
				return !float.IsInfinity(value);
			}
			return false;
		}
	}
	public enum TemporalAudience
	{
		Everybody,
		OwnerOnly,
		OthersOnly
	}
	public enum TemporalEntityKind
	{
		Creature,
		Projectile
	}
	public enum TemporalDomainShape
	{
		Box,
		Sphere
	}
	public enum TemporalRelation
	{
		Unknown,
		Self,
		Ally,
		Neutral,
		Hostile
	}
	[Flags]
	public enum TemporalInteractionPermissions
	{
		None = 0,
		HostileCreatures = 1,
		NeutralCreatures = 2,
		AlliedCreatures = 4,
		HostileProjectiles = 8,
		NeutralProjectiles = 0x10,
		AlliedProjectiles = 0x20,
		OwnProjectiles = 0x40
	}
	public enum TemporalReceiveResult
	{
		Accepted,
		RejectedProtocol,
		RejectedInvalid,
		RejectedStale,
		RejectedCapacity
	}
	public struct TemporalPoint
	{
		public float X;

		public float Y;

		public float Z;

		public TemporalPoint(float x, float y, float z)
		{
			X = x;
			Y = y;
			Z = z;
		}
	}
	public struct TemporalFieldPacket
	{
		public int ProtocolVersion;

		public int FieldId;

		public int Sequence;

		public long OwnerId;

		public long AuthorityId;

		public int PolicyRevision;

		public int PrecedenceRank;

		public bool Active;

		public TemporalPoint Center;

		public TemporalDomainShape Shape;

		public TemporalPoint Dimensions;

		public float TimeScale;

		public float SimulationResolutionHz;

		public float LifetimeSeconds;

		public TemporalAudience Audience;

		public TemporalInteractionPermissions Permissions;
	}
	public struct TemporalEvaluation
	{
		public float TimeScale;

		public int ContributingFields;

		public float SimulationResolutionHz;

		internal TemporalEvaluation(float timeScale, int contributingFields, float simulationResolutionHz = 50f)
		{
			TimeScale = timeScale;
			ContributingFields = contributingFields;
			SimulationResolutionHz = simulationResolutionHz;
		}
	}
	public static class TemporalFieldRules
	{
		public const int ProtocolVersion = 4;

		public const int MaximumActiveFields = 32;

		public const int MaximumTrackedStates = 64;

		public const float MinimumDimension = 1f;

		public const float MaximumDimension = 400f;

		public const float MinimumTimeScale = 0.05f;

		public const float MaximumLifetimeSeconds = 10f;

		public const float MinimumSimulationResolutionHz = 10f;

		public const float MaximumSimulationResolutionHz = 50f;

		public const float StopTombstoneSeconds = 5f;

		public const float MaximumUpdatesPerSecondPerField = 10f;

		public const TemporalInteractionPermissions AllPermissions = TemporalInteractionPermissions.HostileCreatures | TemporalInteractionPermissions.NeutralCreatures | TemporalInteractionPermissions.AlliedCreatures | TemporalInteractionPermissions.HostileProjectiles | TemporalInteractionPermissions.NeutralProjectiles | TemporalInteractionPermissions.AlliedProjectiles | TemporalInteractionPermissions.OwnProjectiles;

		public static bool IsValid(TemporalFieldPacket packet)
		{
			if (packet.ProtocolVersion != 4 || packet.FieldId == 0 || packet.AuthorityId == 0L || packet.OwnerId == 0L || packet.PolicyRevision <= 0 || packet.PrecedenceRank < 0)
			{
				return false;
			}
			if (!packet.Active)
			{
				return true;
			}
			if (IsFinite(packet.Center.X) && IsFinite(packet.Center.Y) && IsFinite(packet.Center.Z) && Enum.IsDefined(typeof(TemporalDomainShape), packet.Shape) && IsValidDimension(packet.Dimensions.X) && IsValidDimension(packet.Dimensions.Y) && IsValidDimension(packet.Dimensions.Z) && (packet.Shape != TemporalDomainShape.Sphere || (packet.Dimensions.X == packet.Dimensions.Y && packet.Dimensions.X == packet.Dimensions.Z)) && IsFinite(packet.TimeScale) && packet.TimeScale >= 0.05f && packet.TimeScale <= 1f && IsFinite(packet.SimulationResolutionHz) && packet.SimulationResolutionHz >= 10f && packet.SimulationResolutionHz <= 50f && IsFinite(packet.LifetimeSeconds) && packet.LifetimeSeconds > 0f && packet.LifetimeSeconds <= 10f && Enum.IsDefined(typeof(TemporalAudience), packet.Audience))
			{
				return (packet.Permissions & ~(TemporalInteractionPermissions.HostileCreatures | TemporalInteractionPermissions.NeutralCreatures | TemporalInteractionPermissions.AlliedCreatures | TemporalInteractionPermissions.HostileProjectiles | TemporalInteractionPermissions.NeutralProjectiles | TemporalInteractionPermissions.AlliedProjectiles | TemporalInteractionPermissions.OwnProjectiles)) == 0;
			}
			return false;
		}

		public static bool ShouldAccept(bool hasState, int currentSequence, int incomingSequence)
		{
			if (hasState)
			{
				return incomingSequence - currentSequence > 0;
			}
			return true;
		}

		public static bool Contains(TemporalFieldPacket packet, TemporalPoint subject)
		{
			float num = subject.X - packet.Center.X;
			float num2 = subject.Y - packet.Center.Y;
			float num3 = subject.Z - packet.Center.Z;
			if (packet.Shape == TemporalDomainShape.Sphere)
			{
				float num4 = packet.Dimensions.X * 0.5f;
				return num * num + num2 * num2 + num3 * num3 <= num4 * num4;
			}
			if (Math.Abs(num) <= packet.Dimensions.X * 0.5f && Math.Abs(num2) <= packet.Dimensions.Y * 0.5f)
			{
				return Math.Abs(num3) <= packet.Dimensions.Z * 0.5f;
			}
			return false;
		}

		public static bool Affects(TemporalAudience audience, long ownerId, long subjectId)
		{
			return audience switch
			{
				TemporalAudience.OwnerOnly => ownerId == subjectId, 
				TemporalAudience.OthersOnly => ownerId != subjectId, 
				_ => true, 
			};
		}

		public static bool AffectsEntity(TemporalInteractionPermissions permissions, TemporalEntityKind kind, TemporalRelation relation)
		{
			TemporalInteractionPermissions temporalInteractionPermissions;
			switch (kind)
			{
			case TemporalEntityKind.Projectile:
				switch (relation)
				{
				case TemporalRelation.Self:
					temporalInteractionPermissions = TemporalInteractionPermissions.OwnProjectiles;
					break;
				case TemporalRelation.Ally:
					temporalInteractionPermissions = TemporalInteractionPermissions.AlliedProjectiles;
					break;
				case TemporalRelation.Neutral:
					temporalInteractionPermissions = TemporalInteractionPermissions.NeutralProjectiles;
					break;
				case TemporalRelation.Hostile:
					temporalInteractionPermissions = TemporalInteractionPermissions.HostileProjectiles;
					break;
				default:
					return false;
				}
				break;
			case TemporalEntityKind.Creature:
				switch (relation)
				{
				case TemporalRelation.Self:
				case TemporalRelation.Ally:
					temporalInteractionPermissions = TemporalInteractionPermissions.AlliedCreatures;
					break;
				case TemporalRelation.Neutral:
					temporalInteractionPermissions = TemporalInteractionPermissions.NeutralCreatures;
					break;
				case TemporalRelation.Hostile:
					temporalInteractionPermissions = TemporalInteractionPermissions.HostileCreatures;
					break;
				default:
					return false;
				}
				break;
			default:
				return false;
			}
			return (permissions & temporalInteractionPermissions) != 0;
		}

		private static bool IsFinite(float value)
		{
			if (!float.IsNaN(value))
			{
				return !float.IsInfinity(value);
			}
			return false;
		}

		private static bool IsValidDimension(float value)
		{
			if (IsFinite(value) && value >= 1f)
			{
				return value <= 400f;
			}
			return false;
		}
	}
	public static class TemporalCompatibilityRules
	{
		public const int CapabilityProtocolVersion = 1;

		public const float MaximumCapabilityAgeSeconds = 7f;

		public static bool IsCompatible(int temporalProtocol, bool enabled, float ageSeconds)
		{
			if (temporalProtocol == 4 && enabled && !float.IsNaN(ageSeconds) && !float.IsInfinity(ageSeconds) && ageSeconds >= 0f)
			{
				return ageSeconds <= 7f;
			}
			return false;
		}
	}
	public enum TemporalCirclePlane
	{
		XY,
		XZ,
		YZ
	}
	public static class TemporalDomainGeometry
	{
		public const int BoxCornerCount = 8;

		public const int BoxEdgeCount = 12;

		private static readonly int[] EdgeCorners = new int[24]
		{
			0, 1, 1, 2, 2, 3, 3, 0, 4, 5,
			5, 6, 6, 7, 7, 4, 0, 4, 1, 5,
			2, 6, 3, 7
		};

		public static TemporalPoint BoxCorner(TemporalPoint dimensions, int index)
		{
			if (index < 0 || index >= 8)
			{
				throw new ArgumentOutOfRangeException("index");
			}
			float num = dimensions.X * 0.5f;
			float num2 = dimensions.Y * 0.5f;
			float num3 = dimensions.Z * 0.5f;
			return index switch
			{
				0 => new TemporalPoint(0f - num, 0f - num2, 0f - num3), 
				1 => new TemporalPoint(num, 0f - num2, 0f - num3), 
				2 => new TemporalPoint(num, 0f - num2, num3), 
				3 => new TemporalPoint(0f - num, 0f - num2, num3), 
				4 => new TemporalPoint(0f - num, num2, 0f - num3), 
				5 => new TemporalPoint(num, num2, 0f - num3), 
				6 => new TemporalPoint(num, num2, num3), 
				_ => new TemporalPoint(0f - num, num2, num3), 
			};
		}

		public static int BoxEdgeCorner(int edge, bool end)
		{
			if (edge < 0 || edge >= 12)
			{
				throw new ArgumentOutOfRangeException("edge");
			}
			return EdgeCorners[edge * 2 + (end ? 1 : 0)];
		}

		public static TemporalPoint SpherePoint(float diameter, TemporalCirclePlane plane, float radians)
		{
			float num = diameter * 0.5f;
			float num2 = (float)Math.Cos(radians) * num;
			float num3 = (float)Math.Sin(radians) * num;
			return plane switch
			{
				TemporalCirclePlane.XY => new TemporalPoint(num2, num3, 0f), 
				TemporalCirclePlane.XZ => new TemporalPoint(num2, 0f, num3), 
				_ => new TemporalPoint(0f, num2, num3), 
			};
		}
	}
	public delegate TemporalRelation TemporalRelationResolver(long fieldOwnerId);
	public sealed class TemporalFieldRegistry
	{
		private struct FieldKey : IEquatable<FieldKey>
		{
			internal long OwnerId;

			internal int FieldId;

			public bool Equals(FieldKey other)
			{
				if (OwnerId == other.OwnerId)
				{
					return FieldId == other.FieldId;
				}
				return false;
			}

			public override bool Equals(object value)
			{
				if (value is FieldKey)
				{
					return Equals((FieldKey)value);
				}
				return false;
			}

			public override int GetHashCode()
			{
				return (OwnerId.GetHashCode() * 397) ^ FieldId;
			}
		}

		private sealed class FieldState
		{
			internal int Sequence;

			internal bool Active;

			internal TemporalFieldPacket Packet;

			internal float ExpiresAt;

			internal float LastChangedAt;
		}

		private readonly Dictionary<FieldKey, FieldState> _states = new Dictionary<FieldKey, FieldState>();

		private readonly List<FieldKey> _removeBuffer = new List<FieldKey>();

		private float _nextExpiryAt = float.PositiveInfinity;

		private long _authorityId;

		private int _policyRevision;

		public int ActiveCount
		{
			get
			{
				int num = 0;
				foreach (FieldState value in _states.Values)
				{
					if (value.Active)
					{
						num++;
					}
				}
				return num;
			}
		}

		public int TrackedCount => _states.Count;

		public long AuthorityId => _authorityId;

		public int PolicyRevision => _policyRevision;

		public TemporalReceiveResult Receive(long authenticatedAuthorityId, TemporalFieldPacket packet, float now)
		{
			Expire(now);
			if (packet.ProtocolVersion != 4)
			{
				return TemporalReceiveResult.RejectedProtocol;
			}
			if (!TemporalFieldRules.IsValid(packet) || packet.AuthorityId != authenticatedAuthorityId || !IsFinite(now) || (_authorityId != 0L && _authorityId != authenticatedAuthorityId))
			{
				return TemporalReceiveResult.RejectedInvalid;
			}
			if (packet.PolicyRevision < _policyRevision)
			{
				return TemporalReceiveResult.RejectedStale;
			}
			if (_authorityId == 0L)
			{
				_authorityId = authenticatedAuthorityId;
			}
			if (packet.PolicyRevision > _policyRevision)
			{
				_states.Clear();
				_nextExpiryAt = float.PositiveInfinity;
				_policyRevision = packet.PolicyRevision;
			}
			FieldKey key = new FieldKey
			{
				OwnerId = packet.OwnerId,
				FieldId = packet.FieldId
			};
			FieldState value;
			bool flag = _states.TryGetValue(key, out value);
			if (!TemporalFieldRules.ShouldAccept(flag, flag ? value.Sequence : 0, packet.Sequence))
			{
				return TemporalReceiveResult.RejectedStale;
			}
			if (!flag)
			{
				if (packet.Active && ActiveCount >= 32)
				{
					return TemporalReceiveResult.RejectedCapacity;
				}
				if (_states.Count >= 64 && !EvictOldestTombstone())
				{
					return TemporalReceiveResult.RejectedCapacity;
				}
				value = new FieldState();
				_states.Add(key, value);
			}
			else if (!value.Active && packet.Active && ActiveCount >= 32)
			{
				return TemporalReceiveResult.RejectedCapacity;
			}
			value.Sequence = packet.Sequence;
			value.Active = packet.Active;
			value.Packet = packet;
			value.LastChangedAt = now;
			value.ExpiresAt = now + (packet.Active ? packet.LifetimeSeconds : 5f);
			if (value.ExpiresAt < _nextExpiryAt)
			{
				_nextExpiryAt = value.ExpiresAt;
			}
			return TemporalReceiveResult.Accepted;
		}

		public TemporalEvaluation Evaluate(TemporalPoint subject, long subjectId, bool independentlyEligible, float now)
		{
			Expire(now);
			return new TemporalEvaluation(1f, 0);
		}

		public TemporalEvaluation EvaluateEntity(TemporalPoint subject, TemporalEntityKind kind, bool independentlyEligible, TemporalRelationResolver resolveRelation, float now)
		{
			Expire(now);
			if (!independentlyEligible || resolveRelation == null || !IsFinite(subject.X) || !IsFinite(subject.Y) || !IsFinite(subject.Z))
			{
				return new TemporalEvaluation(1f, 0);
			}
			float timeScale = 1f;
			int num = 0;
			int num2 = int.MaxValue;
			long num3 = long.MaxValue;
			int num4 = int.MaxValue;
			float simulationResolutionHz = 50f;
			foreach (FieldState value in _states.Values)
			{
				TemporalFieldPacket packet = value.Packet;
				if (value.Active && TemporalFieldRules.Contains(packet, subject) && TemporalFieldRules.AffectsEntity(packet.Permissions, kind, resolveRelation(packet.OwnerId)))
				{
					num++;
					if (packet.PrecedenceRank < num2 || (packet.PrecedenceRank == num2 && packet.OwnerId < num3) || (packet.PrecedenceRank == num2 && packet.OwnerId == num3 && packet.FieldId < num4))
					{
						num2 = packet.PrecedenceRank;
						num3 = packet.OwnerId;
						num4 = packet.FieldId;
						timeScale = packet.TimeScale;
						simulationResolutionHz = packet.SimulationResolutionHz;
					}
				}
			}
			return new TemporalEvaluation(timeScale, num, simulationResolutionHz);
		}

		public void RemoveSender(long ownerId)
		{
			List<FieldKey> list = new List<FieldKey>();
			foreach (FieldKey key in _states.Keys)
			{
				if (key.OwnerId == ownerId)
				{
					list.Add(key);
				}
			}
			for (int i = 0; i < list.Count; i++)
			{
				_states.Remove(list[i]);
			}
			RecalculateNextExpiry();
		}

		public void Clear()
		{
			_states.Clear();
			_nextExpiryAt = float.PositiveInfinity;
			_authorityId = 0L;
			_policyRevision = 0;
		}

		public void Expire(float now)
		{
			if (!IsFinite(now) || now < _nextExpiryAt)
			{
				return;
			}
			_removeBuffer.Clear();
			_nextExpiryAt = float.PositiveInfinity;
			foreach (KeyValuePair<FieldKey, FieldState> state in _states)
			{
				FieldState value = state.Value;
				if (now >= value.ExpiresAt)
				{
					if (!value.Active)
					{
						_removeBuffer.Add(state.Key);
						continue;
					}
					value.Active = false;
					value.Packet.Active = false;
					value.LastChangedAt = now;
					value.ExpiresAt = now + 5f;
				}
				if (value.ExpiresAt < _nextExpiryAt)
				{
					_nextExpiryAt = value.ExpiresAt;
				}
			}
			for (int i = 0; i < _removeBuffer.Count; i++)
			{
				_states.Remove(_removeBuffer[i]);
			}
		}

		private bool EvictOldestTombstone()
		{
			bool flag = false;
			FieldKey key = default(FieldKey);
			float num = float.MaxValue;
			foreach (KeyValuePair<FieldKey, FieldState> state in _states)
			{
				if (!state.Value.Active && state.Value.LastChangedAt < num)
				{
					flag = true;
					num = state.Value.LastChangedAt;
					key = state.Key;
				}
			}
			if (flag)
			{
				return _states.Remove(key);
			}
			return false;
		}

		private void RecalculateNextExpiry()
		{
			_nextExpiryAt = float.PositiveInfinity;
			foreach (FieldState value in _states.Values)
			{
				if (value.ExpiresAt < _nextExpiryAt)
				{
					_nextExpiryAt = value.ExpiresAt;
				}
			}
		}

		private static bool IsFinite(float value)
		{
			if (!float.IsNaN(value))
			{
				return !float.IsInfinity(value);
			}
			return false;
		}
	}
	public static class TemporalStepAdmission
	{
		public static bool ShouldAdvance(float timeScale, ref float accumulator)
		{
			if (float.IsNaN(timeScale) || float.IsInfinity(timeScale) || timeScale >= 1f)
			{
				accumulator = 0f;
				return true;
			}
			if (timeScale < 0.05f)
			{
				timeScale = 0.05f;
			}
			accumulator += timeScale;
			if (accumulator + 1E-06f < 1f)
			{
				return false;
			}
			accumulator -= 1f;
			return true;
		}
	}
}
namespace Valayer.Core.Representation
{
	public enum SharedActionPhase
	{
		Idle,
		Preparing,
		Holding,
		Executing,
		Recovery,
		Interrupted
	}
	public enum SharedActionReceiveResult
	{
		Accepted,
		RejectedProtocol,
		RejectedInvalid,
		RejectedUnauthenticated,
		RejectedStale,
		RejectedTransition,
		RejectedCapacity
	}
	public struct SharedActionPacket
	{
		public int ProtocolVersion;

		public long ActorId;

		public uint ActorObjectId;

		public int ActionKind;

		public int ActionId;

		public int Sequence;

		public SharedActionPhase Phase;

		public long TargetOwnerId;

		public uint TargetObjectId;

		public float LifetimeSeconds;
	}
	public struct SharedActionSnapshot
	{
		public SharedActionPacket Packet;

		public float ReceivedAt;
	}
	public static class SharedActionProtocol
	{
		public const int ProtocolVersion = 1;

		public const int MaximumTrackedActions = 32;

		public const float MinimumLifetimeSeconds = 0.5f;

		public const float MaximumLifetimeSeconds = 5f;

		public static bool IsValid(SharedActionPacket packet)
		{
			if (packet.ProtocolVersion == 1 && packet.ActorId != 0L && packet.ActorObjectId != 0 && packet.ActionKind > 0 && packet.ActionId != 0 && packet.Sequence > 0 && Enum.IsDefined(typeof(SharedActionPhase), packet.Phase) && packet.LifetimeSeconds >= 0.5f && packet.LifetimeSeconds <= 5f)
			{
				if (packet.Phase != SharedActionPhase.Preparing && (packet.TargetOwnerId == 0L || packet.TargetObjectId == 0) && packet.Phase != SharedActionPhase.Interrupted && packet.Phase != SharedActionPhase.Recovery)
				{
					return packet.Phase == SharedActionPhase.Idle;
				}
				return true;
			}
			return false;
		}

		public static bool IsNewer(int current, int incoming)
		{
			return incoming - current > 0;
		}

		public static bool CanTransition(SharedActionPhase current, SharedActionPhase next)
		{
			if (current == next)
			{
				return true;
			}
			switch (current)
			{
			case SharedActionPhase.Preparing:
				if (next != SharedActionPhase.Holding)
				{
					return next == SharedActionPhase.Interrupted;
				}
				return true;
			case SharedActionPhase.Holding:
				if (next != SharedActionPhase.Executing)
				{
					return next == SharedActionPhase.Interrupted;
				}
				return true;
			case SharedActionPhase.Executing:
				if (next != SharedActionPhase.Recovery)
				{
					return next == SharedActionPhase.Interrupted;
				}
				return true;
			case SharedActionPhase.Idle:
			case SharedActionPhase.Recovery:
			case SharedActionPhase.Interrupted:
				if (next != SharedActionPhase.Preparing)
				{
					return next == SharedActionPhase.Idle;
				}
				return true;
			default:
				return false;
			}
		}
	}
	public sealed class SharedActionRegistry
	{
		private struct Key : IEquatable<Key>
		{
			internal long Actor;

			internal int Kind;

			public bool Equals(Key other)
			{
				if (Actor == other.Actor)
				{
					return Kind == other.Kind;
				}
				return false;
			}

			public override bool Equals(object value)
			{
				if (value is Key)
				{
					return Equals((Key)value);
				}
				return false;
			}

			public override int GetHashCode()
			{
				return ((int)Actor * 397) ^ Kind;
			}
		}

		private readonly Dictionary<Key, SharedActionSnapshot> _states = new Dictionary<Key, SharedActionSnapshot>();

		public int Count => _states.Count;

		public SharedActionReceiveResult Receive(long authenticatedSender, SharedActionPacket packet, float now)
		{
			if (packet.ProtocolVersion != 1)
			{
				return SharedActionReceiveResult.RejectedProtocol;
			}
			if (!SharedActionProtocol.IsValid(packet))
			{
				return SharedActionReceiveResult.RejectedInvalid;
			}
			if (authenticatedSender == 0L || packet.ActorId != authenticatedSender)
			{
				return SharedActionReceiveResult.RejectedUnauthenticated;
			}
			Key key = new Key
			{
				Actor = packet.ActorId,
				Kind = packet.ActionKind
			};
			if (_states.TryGetValue(key, out var value))
			{
				if (packet.ActionId == value.Packet.ActionId)
				{
					if (!SharedActionProtocol.IsNewer(value.Packet.Sequence, packet.Sequence))
					{
						return SharedActionReceiveResult.RejectedStale;
					}
					if (!SharedActionProtocol.CanTransition(value.Packet.Phase, packet.Phase))
					{
						return SharedActionReceiveResult.RejectedTransition;
					}
				}
				else if (!SharedActionProtocol.IsNewer(value.Packet.ActionId, packet.ActionId))
				{
					return SharedActionReceiveResult.RejectedStale;
				}
			}
			else if (_states.Count >= 32)
			{
				return SharedActionReceiveResult.RejectedCapacity;
			}
			_states[key] = new SharedActionSnapshot
			{
				Packet = packet,
				ReceivedAt = now
			};
			return SharedActionReceiveResult.Accepted;
		}

		public bool TryGet(long actorId, int actionKind, out SharedActionSnapshot snapshot)
		{
			return _states.TryGetValue(new Key
			{
				Actor = actorId,
				Kind = actionKind
			}, out snapshot);
		}

		public int Expire(float now)
		{
			List<Key> list = new List<Key>();
			foreach (KeyValuePair<Key, SharedActionSnapshot> state in _states)
			{
				if (now - state.Value.ReceivedAt > state.Value.Packet.LifetimeSeconds)
				{
					list.Add(state.Key);
				}
			}
			foreach (Key item in list)
			{
				_states.Remove(item);
			}
			return list.Count;
		}

		public int RemoveActor(long actorId)
		{
			List<Key> list = new List<Key>();
			foreach (KeyValuePair<Key, SharedActionSnapshot> state in _states)
			{
				if (state.Key.Actor == actorId)
				{
					list.Add(state.Key);
				}
			}
			foreach (Key item in list)
			{
				_states.Remove(item);
			}
			return list.Count;
		}

		public void Clear()
		{
			_states.Clear();
		}
	}
}

plugins\Valayer.Integrations.SuperViking.dll

Decompiled 2 days ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.Rendering;
using Valayer.Core;
using Valayer.Core.Representation;
using Valayer.Core.Temporal;
using Valayer.Integrations.SuperViking.Destruction;
using Valayer.Integrations.SuperViking.LaserVision;
using Valayer.Integrations.SuperViking.LiftThrow;
using Valayer.Integrations.SuperViking.SharedActions;
using Valayer.Integrations.SuperViking.TemporalFields;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = "")]
[assembly: AssemblyCompany("Valayer.Integrations.SuperViking")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.1.8.0")]
[assembly: AssemblyInformationalVersion("1.1.8")]
[assembly: AssemblyProduct("Valayer.Integrations.SuperViking")]
[assembly: AssemblyTitle("Valayer.Integrations.SuperViking")]
[assembly: AssemblyVersion("1.1.8.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace Valayer.Integrations.SuperViking
{
	internal static class GroundSlamDiagnostics
	{
		private struct RootState
		{
			internal int OperationId;

			internal long Started;

			internal int CoordinatorOperationId;
		}

		internal static void Install(Harmony harmony, ManualLogSource log)
		{
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Expected O, but got Unknown
			//IL_0080: Expected O, but got Unknown
			if (Plugin.Settings.GroundSlamDiagnosticsEnabled.Value)
			{
				Type type = AccessTools.TypeByName("SuperViking.Powers.GroundSlamPower");
				MethodInfo methodInfo = ((type == null) ? null : AccessTools.Method(type, "Impact", (Type[])null, (Type[])null));
				if (methodInfo == null)
				{
					log.LogError((object)"SuperViking GroundSlamPower.Impact was not found; adapter diagnostics are unavailable.");
					return;
				}
				harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(GroundSlamDiagnostics), "RootPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(GroundSlamDiagnostics), "RootFinalizer", (Type[])null), (HarmonyMethod)null);
				int num = 0;
				num += OperationDiagnostics.RegisterTargets(harmony, "SuperViking.Util.DamageUtil", new string[1] { "AreaDamage" });
				log.LogInfo((object)("Registered SuperViking GroundSlam root and " + (num + OperationDiagnostics.RegisterTargets(harmony, "SuperViking.Util.Crater", new string[2] { "Dig", "AreaReady" })) + " integration-specific diagnostic methods."));
			}
		}

		private static void RootPrefix(out RootState __state)
		{
			RockHitPresentationOptimization.BeginGroundSlam();
			__state = new RootState
			{
				OperationId = OperationDiagnostics.Begin("SuperViking.GroundSlam"),
				Started = Stopwatch.GetTimestamp(),
				CoordinatorOperationId = (Plugin.Settings.ExperimentalDestructionCoordinationEnabled.Value ? DestructionRealizationCoordinator.Begin("SuperViking.GroundSlam") : 0)
			};
		}

		private static Exception RootFinalizer(Exception __exception, RootState __state)
		{
			//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_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			RockHitPresentationOptimization.EndGroundSlam();
			Summary val = DestructionRealizationCoordinator.End(__state.CoordinatorOperationId);
			if (Plugin.Settings.DetailedDestructionDiagnosticsEnabled.Value)
			{
				OperationDiagnostics.RecordCount("Valayer.Destruction.VisualEligible", (long)val.VisualEligible);
				OperationDiagnostics.RecordCount("Valayer.Destruction.VisualRealized", (long)val.VisualRealized);
				OperationDiagnostics.RecordCount("Valayer.Destruction.VisualGroups", (long)val.VisualGroups);
				OperationDiagnostics.RecordCount("Valayer.Destruction.AudioEligible", (long)val.AudioEligible);
				OperationDiagnostics.RecordCount("Valayer.Destruction.AudioRealized", (long)val.AudioRealized);
				OperationDiagnostics.RecordCount("Valayer.Destruction.AudioGroups", (long)val.AudioGroups);
				OperationDiagnostics.RecordCount("Valayer.Destruction.FootprintEvents", (long)val.FootprintEvents);
			}
			double num = (double)(Stopwatch.GetTimestamp() - __state.Started) * 1000.0 / (double)Stopwatch.Frequency;
			OperationDiagnostics.CompleteRoot(__state.OperationId, num, __exception);
			return __exception;
		}
	}
	internal sealed class IntegrationConfig
	{
		internal ConfigEntry<bool> Enabled { get; private set; }

		internal ConfigEntry<bool> LaserEyesEnabled { get; private set; }

		internal ConfigEntry<float> LaserAimUpdatesPerSecond { get; private set; }

		internal ConfigEntry<float> LaserInterpolationMilliseconds { get; private set; }

		internal ConfigEntry<float> LaserRemoteTimeoutSeconds { get; private set; }

		internal ConfigEntry<float> LaserRemoteWidth { get; private set; }

		internal ConfigEntry<bool> TemporalFieldsEnabled { get; private set; }

		internal ConfigEntry<TemporalDomainShape> TemporalDomainShape { get; private set; }

		internal ConfigEntry<float> TemporalBoxSizeX { get; private set; }

		internal ConfigEntry<float> TemporalBoxSizeY { get; private set; }

		internal ConfigEntry<float> TemporalBoxSizeZ { get; private set; }

		internal ConfigEntry<float> TemporalSphereDiameter { get; private set; }

		internal ConfigEntry<float> TemporalEffectiveTimeScale { get; private set; }

		internal ConfigEntry<float> TemporalSpatialResolution { get; private set; }

		internal ConfigEntry<float> TemporalSimulationResolution { get; private set; }

		internal ConfigEntry<float> TemporalDomainLifetime { get; private set; }

		internal ConfigEntry<TemporalInteractionPermissions> TemporalAffectedEntities { get; private set; }

		internal ConfigEntry<string> TemporalOtherPlayerPrecedence { get; private set; }

		internal ConfigEntry<bool> TemporalVisualizationEnabled { get; private set; }

		internal ConfigEntry<bool> TemporalDiagnosticsEnabled { get; private set; }

		internal ConfigEntry<float> TemporalVisualizationDistance { get; private set; }

		internal ConfigEntry<bool> HostAuthorityPanelEnabled { get; private set; }

		internal ConfigEntry<bool> DestructionSchedulingEnabled { get; private set; }

		internal ConfigEntry<bool> ExperimentalDestructionCoordinationEnabled { get; private set; }

		internal ConfigEntry<bool> ExperimentalVisualAggregationEnabled { get; private set; }

		internal ConfigEntry<bool> ExperimentalDestructionAudioAggregationEnabled { get; private set; }

		internal ConfigEntry<bool> ExperimentalPreSpawnLootAggregationEnabled { get; private set; }

		internal ConfigEntry<bool> ExperimentalDestructionIdentityTrackingEnabled { get; private set; }

		internal ConfigEntry<bool> ExperimentalDestructionSpatialTracingEnabled { get; private set; }

		internal ConfigEntry<bool> RockHitAudioBudgetEnabled { get; private set; }

		internal ConfigEntry<int> RockHitMaximumAudioRequests { get; private set; }

		internal ConfigEntry<int> RockHitMaximumAudioRequestsPerCell { get; private set; }

		internal ConfigEntry<float> RockHitAudioCellSize { get; private set; }

		internal ConfigEntry<bool> GroundSlamDiagnosticsEnabled { get; private set; }

		internal ConfigEntry<bool> DetailedDestructionDiagnosticsEnabled { get; private set; }

		internal ConfigEntry<bool> LiftThrowDiagnosticsEnabled { get; private set; }

		internal ConfigEntry<bool> SharedActionDiagnosticsEnabled { get; private set; }

		internal ConfigEntry<bool> SharedActionRepresentationEnabled { get; private set; }

		internal static IntegrationConfig Bind(ConfigFile config)
		{
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Expected O, but got Unknown
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: Expected O, but got Unknown
			//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: Expected O, but got Unknown
			//IL_0112: Unknown result type (might be due to invalid IL or missing references)
			//IL_011c: Expected O, but got Unknown
			//IL_0183: Unknown result type (might be due to invalid IL or missing references)
			//IL_018d: Expected O, but got Unknown
			//IL_01bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c6: Expected O, but got Unknown
			//IL_01f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ff: Expected O, but got Unknown
			//IL_022e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0238: Expected O, but got Unknown
			//IL_0267: Unknown result type (might be due to invalid IL or missing references)
			//IL_0271: Expected O, but got Unknown
			//IL_02a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_02aa: Expected O, but got Unknown
			//IL_02d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e3: Expected O, but got Unknown
			//IL_0312: Unknown result type (might be due to invalid IL or missing references)
			//IL_031c: Expected O, but got Unknown
			//IL_03c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ca: Expected O, but got Unknown
			//IL_04eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_04f5: Expected O, but got Unknown
			//IL_0518: Unknown result type (might be due to invalid IL or missing references)
			//IL_0522: Expected O, but got Unknown
			//IL_0551: Unknown result type (might be due to invalid IL or missing references)
			//IL_055b: Expected O, but got Unknown
			return new IntegrationConfig
			{
				Enabled = config.Bind<bool>("General", "Enabled", true, "Enable the optional SuperViking adapter. Valayer Core does not require this adapter."),
				LaserEyesEnabled = config.Bind<bool>("LaserEyes", "Enabled", false, "Synchronize Laser Vision start, aim, and stop for remote presentation only. Remote events never apply damage."),
				LaserAimUpdatesPerSecond = config.Bind<float>("LaserEyes", "AimUpdatesPerSecond", 15f, new ConfigDescription("Maximum remote aim update rate. Rendering interpolates between updates.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(2f, 30f), Array.Empty<object>())),
				LaserInterpolationMilliseconds = config.Bind<float>("LaserEyes", "InterpolationMilliseconds", 80f, new ConfigDescription("Remote endpoint smoothing time. Lower values track faster; higher values look smoother.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 500f), Array.Empty<object>())),
				LaserRemoteTimeoutSeconds = config.Bind<float>("LaserEyes", "RemoteTimeoutSeconds", 0.75f, new ConfigDescription("Hide a remote beam if stop/update packets are lost for this many seconds.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.25f, 5f), Array.Empty<object>())),
				LaserRemoteWidth = config.Bind<float>("LaserEyes", "RemoteBeamWidth", 0.04f, new ConfigDescription("Local visual width of replicated remote beams in metres.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.005f, 0.25f), Array.Empty<object>())),
				TemporalFieldsEnabled = config.Bind<bool>("TemporalFields", "Enabled", false, "EXPERIMENTAL GATE: apply spatial SuperSpeed fields to configured owner-authoritative creature and projectile relationships without changing global Unity time or other players."),
				TemporalDomainShape = config.Bind<TemporalDomainShape>("TemporalFields.Domain", "Shape", (TemporalDomainShape)0, "Host-authoritative domain shape. Box uses independent X/Y/Z sizes; Sphere uses Diameter."),
				TemporalBoxSizeX = config.Bind<float>("TemporalFields.Domain", "BoxSizeX", 30f, new ConfigDescription("Host-authoritative box width in metres.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 400f), Array.Empty<object>())),
				TemporalBoxSizeY = config.Bind<float>("TemporalFields.Domain", "BoxSizeY", 30f, new ConfigDescription("Host-authoritative box height in metres.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 400f), Array.Empty<object>())),
				TemporalBoxSizeZ = config.Bind<float>("TemporalFields.Domain", "BoxSizeZ", 30f, new ConfigDescription("Host-authoritative box depth in metres.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 400f), Array.Empty<object>())),
				TemporalSphereDiameter = config.Bind<float>("TemporalFields.Domain", "SphereDiameter", 30f, new ConfigDescription("Host-authoritative sphere diameter in metres.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 400f), Array.Empty<object>())),
				TemporalEffectiveTimeScale = config.Bind<float>("TemporalFields.Policy", "EffectiveTimeScale", 0.25f, new ConfigDescription("Host-authoritative eligible-entity time differential; 0.25 advances at quarter speed.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.05f, 1f), Array.Empty<object>())),
				TemporalSpatialResolution = config.Bind<float>("TemporalFields.Policy", "SpatialResolutionMeters", 0.25f, new ConfigDescription("Host quantization for synchronized domain centers.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.05f, 2f), Array.Empty<object>())),
				TemporalSimulationResolution = config.Bind<float>("TemporalFields.Policy", "ProjectileSimulationResolutionHz", 50f, new ConfigDescription("Maximum frequency for reevaluating creature/projectile boundary and eligibility state. The legacy key name is retained for config compatibility.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(10f, 50f), Array.Empty<object>())),
				TemporalDomainLifetime = config.Bind<float>("TemporalFields.Policy", "DomainPacketLifetimeSeconds", 0.5f, new ConfigDescription("Authoritative domain expiry if updates or stops are lost.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.25f, 2f), Array.Empty<object>())),
				TemporalAffectedEntities = config.Bind<TemporalInteractionPermissions>("TemporalFields.Policy", "AffectedEntityCategories", (TemporalInteractionPermissions)127, "Host-authoritative creature and projectile relationship categories. Player characters are always immune."),
				TemporalOtherPlayerPrecedence = config.Bind<string>("TemporalFields.Authority", "OtherPlayerPrecedence", string.Empty, "Ordered comma-separated player session IDs. The listen host is always locked at rank 0; unlisted players tie at rank 1000 and resolve by authenticated ID."),
				TemporalVisualizationEnabled = config.Bind<bool>("TemporalFields.Visual", "Enabled", true, "Render authorized box/sphere domain boundaries as local holograms. Presentation has no collider or gameplay effect."),
				TemporalDiagnosticsEnabled = config.Bind<bool>("TemporalFields.Diagnostics", "Enabled", false, "EXPERIMENTAL and disabled by default: emit bounded domain membership and effective creature-progression counters."),
				TemporalVisualizationDistance = config.Bind<float>("TemporalFields.Visual", "MaximumDistance", 150f, new ConfigDescription("Maximum camera distance for temporal-domain holograms in metres.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(20f, 500f), Array.Empty<object>())),
				HostAuthorityPanelEnabled = config.Bind<bool>("TemporalFields.Authority", "InGamePanelEnabled", true, "Show the host-only Valayer Authority button and policy panel. Dedicated servers retain authority without rendering a panel."),
				DestructionSchedulingEnabled = config.Bind<bool>("Destruction", "SchedulingEnabled", false, "Reserved gate. Authoritative GroundSlam damage is intentionally not deferred because section, support, drop, persistence, and random ordering must remain exact."),
				ExperimentalDestructionCoordinationEnabled = config.Bind<bool>("Destruction", "ExperimentalDestructionCoordination", false, "EXPERIMENTAL and disabled by default: coordinate compatible destruction presentation/resource realization only when the Core coordinator is also enabled."),
				ExperimentalVisualAggregationEnabled = config.Bind<bool>("Destruction", "ExperimentalVisualAggregation", false, "EXPERIMENTAL and disabled by default: aggregate compatible destruction visual effects before allocation where the adapter can prove safety."),
				ExperimentalDestructionAudioAggregationEnabled = config.Bind<bool>("Destruction", "ExperimentalDestructionAudioAggregation", false, "EXPERIMENTAL and disabled by default: aggregate compatible destruction audio without changing VPO-owned ZSFX.Play behavior."),
				ExperimentalPreSpawnLootAggregationEnabled = config.Bind<bool>("Destruction", "ExperimentalPreSpawnLootAggregation", false, "EXPERIMENTAL and disabled by default: aggregate compatible material yields before item objects are spawned; unsupported paths fail open."),
				ExperimentalDestructionIdentityTrackingEnabled = config.Bind<bool>("Diagnostics", "ExperimentalDestructionIdentityTracking", false, "EXPERIMENTAL and disabled by default: trace unique destruction identities with bounded memory."),
				ExperimentalDestructionSpatialTracingEnabled = config.Bind<bool>("Diagnostics", "ExperimentalDestructionSpatialTracing", false, "EXPERIMENTAL and disabled by default: trace bounded destruction spatial footprints."),
				RockHitAudioBudgetEnabled = config.Bind<bool>("Destruction", "RockHitAudioBudget", true, "Skip owner-authoritative hits to MineRock5 sections already at zero health and bound repeated local MineRock/MineRock5 hit effects and audio during one GroundSlam. Damage outcomes, support, terrain, drops, persistence, ownership, and random progression remain unchanged."),
				RockHitMaximumAudioRequests = config.Bind<int>("Destruction", "RockHitMaximumAudioRequests", 16, new ConfigDescription("Maximum admitted rock hit effect groups and audio requests during one GroundSlam.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 64), Array.Empty<object>())),
				RockHitMaximumAudioRequestsPerCell = config.Bind<int>("Destruction", "RockHitMaximumAudioRequestsPerCell", 2, new ConfigDescription("Maximum admitted rock hit effect groups and audio requests in one spatial cell during one GroundSlam.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 8), Array.Empty<object>())),
				RockHitAudioCellSize = config.Bind<float>("Destruction", "RockHitAudioCellSize", 3f, new ConfigDescription("Rock hit presentation budgeting cell size in metres.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.5f, 10f), Array.Empty<object>())),
				GroundSlamDiagnosticsEnabled = config.Bind<bool>("Diagnostics", "GroundSlamEnabled", false, "EXPERIMENTAL and disabled by default: register SuperViking GroundSlam as a detailed Valayer diagnostic operation."),
				DetailedDestructionDiagnosticsEnabled = config.Bind<bool>("Diagnostics", "DetailedDestructionDiagnostics", false, "EXPERIMENTAL and disabled by default: add operation-wide destruction realization, identity, and spatial metrics."),
				LiftThrowDiagnosticsEnabled = config.Bind<bool>("Diagnostics", "LiftThrowTargets", true, "Explain why SuperViking accepted or rejected a Lift/Throw prop target without changing eligibility."),
				SharedActionDiagnosticsEnabled = config.Bind<bool>("Diagnostics", "SharedActionTimeline", true, "Record semantic Lift/Throw preparation, holding, execution, recovery, and interruption phases."),
				SharedActionRepresentationEnabled = config.Bind<bool>("SharedActions", "Enabled", false, "Synchronize ordered Lift/Throw action phases and reconstruct remote arm presentation. Receiver never moves targets, changes ownership/physics, or applies gameplay effects.")
			};
		}

		internal void LogEffective(ManualLogSource log)
		{
			//IL_01a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ad: Unknown result type (might be due to invalid IL or missing references)
			bool enabled = DestructionRealizationCoordinator.Enabled;
			bool flag = ExperimentalDestructionCoordinationEnabled.Value && enabled;
			bool flag2 = ExperimentalVisualAggregationEnabled.Value && enabled;
			bool flag3 = false;
			bool flag4 = false;
			log.LogInfo((object)("Effective integration config: Enabled=" + Enabled.Value + ", GroundSlamDiagnostics=" + GroundSlamDiagnosticsEnabled.Value + ", LiftThrowDiagnostics=" + LiftThrowDiagnosticsEnabled.Value + ", SharedActionDiagnostics=" + SharedActionDiagnosticsEnabled.Value + ", SharedActionRepresentation=" + SharedActionRepresentationEnabled.Value + ", LaserEyes=" + LaserEyesEnabled.Value + ", LaserAimHz=" + LaserAimUpdatesPerSecond.Value.ToString("0.###") + ", RockHitAudioBudget=" + RockHitAudioBudgetEnabled.Value + ", RockHitAudioMax=" + RockHitMaximumAudioRequests.Value + ", TemporalFields(experimental)=" + TemporalFieldsEnabled.Value + ", TemporalDiagnostics=" + TemporalDiagnosticsEnabled.Value + ", TemporalEntities=" + ((object)TemporalAffectedEntities.Value/*cast due to .constrained prefix*/).ToString() + ", DestructionScheduling(experimental)=" + DestructionSchedulingEnabled.Value + ", DestructionCoordination(requested/effective)=" + ExperimentalDestructionCoordinationEnabled.Value + "/" + flag + ", VisualAggregation(requested/effective)=" + ExperimentalVisualAggregationEnabled.Value + "/" + flag2 + ", AudioAggregation(requested/effective)=" + ExperimentalDestructionAudioAggregationEnabled.Value + "/" + flag3 + ", PreSpawnLoot(requested/effective)=" + ExperimentalPreSpawnLootAggregationEnabled.Value + "/" + flag4 + ", IdentityTracing(experimental)=" + ExperimentalDestructionIdentityTrackingEnabled.Value + ", SpatialTracing(experimental)=" + ExperimentalDestructionSpatialTracingEnabled.Value + "."));
			if (DestructionSchedulingEnabled.Value)
			{
				log.LogWarning((object)"Destruction scheduling is enabled, but remains intentionally inert.");
			}
			if (ExperimentalDestructionCoordinationEnabled.Value && !enabled)
			{
				log.LogWarning((object)"Experimental destruction coordination requested by SuperViking, but Core coordination is disabled; effective capability is false.");
			}
			if (ExperimentalDestructionAudioAggregationEnabled.Value || ExperimentalPreSpawnLootAggregationEnabled.Value)
			{
				log.LogWarning((object)"Requested audio/pre-spawn loot aggregation has no installed realization adapter in this build; effective capability is false and original Valheim realization remains active.");
			}
			if (ExperimentalDestructionCoordinationEnabled.Value || ExperimentalVisualAggregationEnabled.Value || ExperimentalDestructionAudioAggregationEnabled.Value || ExperimentalPreSpawnLootAggregationEnabled.Value || ExperimentalDestructionIdentityTrackingEnabled.Value || ExperimentalDestructionSpatialTracingEnabled.Value)
			{
				log.LogWarning((object)"Experimental destruction capabilities are enabled explicitly; each remains bounded, ownership-preserving, and fails open when unsupported.");
			}
			if (TemporalFieldsEnabled.Value)
			{
				log.LogWarning((object)"Temporal creature/projectile simulation is experimental and remains disabled by default pending genuine authenticated two-peer verification.");
			}
		}
	}
	[BepInPlugin("foundation.valayer.heimordination.superviking", "Valayer — SuperViking Integration", "1.1.8")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInProcess("valheim.exe")]
	[BepInProcess("valheim_server.exe")]
	public sealed class Plugin : BaseUnityPlugin
	{
		public const string PluginGuid = "foundation.valayer.heimordination.superviking";

		public const string PluginName = "Valayer — SuperViking Integration";

		public const string PluginVersion = "1.1.8";

		public const string SuperVikingGuid = "com.preston.superviking";

		private Harmony _harmony;

		internal static ManualLogSource Log { get; private set; }

		internal static IntegrationConfig Settings { get; private set; }

		private void Awake()
		{
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Expected O, but got Unknown
			Log = ((BaseUnityPlugin)this).Logger;
			Settings = IntegrationConfig.Bind(((BaseUnityPlugin)this).Config);
			Settings.LogEffective(Log);
			if (!Settings.Enabled.Value)
			{
				Log.LogInfo((object)"SuperViking integration disabled by [General] Enabled.");
				return;
			}
			_harmony = new Harmony("foundation.valayer.heimordination.superviking");
			TemporalFieldIntegration.Install(_harmony, Log);
			if (!Chainloader.PluginInfos.ContainsKey("com.preston.superviking"))
			{
				Log.LogInfo((object)"SuperViking is not installed; ability adapters remain inert while enabled Core temporal authority may serve a dedicated host.");
				return;
			}
			RockHitPresentationOptimization.Install(_harmony, Log);
			GroundSlamDiagnostics.Install(_harmony, Log);
			LiftThrowDiagnostics.Install(_harmony, Log);
			SharedActionDiagnostics.Install(_harmony, Log);
			SharedActionIntegration.Install(_harmony, Log);
			LaserVisionIntegration.Install(_harmony, Log);
			Log.LogInfo((object)"Valayer — SuperViking Integration 1.1.8 loaded. High-risk gameplay adapters remain disabled by default.");
		}

		private void Update()
		{
			HostAuthorityPanel.Tick();
			if (_harmony != null)
			{
				RockHitPresentationOptimization.Tick();
				LaserVisionIntegration.Tick();
				TemporalFieldIntegration.Tick();
				SharedActionIntegration.Tick();
			}
		}

		private void LateUpdate()
		{
			if (_harmony != null && Settings.SharedActionRepresentationEnabled.Value)
			{
				SharedActionIntegration.LateTick();
			}
		}

		private void OnGUI()
		{
			if (_harmony != null)
			{
				HostAuthorityPanel.Draw();
			}
		}

		private void OnDestroy()
		{
			RockHitPresentationOptimization.Shutdown();
			LaserVisionIntegration.Shutdown();
			TemporalFieldIntegration.Shutdown();
			SharedActionIntegration.Shutdown();
			if (_harmony != null)
			{
				_harmony.UnpatchSelf();
				_harmony = null;
			}
		}
	}
}
namespace Valayer.Integrations.SuperViking.TemporalFields
{
	internal static class HostAuthorityPanel
	{
		[CompilerGenerated]
		private static class <>O
		{
			public static WindowFunction <0>__Window;
		}

		private static bool _open;

		private static Rect _window = new Rect(30f, 70f, 460f, 700f);

		private static Vector2 _scroll;

		private static CursorLockMode _previousLock;

		private static bool _previousVisible;

		internal static void Tick()
		{
			if (!CanManage())
			{
				if (_open)
				{
					Close();
				}
			}
			else if (Input.GetKeyDown((KeyCode)289))
			{
				if (_open)
				{
					Close();
				}
				else
				{
					Open();
				}
			}
		}

		internal static void Draw()
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Expected O, but got Unknown
			if (_open && CanManage())
			{
				Rect window = _window;
				object obj = <>O.<0>__Window;
				if (obj == null)
				{
					WindowFunction val = Window;
					<>O.<0>__Window = val;
					obj = (object)val;
				}
				_window = GUI.Window(1447119961, window, (WindowFunction)obj, "Valayer · Host Authority");
			}
		}

		private static bool CanManage()
		{
			if (Plugin.Settings != null && Plugin.Settings.HostAuthorityPanelEnabled.Value && (Object)(object)ZNet.instance != (Object)null && ZNet.instance.IsServer())
			{
				return (Object)(object)Player.m_localPlayer != (Object)null;
			}
			return false;
		}

		private static void Open()
		{
			//IL_0006: 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)
			_open = true;
			_previousLock = Cursor.lockState;
			_previousVisible = Cursor.visible;
			Cursor.lockState = (CursorLockMode)0;
			Cursor.visible = true;
		}

		private static void Close()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			_open = false;
			Cursor.lockState = _previousLock;
			Cursor.visible = _previousVisible;
		}

		private static void Window(int id)
		{
			//IL_0000: 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_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: 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_00d8: Invalid comparison between Unknown and I4
			//IL_0116: Unknown result type (might be due to invalid IL or missing references)
			//IL_02fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0302: 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)
			_scroll = GUILayout.BeginScrollView(_scroll, Array.Empty<GUILayoutOption>());
			GUILayout.Label("F8 toggles this panel. The listen-host player is locked at priority 0.", Array.Empty<GUILayoutOption>());
			GUILayout.Label("Authority: Listen host · Policy revision " + TemporalFieldNetwork.PolicyRevision, Array.Empty<GUILayoutOption>());
			GUILayout.Label("Peer readiness: " + TemporalFieldNetwork.CompatibilitySummary(), Array.Empty<GUILayoutOption>());
			GUILayout.Space(8f);
			GUILayout.Label("Spatial domain", Array.Empty<GUILayoutOption>());
			GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
			if (GUILayout.Button("Box" + (((int)Plugin.Settings.TemporalDomainShape.Value == 0) ? " ✓" : ""), Array.Empty<GUILayoutOption>()))
			{
				Set<TemporalDomainShape>(Plugin.Settings.TemporalDomainShape, (TemporalDomainShape)0);
			}
			if (GUILayout.Button("Sphere" + (((int)Plugin.Settings.TemporalDomainShape.Value == 1) ? " ✓" : ""), Array.Empty<GUILayoutOption>()))
			{
				Set<TemporalDomainShape>(Plugin.Settings.TemporalDomainShape, (TemporalDomainShape)1);
			}
			GUILayout.EndHorizontal();
			if ((int)Plugin.Settings.TemporalDomainShape.Value == 0)
			{
				Float("Box X", Plugin.Settings.TemporalBoxSizeX, 1f, 400f, 1f);
				Float("Box Y", Plugin.Settings.TemporalBoxSizeY, 1f, 400f, 1f);
				Float("Box Z", Plugin.Settings.TemporalBoxSizeZ, 1f, 400f, 1f);
			}
			else
			{
				Float("Sphere diameter", Plugin.Settings.TemporalSphereDiameter, 1f, 400f, 1f);
			}
			GUILayout.Space(8f);
			GUILayout.Label("Shared simulation policy", Array.Empty<GUILayoutOption>());
			Float("Time differential", Plugin.Settings.TemporalEffectiveTimeScale, 0.05f, 1f, 0.05f);
			Float("Spatial resolution", Plugin.Settings.TemporalSpatialResolution, 0.05f, 2f, 0.05f);
			Float("Entity resolution Hz", Plugin.Settings.TemporalSimulationResolution, 10f, 50f, 1f);
			Float("Packet lifetime", Plugin.Settings.TemporalDomainLifetime, 0.25f, 2f, 0.05f);
			GUILayout.Label("Affected creature relationships", Array.Empty<GUILayoutOption>());
			Permission("Hostile", (TemporalInteractionPermissions)1);
			Permission("Neutral", (TemporalInteractionPermissions)2);
			Permission("Allied / tamed", (TemporalInteractionPermissions)4);
			GUILayout.Label("Affected projectile relationships", Array.Empty<GUILayoutOption>());
			Permission("Hostile", (TemporalInteractionPermissions)8);
			Permission("Neutral / environmental", (TemporalInteractionPermissions)16);
			Permission("Allied players / creatures", (TemporalInteractionPermissions)32);
			Permission("Field owner's projectiles", (TemporalInteractionPermissions)64);
			GUILayout.Space(8f);
			GUILayout.Label("Player precedence", Array.Empty<GUILayoutOption>());
			Player localPlayer = Player.m_localPlayer;
			GUILayout.Label("0 · " + localPlayer.GetPlayerName() + " [HOST · LOCKED]", Array.Empty<GUILayoutOption>());
			ZDOID zDOID = ((Character)localPlayer).GetZDOID();
			DrawOtherPlayers(((ZDOID)(ref zDOID)).UserID);
			GUILayout.Space(10f);
			if (GUILayout.Button("Close", Array.Empty<GUILayoutOption>()))
			{
				Close();
			}
			GUILayout.EndScrollView();
			GUI.DragWindow(new Rect(0f, 0f, 10000f, 24f));
		}

		private static void DrawOtherPlayers(long hostId)
		{
			List<Player> source = (from p in Player.GetAllPlayers()
				where (Object)(object)p != (Object)null
				select p).ToList();
			List<long> connected = (from id in source.Select(delegate(Player p)
				{
					//IL_0001: Unknown result type (might be due to invalid IL or missing references)
					//IL_0006: Unknown result type (might be due to invalid IL or missing references)
					ZDOID zDOID = ((Character)p).GetZDOID();
					return ((ZDOID)(ref zDOID)).UserID;
				})
				where id != 0L && id != hostId
				select id).Distinct().ToList();
			List<long> list = ParseOrder();
			foreach (long item in connected)
			{
				if (!list.Contains(item))
				{
					list.Add(item);
				}
			}
			list.RemoveAll((long id) => !connected.Contains(id));
			for (int num = 0; num < list.Count; num++)
			{
				long playerId = list[num];
				Player val = ((IEnumerable<Player>)source).FirstOrDefault((Func<Player, bool>)delegate(Player p)
				{
					//IL_0001: Unknown result type (might be due to invalid IL or missing references)
					//IL_0006: Unknown result type (might be due to invalid IL or missing references)
					ZDOID zDOID = ((Character)p).GetZDOID();
					return ((ZDOID)(ref zDOID)).UserID == playerId;
				});
				GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
				GUILayout.Label(num + 1 + " · " + (((Object)(object)val == (Object)null) ? playerId.ToString(CultureInfo.InvariantCulture) : val.GetPlayerName()), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(270f) });
				GUI.enabled = num > 0;
				if (GUILayout.Button("↑", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(42f) }))
				{
					Move(list, num, num - 1);
					GUI.enabled = true;
					GUILayout.EndHorizontal();
					return;
				}
				GUI.enabled = num + 1 < list.Count;
				if (GUILayout.Button("↓", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(42f) }))
				{
					Move(list, num, num + 1);
					GUI.enabled = true;
					GUILayout.EndHorizontal();
					return;
				}
				GUI.enabled = true;
				GUILayout.EndHorizontal();
			}
			if (list.Count == 0)
			{
				GUILayout.Label("No other represented players are connected.", Array.Empty<GUILayoutOption>());
			}
		}

		private static List<long> ParseOrder()
		{
			List<long> list = new List<long>();
			string[] array = (Plugin.Settings.TemporalOtherPlayerPrecedence.Value ?? string.Empty).Split(new char[3] { ',', ';', ' ' }, StringSplitOptions.RemoveEmptyEntries);
			for (int i = 0; i < array.Length; i++)
			{
				if (long.TryParse(array[i], NumberStyles.Integer, CultureInfo.InvariantCulture, out var result) && result != 0L && !list.Contains(result))
				{
					list.Add(result);
				}
			}
			return list;
		}

		private static void Move(List<long> values, int from, int to)
		{
			long item = values[from];
			values.RemoveAt(from);
			values.Insert(to, item);
			Plugin.Settings.TemporalOtherPlayerPrecedence.Value = string.Join(",", values.Select((long num) => num.ToString(CultureInfo.InvariantCulture)).ToArray());
			TemporalFieldNetwork.NotifyPolicyChanged();
		}

		private static void Float(string label, ConfigEntry<float> entry, float minimum, float maximum, float step)
		{
			GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
			GUILayout.Label(label + ": " + entry.Value.ToString("0.##", CultureInfo.InvariantCulture), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(235f) });
			if (GUILayout.Button("−", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(45f) }))
			{
				Set(entry, Mathf.Clamp(Mathf.Round((entry.Value - step) / step) * step, minimum, maximum));
			}
			if (GUILayout.Button("+", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(45f) }))
			{
				Set(entry, Mathf.Clamp(Mathf.Round((entry.Value + step) / step) * step, minimum, maximum));
			}
			GUILayout.EndHorizontal();
		}

		private static void Permission(string label, TemporalInteractionPermissions permission)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: 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_0014: Invalid comparison between Unknown and I4
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: 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)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			TemporalInteractionPermissions value = Plugin.Settings.TemporalAffectedEntities.Value;
			bool flag = (value & permission) > 0;
			if (GUILayout.Button((flag ? "☑ " : "☐ ") + label, Array.Empty<GUILayoutOption>()))
			{
				Set<TemporalInteractionPermissions>(Plugin.Settings.TemporalAffectedEntities, (TemporalInteractionPermissions)(flag ? (value & ~permission) : (value | permission)));
			}
		}

		private static void Set<T>(ConfigEntry<T> entry, T value)
		{
			if (!object.Equals(entry.Value, value))
			{
				entry.Value = value;
				TemporalFieldNetwork.NotifyPolicyChanged();
			}
		}
	}
	internal static class TemporalCreatureSimulation
	{
		private sealed class CreatureState
		{
			internal float Scale = 1f;

			internal float NextEvaluationAt;

			internal float LastSeenAt;

			internal ZSyncAnimation Animation;

			internal float BaselineAnimationSpeed = 1f;

			internal bool AnimationApplied;
		}

		private const int MaximumTrackedCreatures = 2048;

		private const float StaleStateSeconds = 10f;

		private static readonly Dictionary<int, CreatureState> States = new Dictionary<int, CreatureState>();

		private static readonly TemporalRelationResolver RelationResolver = new TemporalRelationResolver(ResolveRelation);

		private static FieldInfo _aiCharacterField;

		private static FieldInfo _animationAnimatorField;

		private static Character _evaluatedCharacter;

		private static ManualLogSource _log;

		private static float _nextPruneAt;

		private static float _nextFailureLogAt;

		private static float _nextDiagnosticsAt;

		private static int _diagnosticEvaluations;

		private static int _diagnosticInside;

		private static int _diagnosticSlowed;

		private static int _diagnosticApplied;

		private static bool _installed;

		[ThreadStatic]
		private static int _characterStepDepth;

		[ThreadStatic]
		private static int _aiStepDepth;

		internal static void Install(Harmony harmony, ManualLogSource log)
		{
			//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e4: Expected O, but got Unknown
			_log = log;
			_aiCharacterField = AccessTools.Field(typeof(BaseAI), "m_character");
			_animationAnimatorField = AccessTools.Field(typeof(ZSyncAnimation), "m_animator");
			int num = PatchOverrides(harmony, typeof(Character), "CustomFixedUpdate", "CharacterStepPrefix", "CharacterStepFinalizer");
			int num2 = PatchOverrides(harmony, typeof(BaseAI), "UpdateAI", "AIStepPrefix", "AIStepFinalizer");
			MethodInfo methodInfo = AccessTools.Method(typeof(Character), "SetMoveDir", (Type[])null, (Type[])null);
			if (_aiCharacterField == null || _animationAnimatorField == null || methodInfo == null || num == 0 || num2 == 0)
			{
				log.LogWarning((object)"Temporal creature simulation could not bind all movement/AI/animation boundaries; creature execution remains inert.");
				return;
			}
			harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(TemporalCreatureSimulation), "SetMoveDirPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			_installed = true;
			log.LogInfo((object)("Temporal creature simulation installed across " + num + " character progression and " + num2 + " AI progression boundaries."));
		}

		private static int PatchOverrides(Harmony harmony, Type root, string methodName, string prefixName, string finalizerName)
		{
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Expected O, but got Unknown
			//IL_0093: Expected O, but got Unknown
			int num = 0;
			HashSet<MethodBase> hashSet = new HashSet<MethodBase>();
			Type[] types = root.Assembly.GetTypes();
			foreach (Type type in types)
			{
				if (root.IsAssignableFrom(type))
				{
					MethodInfo methodInfo = AccessTools.DeclaredMethod(type, methodName, new Type[1] { typeof(float) }, (Type[])null);
					if (!(methodInfo == null) && !methodInfo.IsAbstract && hashSet.Add(methodInfo))
					{
						harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(TemporalCreatureSimulation), prefixName, (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(TemporalCreatureSimulation), finalizerName, (Type[])null), (HarmonyMethod)null);
						num++;
					}
				}
			}
			return num;
		}

		private static void CharacterStepPrefix(Character __instance, ref float __0)
		{
			if (_characterStepDepth++ == 0)
			{
				__0 *= EvaluateScale(__instance, requireOwner: true);
			}
		}

		private static Exception CharacterStepFinalizer(Exception __exception)
		{
			if (_characterStepDepth > 0)
			{
				_characterStepDepth--;
			}
			return __exception;
		}

		private static void AIStepPrefix(BaseAI __instance, ref float __0)
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			if (_aiStepDepth++ == 0 && !((Object)(object)__instance == (Object)null))
			{
				Character character = ((_aiCharacterField == null) ? ((Character)null) : ((Character)_aiCharacterField.GetValue(__instance)));
				__0 *= EvaluateScale(character, requireOwner: true);
			}
		}

		private static Exception AIStepFinalizer(Exception __exception)
		{
			if (_aiStepDepth > 0)
			{
				_aiStepDepth--;
			}
			return __exception;
		}

		private static void SetMoveDirPrefix(Character __instance, ref Vector3 dir)
		{
			//IL_0012: 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_001d: Unknown result type (might be due to invalid IL or missing references)
			float num = EvaluateScale(__instance, requireOwner: true);
			if (num < 0.999f)
			{
				dir *= num;
			}
		}

		private static float EvaluateScale(Character character, bool requireOwner)
		{
			//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)
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_00df: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0147: Unknown result type (might be due to invalid IL or missing references)
			//IL_0110: Unknown result type (might be due to invalid IL or missing references)
			//IL_0126: Unknown result type (might be due to invalid IL or missing references)
			if (!_installed)
			{
				return 1f;
			}
			if ((Object)(object)character == (Object)null || character is Player || character.IsDead())
			{
				return 1f;
			}
			if (requireOwner && !character.IsOwner())
			{
				return 1f;
			}
			try
			{
				int instanceID = ((Object)character).GetInstanceID();
				float unscaledTime = Time.unscaledTime;
				if (!States.TryGetValue(instanceID, out var value))
				{
					if (States.Count >= 2048)
					{
						return 1f;
					}
					value = new CreatureState();
					States.Add(instanceID, value);
				}
				value.LastSeenAt = unscaledTime;
				if (unscaledTime < value.NextEvaluationAt)
				{
					return value.Scale;
				}
				try
				{
					_evaluatedCharacter = character;
					Vector3 position = ((Component)character).transform.position;
					TemporalEvaluation val = TemporalFieldNetwork.Registry.EvaluateEntity(new TemporalPoint(position.x, position.y, position.z), (TemporalEntityKind)0, true, RelationResolver, unscaledTime);
					value.Scale = val.TimeScale;
					if (Plugin.Settings.TemporalDiagnosticsEnabled.Value)
					{
						_diagnosticEvaluations++;
						if (val.ContributingFields > 0)
						{
							_diagnosticInside++;
						}
						if (val.TimeScale < 0.999f)
						{
							_diagnosticSlowed++;
						}
					}
					value.NextEvaluationAt = unscaledTime + 1f / val.SimulationResolutionHz;
					return value.Scale;
				}
				finally
				{
					_evaluatedCharacter = null;
				}
			}
			catch (Exception ex)
			{
				_evaluatedCharacter = null;
				float unscaledTime2 = Time.unscaledTime;
				if (_log != null && unscaledTime2 >= _nextFailureLogAt)
				{
					_nextFailureLogAt = unscaledTime2 + 10f;
					_log.LogWarning((object)("Temporal creature evaluation failed open: " + ex.Message));
				}
				return 1f;
			}
		}

		private static TemporalRelation ResolveRelation(long fieldOwnerId)
		{
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Invalid comparison between Unknown and I4
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Invalid comparison between Unknown and I4
			Character evaluatedCharacter = _evaluatedCharacter;
			if (!((Object)(object)evaluatedCharacter == (Object)null))
			{
				Player val = null;
				foreach (Player allPlayer in Player.GetAllPlayers())
				{
					if ((Object)(object)allPlayer != (Object)null)
					{
						ZDOID zDOID = ((Character)allPlayer).GetZDOID();
						if (((ZDOID)(ref zDOID)).UserID == fieldOwnerId)
						{
							val = allPlayer;
							break;
						}
					}
				}
				if (!((Object)(object)val == (Object)null))
				{
					if (!((Object)(object)evaluatedCharacter == (Object)(object)val))
					{
						if (!(evaluatedCharacter is Player) && !evaluatedCharacter.IsTamed() && (int)evaluatedCharacter.GetFaction() != 11)
						{
							if ((int)evaluatedCharacter.GetFaction() != 1)
							{
								if (BaseAI.IsEnemy((Character)(object)val, evaluatedCharacter))
								{
									return (TemporalRelation)4;
								}
								return (TemporalRelation)3;
							}
							return (TemporalRelation)3;
						}
						return (TemporalRelation)2;
					}
					return (TemporalRelation)1;
				}
				return (TemporalRelation)0;
			}
			return (TemporalRelation)0;
		}

		internal static void Tick()
		{
			if (!_installed)
			{
				return;
			}
			float unscaledTime = Time.unscaledTime;
			if (Plugin.Settings.TemporalDiagnosticsEnabled.Value && _log != null && unscaledTime >= _nextDiagnosticsAt)
			{
				_nextDiagnosticsAt = unscaledTime + 1f;
				_log.LogInfo((object)("Temporal creature progression: evaluations=" + _diagnosticEvaluations + ", domainMembers=" + _diagnosticInside + ", slowed=" + _diagnosticSlowed + ", animationApplied=" + _diagnosticApplied + ", activeDomains=" + TemporalFieldNetwork.Registry.ActiveCount + "."));
				_diagnosticEvaluations = 0;
				_diagnosticInside = 0;
				_diagnosticSlowed = 0;
				_diagnosticApplied = 0;
			}
			List<Character> allCharacters = Character.GetAllCharacters();
			for (int i = 0; i < allCharacters.Count; i++)
			{
				Character val = allCharacters[i];
				if ((Object)(object)val == (Object)null || val is Player)
				{
					continue;
				}
				if (!val.IsOwner())
				{
					if (States.TryGetValue(((Object)val).GetInstanceID(), out var value))
					{
						RestoreAnimation(value);
					}
				}
				else
				{
					ApplyAnimation(val, EvaluateScale(val, requireOwner: false));
				}
			}
			if (unscaledTime < _nextPruneAt)
			{
				return;
			}
			_nextPruneAt = unscaledTime + 2f;
			List<int> list = new List<int>();
			foreach (KeyValuePair<int, CreatureState> state in States)
			{
				if (unscaledTime - state.Value.LastSeenAt > 10f)
				{
					list.Add(state.Key);
				}
			}
			for (int j = 0; j < list.Count; j++)
			{
				RestoreAnimation(States[list[j]]);
				States.Remove(list[j]);
			}
		}

		private static void ApplyAnimation(Character character, float scale)
		{
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			if (!States.TryGetValue(((Object)character).GetInstanceID(), out var value))
			{
				return;
			}
			if ((Object)(object)value.Animation == (Object)null)
			{
				value.Animation = ((Component)character).GetComponent<ZSyncAnimation>();
			}
			if ((Object)(object)value.Animation == (Object)null)
			{
				return;
			}
			Animator val = ((_animationAnimatorField == null) ? ((Animator)null) : ((Animator)_animationAnimatorField.GetValue(value.Animation)));
			if ((Object)(object)val == (Object)null)
			{
				return;
			}
			if (scale < 0.999f)
			{
				if (!value.AnimationApplied)
				{
					value.BaselineAnimationSpeed = val.speed;
				}
				value.Animation.SetSpeed(value.BaselineAnimationSpeed * scale);
				value.AnimationApplied = true;
				if (Plugin.Settings.TemporalDiagnosticsEnabled.Value)
				{
					_diagnosticApplied++;
				}
			}
			else
			{
				RestoreAnimation(value);
			}
		}

		private static void RestoreAnimation(CreatureState state)
		{
			if (state != null && state.AnimationApplied)
			{
				if ((Object)(object)state.Animation != (Object)null)
				{
					state.Animation.SetSpeed(state.BaselineAnimationSpeed);
				}
				state.AnimationApplied = false;
			}
		}

		internal static void Shutdown()
		{
			foreach (CreatureState value in States.Values)
			{
				RestoreAnimation(value);
			}
			States.Clear();
			_evaluatedCharacter = null;
			_nextPruneAt = 0f;
			_nextFailureLogAt = 0f;
			_nextDiagnosticsAt = 0f;
			_diagnosticEvaluations = 0;
			_diagnosticInside = 0;
			_diagnosticSlowed = 0;
			_diagnosticApplied = 0;
			_characterStepDepth = 0;
			_aiStepDepth = 0;
			_installed = false;
		}
	}
	internal static class TemporalDomainPresentation
	{
		private struct Key : IEquatable<Key>
		{
			internal long Owner;

			internal int Field;

			public bool Equals(Key other)
			{
				if (Owner == other.Owner)
				{
					return Field == other.Field;
				}
				return false;
			}

			public override bool Equals(object value)
			{
				if (value is Key)
				{
					return Equals((Key)value);
				}
				return false;
			}

			public override int GetHashCode()
			{
				return (Owner.GetHashCode() * 397) ^ Field;
			}
		}

		private sealed class Domain
		{
			internal TemporalFieldPacket Packet;

			internal float ReceivedAt;

			internal GameObject Root;

			internal readonly List<LineRenderer> Lines = new List<LineRenderer>();

			internal TextMesh Label;

			internal TemporalDomainShape BuiltShape;

			internal TemporalPoint BuiltDimensions;
		}

		private static readonly Dictionary<Key, Domain> Domains = new Dictionary<Key, Domain>();

		private static readonly List<Key> Remove = new List<Key>();

		private static Material _material;

		private static int _policyRevision;

		internal static void Receive(TemporalFieldPacket packet, float now)
		{
			//IL_0000: 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_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			if (packet.PolicyRevision > _policyRevision)
			{
				Clear();
				_policyRevision = packet.PolicyRevision;
			}
			Key key = new Key
			{
				Owner = packet.OwnerId,
				Field = packet.FieldId
			};
			Domain value;
			if (!packet.Active)
			{
				if (Domains.TryGetValue(key, out value))
				{
					Destroy(value);
				}
				Domains.Remove(key);
				return;
			}
			if (!Domains.TryGetValue(key, out value))
			{
				value = new Domain();
				Domains.Add(key, value);
			}
			value.Packet = packet;
			value.ReceivedAt = now;
		}

		internal static void Tick()
		{
			//IL_0073: 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_00bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_0135: Unknown result type (might be due to invalid IL or missing references)
			float unscaledTime = Time.unscaledTime;
			Remove.Clear();
			foreach (KeyValuePair<Key, Domain> domain in Domains)
			{
				Domain value = domain.Value;
				if (unscaledTime - value.ReceivedAt > value.Packet.LifetimeSeconds || !Plugin.Settings.TemporalVisualizationEnabled.Value)
				{
					Destroy(value);
					Remove.Add(domain.Key);
					continue;
				}
				if (!WithinDistance(value.Packet))
				{
					if ((Object)(object)value.Root != (Object)null)
					{
						value.Root.SetActive(false);
					}
					continue;
				}
				if ((Object)(object)value.Root == (Object)null || value.BuiltShape != value.Packet.Shape || !Same(value.BuiltDimensions, value.Packet.Dimensions))
				{
					Build(value);
				}
				if (!((Object)(object)value.Root == (Object)null))
				{
					value.Root.SetActive(true);
					value.Root.transform.position = new Vector3(value.Packet.Center.X, value.Packet.Center.Y, value.Packet.Center.Z);
					Style(value, unscaledTime);
				}
			}
			foreach (Key item in Remove)
			{
				Domains.Remove(item);
			}
		}

		private static bool WithinDistance(TemporalFieldPacket packet)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: 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_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			Camera main = Camera.main;
			if ((Object)(object)main == (Object)null)
			{
				return true;
			}
			Vector3 val = default(Vector3);
			((Vector3)(ref val))..ctor(packet.Center.X, packet.Center.Y, packet.Center.Z);
			float value = Plugin.Settings.TemporalVisualizationDistance.Value;
			Vector3 val2 = ((Component)main).transform.position - val;
			return ((Vector3)(ref val2)).sqrMagnitude <= value * value;
		}

		private static void Build(Domain domain)
		{
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Expected O, but got Unknown
			//IL_0057: 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_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_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Expected O, but got Unknown
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
			Destroy(domain);
			Material val = Material();
			if (!((Object)(object)val == (Object)null))
			{
				domain.Root = new GameObject("ValayerTemporalDomain_" + domain.Packet.OwnerId + "_" + domain.Packet.FieldId);
				domain.BuiltShape = domain.Packet.Shape;
				domain.BuiltDimensions = domain.Packet.Dimensions;
				if ((int)domain.Packet.Shape == 0)
				{
					BuildBox(domain, val);
				}
				else
				{
					BuildSphere(domain, val);
				}
				GameObject val2 = new GameObject("authority");
				val2.transform.SetParent(domain.Root.transform, false);
				val2.transform.localPosition = Vector3.up * (domain.Packet.Dimensions.Y * 0.5f + 0.75f);
				domain.Label = val2.AddComponent<TextMesh>();
				domain.Label.anchor = (TextAnchor)7;
				domain.Label.alignment = (TextAlignment)1;
				domain.Label.characterSize = 0.16f;
				domain.Label.fontSize = 32;
				domain.Label.text = ((domain.Packet.PrecedenceRank == 0) ? "HOST · PRIORITY 0" : ("PRIORITY " + domain.Packet.PrecedenceRank));
			}
		}

		private static void BuildBox(Domain domain, Material material)
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: 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_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_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: 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_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)
			for (int i = 0; i < 12; i++)
			{
				LineRenderer val = Line(domain.Root.transform, material, 2, loop: false);
				TemporalPoint val2 = TemporalDomainGeometry.BoxCorner(domain.Packet.Dimensions, TemporalDomainGeometry.BoxEdgeCorner(i, false));
				TemporalPoint val3 = TemporalDomainGeometry.BoxCorner(domain.Packet.Dimensions, TemporalDomainGeometry.BoxEdgeCorner(i, true));
				val.SetPosition(0, new Vector3(val2.X, val2.Y, val2.Z));
				val.SetPosition(1, new Vector3(val3.X, val3.Y, val3.Z));
				domain.Lines.Add(val);
			}
		}

		private static void BuildSphere(Domain domain, Material material)
		{
			//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_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			float num = domain.Packet.Dimensions.X * 0.5f;
			for (int i = 0; i < 3; i++)
			{
				LineRenderer val = Line(domain.Root.transform, material, 65, loop: true);
				for (int j = 0; j <= 64; j++)
				{
					float num2 = (float)j * (float)Math.PI * 2f / 64f;
					TemporalPoint val2 = TemporalDomainGeometry.SpherePoint(num * 2f, (TemporalCirclePlane)i, num2);
					val.SetPosition(j, new Vector3(val2.X, val2.Y, val2.Z));
				}
				domain.Lines.Add(val);
			}
		}

		private static LineRenderer Line(Transform parent, Material material, int count, bool loop)
		{
			//IL_0005: 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)
			GameObject val = new GameObject("hologram");
			val.transform.SetParent(parent, false);
			LineRenderer obj = val.AddComponent<LineRenderer>();
			obj.useWorldSpace = false;
			obj.positionCount = count;
			obj.loop = loop;
			((Renderer)obj).sharedMaterial = material;
			((Renderer)obj).shadowCastingMode = (ShadowCastingMode)0;
			((Renderer)obj).receiveShadows = false;
			((Renderer)obj).lightProbeUsage = (LightProbeUsage)0;
			obj.numCapVertices = 2;
			return obj;
		}

		private static void Style(Domain domain, float now)
		{
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: 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_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0104: Unknown result type (might be due to invalid IL or missing references)
			//IL_0144: Unknown result type (might be due to invalid IL or missing references)
			//IL_0171: Unknown result type (might be due to invalid IL or missing references)
			//IL_017d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0182: Unknown result type (might be due to invalid IL or missing references)
			//IL_0187: Unknown result type (might be due to invalid IL or missing references)
			Color val = ((domain.Packet.PrecedenceRank == 0) ? new Color(0.12f, 0.48f, 1f, 1f) : ((domain.Packet.PrecedenceRank < 1000) ? new Color(0.75f, 0.22f, 1f, 1f) : new Color(0.1f, 0.9f, 0.82f, 1f)));
			float num = 0.55f + 0.2f * Mathf.Sin(now * 2.5f + (float)(domain.Packet.OwnerId % 17));
			Color val2 = default(Color);
			((Color)(ref val2))..ctor(val.r, val.g, val.b, num);
			float num2 = ((domain.Packet.PrecedenceRank == 0) ? 0.07f : ((domain.Packet.PrecedenceRank < 1000) ? 0.05f : 0.035f));
			foreach (LineRenderer line in domain.Lines)
			{
				line.startColor = val2;
				line.endColor = val2;
				line.startWidth = num2;
				line.endWidth = num2;
			}
			if ((Object)(object)domain.Label != (Object)null)
			{
				domain.Label.color = val2;
				Camera main = Camera.main;
				if ((Object)(object)main != (Object)null)
				{
					((Component)domain.Label).transform.rotation = Quaternion.LookRotation(((Component)domain.Label).transform.position - ((Component)main).transform.position);
				}
			}
		}

		private static Material Material()
		{
			//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_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Expected O, but got Unknown
			//IL_00e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0105: Expected O, but got Unknown
			if ((Object)(object)_material != (Object)null)
			{
				return _material;
			}
			Type type = AccessTools.TypeByName("SuperViking.Util.SpeedTrail");
			MethodInfo methodInfo = ((type == null) ? null : AccessTools.Method(type, "FindTrailMaterial", (Type[])null, (Type[])null));
			Material val = (Material)((methodInfo == null) ? null : /*isinst with value type is only supported in some contexts*/);
			if ((Object)(object)val != (Object)null)
			{
				_material = new Material(val)
				{
					name = "ValayerTemporalHologram",
					hideFlags = (HideFlags)61
				};
				return _material;
			}
			Shader val2 = Shader.Find("Legacy Shaders/Particles/Additive");
			if ((Object)(object)val2 == (Object)null)
			{
				val2 = Shader.Find("Particles/Standard Unlit");
			}
			if ((Object)(object)val2 == (Object)null)
			{
				val2 = Shader.Find("Sprites/Default");
			}
			if ((Object)(object)val2 == (Object)null)
			{
				val2 = Shader.Find("UI/Default");
			}
			if ((Object)(object)val2 == (Object)null)
			{
				if (Plugin.Log != null)
				{
					Plugin.Log.LogWarning((object)"Temporal holograms are unavailable because no compatible line material shader was found.");
				}
				return null;
			}
			_material = new Material(val2)
			{
				name = "ValayerTemporalHologram",
				hideFlags = (HideFlags)61
			};
			return _material;
		}

		private static bool Same(TemporalPoint a, TemporalPoint b)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_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)
			if (a.X == b.X && a.Y == b.Y)
			{
				return a.Z == b.Z;
			}
			return false;
		}

		private static void Destroy(Domain domain)
		{
			if ((Object)(object)domain.Root != (Object)null)
			{
				Object.Destroy((Object)(object)domain.Root);
			}
			domain.Root = null;
			domain.Label = null;
			domain.Lines.Clear();
		}

		internal static void Clear()
		{
			foreach (Domain value in Domains.Values)
			{
				Destroy(value);
			}
			Domains.Clear();
			Remove.Clear();
		}

		internal static void Shutdown()
		{
			Clear();
			if ((Object)(object)_material != (Object)null)
			{
				Object.Destroy((Object)(object)_material);
			}
			_material = null;
			_policyRevision = 0;
		}
	}
	internal static class TemporalFieldIntegration
	{
		private const int SuperSpeedFieldId = 1397968964;

		private const float PublishInterval = 0.1f;

		private static ManualLogSource _log;

		private static FieldInfo _scaleField;

		private static FieldInfo _refusedLoggedField;

		private static object _refusalSuppressedFor;

		private static float _nextPublishAt;

		private static bool _publishedActive;

		private static int _sequence;

		internal static void Install(Harmony harmony, ManualLogSource log)
		{
			//IL_00cb: 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_00ec: Expected O, but got Unknown
			//IL_00ec: Expected O, but got Unknown
			//IL_0137: Unknown result type (might be due to invalid IL or missing references)
			//IL_0143: Expected O, but got Unknown
			//IL_0160: Unknown result type (might be due to invalid IL or missing references)
			//IL_016d: Expected O, but got Unknown
			//IL_018a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0197: Expected O, but got Unknown
			_log = log;
			TemporalFieldNetwork.Initialize(log);
			if (!Plugin.Settings.TemporalFieldsEnabled.Value)
			{
				return;
			}
			TemporalProjectileSimulation.Install(harmony, log);
			TemporalCreatureSimulation.Install(harmony, log);
			Type type = AccessTools.TypeByName("SuperViking.SuperSpeed");
			MethodInfo methodInfo = ((type == null) ? null : AccessTools.Method(type, "Step", (Type[])null, (Type[])null));
			_scaleField = ((type == null) ? null : AccessTools.Field(type, "_scale"));
			_refusedLoggedField = ((type == null) ? null : AccessTools.Field(type, "_refusedLogged"));
			if (methodInfo == null || _scaleField == null || _refusedLoggedField == null)
			{
				log.LogInfo((object)"Temporal host authority and projectile execution are active; no local SuperViking activation bridge was found.");
				return;
			}
			harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(TemporalFieldIntegration), "SuperSpeedStepPostfix", (Type[])null), new HarmonyMethod(typeof(TemporalFieldIntegration), "SuperSpeedStepTranspiler", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null);
			MethodInfo methodInfo2 = AccessTools.Method(type, "OnDisable", (Type[])null, (Type[])null);
			MethodInfo methodInfo3 = AccessTools.Method(type, "OnDestroy", (Type[])null, (Type[])null);
			MethodInfo methodInfo4 = AccessTools.Method(type, "RestoreNow", (Type[])null, (Type[])null);
			if (methodInfo4 != null)
			{
				harmony.Patch((MethodBase)methodInfo4, (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(TemporalFieldIntegration), "SuperSpeedRestoreTranspiler", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null);
			}
			if (methodInfo2 != null)
			{
				harmony.Patch((MethodBase)methodInfo2, (HarmonyMethod)null, new HarmonyMethod(typeof(TemporalFieldIntegration), "SuperSpeedInterruptedPostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			if (methodInfo3 != null)
			{
				harmony.Patch((MethodBase)methodInfo3, (HarmonyMethod)null, new HarmonyMethod(typeof(TemporalFieldIntegration), "SuperSpeedInterruptedPostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			log.LogInfo((object)"Temporal fields replace SuperSpeed's global clock writes with configured owner-authoritative creature/projectile domains; player characters remain unaffected.");
		}

		internal static void Tick()
		{
			TemporalFieldNetwork.Tick();
			TemporalProjectileSimulation.Tick();
			TemporalCreatureSimulation.Tick();
		}

		private static IEnumerable<CodeInstruction> SuperSpeedStepTranspiler(IEnumerable<CodeInstruction> instructions)
		{
			return ReplaceGlobalTimeWrites(instructions);
		}

		private static IEnumerable<CodeInstruction> SuperSpeedRestoreTranspiler(IEnumerable<CodeInstruction> instructions)
		{
			return ReplaceGlobalTimeWrites(instructions);
		}

		private static IEnumerable<CodeInstruction> ReplaceGlobalTimeWrites(IEnumerable<CodeInstruction> instructions)
		{
			MethodInfo fadeTimeScale = AccessTools.Method(typeof(Game), "FadeTimeScale", (Type[])null, (Type[])null);
			MethodInfo setTimeScale = AccessTools.PropertySetter(typeof(Time), "timeScale");
			MethodInfo setFixedDeltaTime = AccessTools.PropertySetter(typeof(Time), "fixedDeltaTime");
			MethodInfo ignoreFade = AccessTools.Method(typeof(TemporalFieldIntegration), "IgnoreFadeTimeScale", (Type[])null, (Type[])null);
			MethodInfo ignoreTimeScale = AccessTools.Method(typeof(TemporalFieldIntegration), "IgnoreTimeScale", (Type[])null, (Type[])null);
			MethodInfo ignoreFixedStep = AccessTools.Method(typeof(TemporalFieldIntegration), "IgnoreFixedDeltaTime", (Type[])null, (Type[])null);
			foreach (CodeInstruction instruction in instructions)
			{
				if (CodeInstructionExtensions.Calls(instruction, fadeTimeScale))
				{
					instruction.opcode = OpCodes.Call;
					instruction.operand = ignoreFade;
				}
				else if (CodeInstructionExtensions.Calls(instruction, setTimeScale))
				{
					instruction.opcode = OpCodes.Call;
					instruction.operand = ignoreTimeScale;
				}
				else if (CodeInstructionExtensions.Calls(instruction, setFixedDeltaTime))
				{
					instruction.opcode = OpCodes.Call;
					instruction.operand = ignoreFixedStep;
				}
				yield return instruction;
			}
		}

		private static void IgnoreFadeTimeScale(float scale, float transitionSeconds)
		{
		}

		private static void IgnoreTimeScale(float scale)
		{
		}

		private static void IgnoreFixedDeltaTime(float step)
		{
		}

		private static void SuperSpeedStepPostfix(object __instance)
		{
			try
			{
				if (_refusalSuppressedFor != __instance)
				{
					_refusedLoggedField.SetValue(__instance, true);
					_refusalSuppressedFor = __instance;
				}
				Player localPlayer = Player.m_localPlayer;
				float num = (float)_scaleField.GetValue(__instance);
				bool num2 = (Object)(object)localPlayer != (Object)null && (Object)(object)ZNet.instance != (Object)null && !((Character)localPlayer).IsDead() && !((Character)localPlayer).IsTeleporting() && num < 0.999f;
				float unscaledTime = Time.unscaledTime;
				if (!num2)
				{
					if (_publishedActive)
					{
						Publish(active: false);
					}
				}
				else if (!(unscaledTime + 1E-06f < _nextPublishAt))
				{
					Publish(active: true);
					_nextPublishAt = unscaledTime + 0.1f;
				}
			}
			catch (Exception ex)
			{
				if (_log != null)
				{
					_log.LogWarning((object)("Temporal SuperSpeed bridge failed open: " + ex.Message));
				}
			}
		}

		private static void Publish(bool active)
		{
			if (TemporalFieldNetwork.Request(1397968964, ++_sequence, active))
			{
				_publishedActive = active;
			}
		}

		private static void SuperSpeedInterruptedPostfix()
		{
			if (_publishedActive)
			{
				Publish(active: false);
				_nextPublishAt = 0f;
			}
		}

		internal static void Shutdown()
		{
			if (_publishedActive)
			{
				Publish(active: false);
			}
			_publishedActive = false;
			_nextPublishAt = 0f;
			_refusalSuppressedFor = null;
			TemporalProjectileSimulation.Shutdown();
			TemporalCreatureSimulation.Shutdown();
			TemporalFieldNetwork.Shutdown();
		}
	}
	internal static class TemporalFieldNetwork
	{
		private struct DomainKey : IEquatable<DomainKey>
		{
			internal long Owner;

			internal int Field;

			public bool Equals(DomainKey other)
			{
				if (Owner == other.Owner)
				{
					return Field == other.Field;
				}
				return false;
			}

			public override bool Equals(object value)
			{
				if (value is DomainKey)
				{
					return Equals((DomainKey)value);
				}
				return false;
			}

			public override int GetHashCode()
			{
				return ((int)Owner * 397) ^ Field;
			}
		}

		private sealed class DomainAnchor
		{
			internal TemporalPoint Center;

			internal float ExpiresAt;
		}

		private const string RequestRpc = "Valayer_TemporalDomainRequest_v4";

		private const string EffectiveRpc = "Valayer_TemporalDomainEffective_v4";

		private const string CapabilityRpc = "Valayer_TemporalCapability_v1";

		private static ZRoutedRpc _registeredRpc;

		private static ManualLogSource _log;

		private static string _policyFingerprint;

		private static int _policyRevision = 1;

		private static long _requests;

		private static long _effectiveSent;

		private static long _effectiveReceived;

		private static long _requestsAccepted;

		private static long _requestsRejected;

		private static float _nextPeerReconcileAt;

		private static float _nextCapabilityAt;

		private static readonly Dictionary<long, float> CompatiblePeers = new Dictionary<long, float>();

		private static readonly Dictionary<DomainKey, DomainAnchor> DomainAnchors = new Dictionary<DomainKey, DomainAnchor>();

		internal static readonly TemporalFieldRegistry Registry = new TemporalFieldRegistry();

		private static readonly TemporalAuthorityRequestGate RequestGate = new TemporalAuthorityRequestGate();

		internal static int PolicyRevision => _policyRevision;

		internal static void Initialize(ManualLogSource log)
		{
			_log = log;
		}

		internal static void Tick()
		{
			EnsureRegistered();
			PublishCapability();
			Registry.Expire(Time.unscaledTime);
			TemporalDomainPresentation.Tick();
			RequestGate.Expire(Time.unscaledTime);
			if (!((Object)(object)ZNet.instance != (Object)null) || !ZNet.instance.IsServer() || !(Time.unscaledTime >= _nextPeerReconcileAt))
			{
				return;
			}
			_nextPeerReconcileAt = Time.unscaledTime + 1f;
			RequestGate.RemoveDisconnected((Predicate<long>)IsKnownPeer);
			List<long> list = new List<long>();
			foreach (long key in CompatiblePeers.Keys)
			{
				if (!IsKnownPeer(key))
				{
					list.Add(key);
				}
			}
			foreach (long item in list)
			{
				CompatiblePeers.Remove(item);
			}
			PruneDomainAnchors(Time.unscaledTime);
		}

		internal static bool Request(int fieldId, int sequence, bool active)
		{
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Expected O, but got Unknown
			EnsureRegistered();
			if (_registeredRpc == null || (Object)(object)ZNet.instance == (Object)null)
			{
				return false;
			}
			ZPackage val = new ZPackage();
			val.Write(4);
			val.Write(fieldId);
			val.Write(sequence);
			val.Write(active);
			_registeredRpc.InvokeRoutedRPC("Valayer_TemporalDomainRequest_v4", new object[1] { val });
			_requests++;
			return true;
		}

		private static void EnsureRegistered()
		{
			ZRoutedRpc instance = ZRoutedRpc.instance;
			if (instance == _registeredRpc)
			{
				return;
			}
			Registry.Clear();
			RequestGate.Clear();
			CompatiblePeers.Clear();
			DomainAnchors.Clear();
			TemporalDomainPresentation.Clear();
			_registeredRpc = instance;
			if (instance != null)
			{
				instance.Register<ZPackage>("Valayer_TemporalDomainRequest_v4", (Action<long, ZPackage>)ReceiveRequest);
				instance.Register<ZPackage>("Valayer_TemporalDomainEffective_v4", (Action<long, ZPackage>)ReceiveEffective);
				instance.Register<ZPackage>("Valayer_TemporalCapability_v1", (Action<long, ZPackage>)ReceiveCapability);
				if (_log != null)
				{
					_log.LogInfo((object)("Registered authoritative temporal-domain RPC protocol v" + 4 + "."));
				}
			}
		}

		private static void ReceiveRequest(long sender, ZPackage package)
		{
			//IL_0153: Unknown result type (might be due to invalid IL or missing references)
			//IL_014c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0158: Unknown result type (might be due to invalid IL or missing references)
			//IL_01be: Unknown result type (might be due to invalid IL or missing references)
			//IL_019a: Unknown result type (might be due to invalid IL or missing references)
			//IL_019f: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f3: 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_020b: Unknown result type (might be due to invalid IL or missing references)
			//IL_020e: Invalid comparison between Unknown and I4
			//IL_024a: Unknown result type (might be due to invalid IL or missing references)
			//IL_023d: Unknown result type (might be due to invalid IL or missing references)
			//IL_024f: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_02bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_0268: Unknown result type (might be due to invalid IL or missing references)
			//IL_0276: Unknown result type (might be due to invalid IL or missing references)
			//IL_0284: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_033b: Unknown result type (might be due to invalid IL or missing references)
			//IL_033d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0344: Unknown result type (might be due to invalid IL or missing references)
			//IL_0346: Unknown result type (might be due to invalid IL or missing references)
			//IL_034d: Unknown result type (might be due to invalid IL or missing references)
			//IL_034f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0399: Unknown result type (might be due to invalid IL or missing references)
			//IL_03aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_03b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_03b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_03b7: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if ((Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsServer() || !Plugin.Settings.TemporalFieldsEnabled.Value)
				{
					return;
				}
				int num = package.ReadInt();
				int num2 = package.ReadInt();
				int num3 = package.ReadInt();
				bool flag = package.ReadBool();
				if (num != 4 || num2 == 0)
				{
					if (_log != null)
					{
						_log.LogWarning((object)("Rejected temporal request with incompatible protocol/field from authenticated sender " + sender + "."));
					}
					return;
				}
				if (!IsKnownPeer(sender))
				{
					if (_log != null)
					{
						_log.LogWarning((object)("Rejected temporal request from sender not present in the server peer set: " + sender + "."));
					}
					return;
				}
				if (flag && !AllPeersCompatible())
				{
					_requestsRejected++;
					if (_log != null)
					{
						_log.LogWarning((object)("Rejected temporal activation until every connected peer reports enabled protocol v" + 4 + "."));
					}
					return;
				}
				DomainKey key = new DomainKey
				{
					Owner = sender,
					Field = num2
				};
				DomainAnchors.TryGetValue(key, out var value);
				Vector3 position = (Vector3)((value == null) ? Vector3.zero : new Vector3(value.Center.X, value.Center.Y, value.Center.Z));
				if (flag && value == null && !TryGetOwnerPosition(sender, out position))
				{
					if (_log != null)
					{
						_log.LogWarning((object)("Rejected temporal activation because no authoritative character ZDO represents sender " + sender + "."));
					}
					return;
				}
				if (!flag)
				{
					position = Vector3.zero;
				}
				if ((int)RequestGate.Receive(sender, num2, num3, flag, Time.unscaledTime, Plugin.Settings.TemporalDomainLifetime.Value) != 0)
				{
					_requestsRejected++;
					return;
				}
				_requestsAccepted++;
				RefreshPolicyRevision();
				TemporalDomainShape value2 = Plugin.Settings.TemporalDomainShape.Value;
				float value3 = Plugin.Settings.TemporalSphereDiameter.Value;
				TemporalPoint dimensions = (((int)value2 == 1) ? new TemporalPoint(value3, value3, value3) : new TemporalPoint(Plugin.Settings.TemporalBoxSizeX.Value, Plugin.Settings.TemporalBoxSizeY.Value, Plugin.Settings.TemporalBoxSizeZ.Value));
				float value4 = Plugin.Settings.TemporalSpatialResolution.Value;
				TemporalPoint center = default(TemporalPoint);
				if (value == null)
				{
					((TemporalPoint)(ref center))..ctor(Quantize(position.x, value4), Quantize(position.y, value4), Quantize(position.z, value4));
					if (flag)
					{
						value = new DomainAnchor
						{
							Center = center
						};
						DomainAnchors[key] = value;
					}
				}
				else
				{
					center = value.Center;
				}
				if (flag && value != null)
				{
					value.ExpiresAt = Time.unscaledTime + Plugin.Settings.TemporalDomainLifetime.Value;
				}
				BroadcastEffective(new TemporalFieldPacket
				{
					ProtocolVersion = 4,
					FieldId = num2,
					Sequence = num3,
					OwnerId = sender,
					AuthorityId = ZNet.GetUID(),
					PolicyRevision = _policyRevision,
					PrecedenceRank = ResolvePrecedence(sender),
					Active = flag,
					Center = center,
					Shape = value2,
					Dimensions = dimensions,
					TimeScale = Plugin.Settings.TemporalEffectiveTimeScale.Value,
					SimulationResolutionHz = Plugin.Settings.TemporalSimulationResolution.Value,
					LifetimeSeconds = Plugin.Settings.TemporalDomainLifetime.Value,
					Audience = (TemporalAudience)0,
					Permissions = (TemporalInteractionPermissions)(Plugin.Settings.TemporalAffectedEntities.Value & 0x7F)
				});
				if (!flag)
				{
					DomainAnchors.Remove(key);
				}
			}
			catch (Exception ex)
			{
				if (_log != null)
				{
					_log.LogWarning((object)("Rejected malformed temporal-domain request: " + ex.Message));
				}
			}
		}

		private static void BroadcastEffective(TemporalFieldPacket packet)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Expected O, but got Unknown
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			ZPackage val = new ZPackage();
			WritePacket(val, packet);
			_registeredRpc.InvokeRoutedRPC(0L, "Valayer_TemporalDomainEffective_v4", new object[1] { val });
			_effectiveSent++;
		}

		private static void ReceiveEffective(long sender, ZPackage package)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: 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_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				long num = ExpectedAuthorityId();
				if (sender != 0L && sender == num)
				{
					TemporalFieldPacket val = ReadPacket(package);
					if (val.AuthorityId == num && (int)Registry.Receive(num, val, Time.unscaledTime) == 0)
					{
						_effectiveReceived++;
						TemporalDomainPresentation.Receive(val, Time.unscaledTime);
					}
				}
			}
			catch (Exception ex)
			{
				if (_log != null)
				{
					_log.LogWarning((object)("Rejected malformed effective temporal domain: " + ex.Message));
				}
			}
		}

		private static long ExpectedAuthorityId()
		{
			if ((Object)(object)ZNet.instance == (Object)null)
			{
				return 0L;
			}
			if (ZNet.instance.IsServer())
			{
				return ZNet.GetUID();
			}
			return ZNet.instance.GetServerPeer()?.m_uid ?? 0;
		}

		private static void PublishCapability()
		{
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Expected O, but got Unknown
			if (_registeredRpc != null && !((Object)(object)ZNet.instance == (Object)null) && !ZNet.instance.IsServer() && !(Time.unscaledTime < _nextCapabilityAt))
			{
				_nextCapabilityAt = Time.unscaledTime + 3f;
				ZPackage val = new ZPackage();
				val.Write(4);
				val.Write(Plugin.Settings.TemporalFieldsEnabled.Value);
				_registeredRpc.InvokeRoutedRPC("Valayer_TemporalCapability_v1", new object[1] { val });
			}
		}

		private static void ReceiveCapability(long sender, ZPackage package)
		{
			try
			{
				if (!((Object)(object)ZNet.instance == (Object)null) && ZNet.instance.IsServer() && IsKnownPeer(sender))
				{
					int num = package.ReadInt();
					bool flag = package.ReadBool();
					if (TemporalCompatibilityRules.IsCompatible(num, flag, 0f))
					{
						CompatiblePeers[sender] = Time.unscaledTime;
					}
					else
					{
						CompatiblePeers.Remove(sender);
					}
				}
			}
			catch
			{
				CompatiblePeers.Remove(sender);
			}
		}

		private static bool AllPeersCompatible()
		{
			if ((Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsServer())
			{
				return false;
			}
			float unscaledTime = Time.unscaledTime;
			foreach (ZNetPeer peer in ZNet.instance.GetPeers())
			{
				if (peer != null && peer.m_uid != ZNet.GetUID() && (!CompatiblePeers.TryGetValue(peer.m_uid, out var value) || !TemporalCompatibilityRules.IsCompatible(4, true, unscaledTime - value)))
				{
					return false;
				}
			}
			return true;
		}

		internal static string CompatibilitySummary()
		{
			if ((Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsServer())
			{
				return "authority unavailable";
			}
			int num = 0;
			int num2 = 0;
			float unscaledTime = Time.unscaledTime;
			foreach (ZNetPeer peer in ZNet.instance.GetPeers())
			{
				if (peer != null && peer.m_uid != ZNet.GetUID())
				{
					num++;
					if (CompatiblePeers.TryGetValue(peer.m_uid, out var value) && TemporalCompatibilityRules.IsCompatible(4, true, unscaledTime - value))
					{
						num2++;
					}
				}
			}
			return num2 + "/" + num + " remote peers compatible";
		}

		internal static void NotifyPolicyChanged()
		{
			RefreshPolicyRevision();
		}

		private static bool IsKnownPeer(long sender)
		{
			if (sender == ZNet.GetUID())
			{
				return true;
			}
			foreach (ZNetPeer peer in ZNet.instance.GetPeers())
			{
				if (peer != null && peer.m_uid == sender)
				{
					return true;
				}
			}
			return false;
		}

		private static Player FindPlayer(long ownerId)
		{
			//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)
			foreach (Player allPlayer in Player.GetAllPlayers())
			{
				if ((Object)(object)allPlayer != (Object)null)
				{
					ZDOID zDOID = ((Character)allPlayer).GetZDOID();
					if (((ZDOID)(ref zDOID)).UserID == ownerId)
					{
						return allPlayer;
					}
				}
			}
			return null;
		}

		private static bool TryGetOwnerPosition(long ownerId, out Vector3 position)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: 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_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			Player val = FindPlayer(ownerId);
			if ((Object)(object)val != (Object)null)
			{
				position = ((Component)val).transform.position;
				return true;
			}
			foreach (ZNetPeer peer in ZNet.instance.GetPeers())
			{
				if (peer != null && peer.m_uid == ownerId && !((ZDOID)(ref peer.m_characterID)).IsNone())
				{
					ZDO val2 = ((ZDOMan.instance == null) ? null : ZDOMan.instance.GetZDO(peer.m_characterID));
					if (val2 != null)
					{
						position = val2.GetPosition();
						return true;
					}
				}
			}
			position = Vector3.zero;
			return false;
		}

		private static int ResolvePrecedence(long ownerId)
		{
			if (ownerId == ZNet.GetUID() && (Object)(object)FindPlayer(ownerId) != (Object)null)
			{
				return 0;
			}
			string[] array = (Plugin.Settings.TemporalOtherPlayerPrecedence.Value ?? string.Empty).Split(new char[3] { ',', ';', ' ' }, StringSplitOptions.RemoveEmptyEntries);
			for (int i = 0; i < array.Length; i++)
			{
				if (long.TryParse(array[i], out var result) && result == ownerId)
				{
					return i + 1;
				}
			}
			return 1000;
		}

		private static void PruneDomainAnchors(float now)
		{
			List<DomainKey> list = new List<DomainKey>();
			foreach (KeyValuePair<DomainKey, DomainAnchor> domainAnchor in DomainAnchors)
			{
				if (domainAnchor.Value == null || now >= domainAnchor.Value.ExpiresAt || !IsKnownPeer(domainAnchor.Key.Owner))
				{
					list.Add(domainAnchor.Key);
				}
			}
			foreach (DomainKey item in list)
			{
				DomainAnchors.Remove(item);
			}
		}

		private static void RefreshPolicyRevision()
		{
			//IL_0013: 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_0155: Unknown result type (might be due to invalid IL or missing references)
			//IL_015a: Unknown result type (might be due to invalid IL or missing references)
			string text = ((object)Plugin.Settings.TemporalDomainShape.Value/*cast due to .constrained prefix*/).ToString() + "|" + Plugin.Settings.TemporalBoxSizeX.Value + "|" + Plugin.Settings.TemporalBoxSizeY.Value + "|" + Plugin.Settings.TemporalBoxSizeZ.Value + "|" + Plugin.Settings.TemporalSphereDiameter.Value + "|" + Plugin.Settings.TemporalEffectiveTimeScale.Value + "|" + Plugin.Settings.TemporalSpatialResolution.Value + "|" + Plugin.Settings.TemporalSimulationResolution.Value + "|" + Plugin.Settings.TemporalDomainLifetime.Value + "|" + ((object)Plugin.Settings.TemporalAffectedEntities.Value/*cast due to .constrained prefix*/).ToString() + "|" + Plugin.Settings.TemporalOtherPlayerPrecedence.Value;
			if (_policyFingerprint != null && _policyFingerprint != text)
			{
				_policyRevision++;
			}
			_policyFingerprint = text;
		}

		private static float Quantize(float value, float resolution)
		{
			return Mathf.Round(value / resolution) * resolution;
		}

		private static void WritePacket(ZPackage package, TemporalFieldPacket packet)
		{
			//IL_0001: 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_0019: 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_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: 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_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_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)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Expected I4, but got Unknown
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: 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_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_00ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f4: Expected I4, but got Unknown
			//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0100: Expected I4, but got Unknown
			package.Write(packet.ProtocolVersion);
			package.Write(packet.FieldId);
			package.Write(packet.Sequence);
			package.Write(packet.OwnerId);
			package.Write(packet.AuthorityId);
			package.Write(packet.PolicyRevision);
			package.Write(packet.PrecedenceRank);
			package.Write(packet.Active);
			package.Write(new Vector3(packet.Center.X, packet.Center.Y, packet.Center.Z));
			package.Write((int)packet.Shape);
			package.Write(new Vector3(packet.Dimensions.X, packet.Dimensions.Y, packet.Dimensions.Z));
			package.Write(packet.TimeScale);
			package.Write(packet.SimulationResolutionHz);
			package.Write(packet.LifetimeSeconds);
			package.Write((int)packet.Audience);
			package.Write((int)packet.Permissions);
		}

		private static TemporalFieldPacket ReadPacket(ZPackage package)
		{
			//IL_0002: 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_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: 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)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0092: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: 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_00aa: 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_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0105: Unknown result type (might be due to invalid IL or missing references)
			//IL_010a: Unknown result type (might be due to invalid IL or missing references)
			TemporalFieldPacket result = new TemporalFieldPacket
			{
				ProtocolVersion = package.ReadInt(),
				FieldId = package.ReadInt(),
				Sequence = package.ReadInt(),
				OwnerId = package.ReadLong(),
				AuthorityId = package.ReadLong(),
				PolicyRevision = package.ReadInt(),
				PrecedenceRank = package.ReadInt(),
				Active = package.ReadBool()
			};
			Vector3 val = package.ReadVector3();
			result.Center = new TemporalPoint(val.x, val.y, val.z);
			result.Shape = (TemporalDomainShape)package.ReadInt();
			Vector3 val2 = package.ReadVector3();
			result.Dimensions = new TemporalPoint(val2.x, val2.y, val2.z);
			result.TimeScale = package.ReadSingle();
			result.SimulationResolutionHz = package.ReadSingle();
			result.LifetimeSeconds = package.ReadSingle();
			result.Audience = (TemporalAudience)package.ReadInt();
			result.Permissions = (TemporalInteractionPermissions)package.ReadInt();
			return result;
		}

		internal static void Shutdown()
		{
			Registry.Clear();
			RequestGate.Clear();
			CompatiblePeers.Clear();
			DomainAnchors.Clear();
			TemporalDomainPresentation.Shutdown();
			if (_log != null && (_requests != 0L || _effectiveSent != 0L || _effectiveReceived != 0L))
			{
				_log.LogInfo((object)("Temporal-domain traffic: requests=" + _requests + ", effectiveSent=" + _effectiveSent + ", effectiveReceived=" + _effectiveReceived + ", authorityAccepted=" + _requestsAccepted + ", authorityRejected=" + _requestsRejected + "."));
			}
			_registeredRpc = null;
			_requests = 0L