Decompiled source of Thunderfen v1.0.7

patchers/Peak3GoToVoidBridge.dll

Decompiled a week ago
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.CompilerServices;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Collections.Generic;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: AssemblyVersion("0.0.0.0")]
public static class Peak3GoToVoidBridge
{
	public static IEnumerable<string> TargetDLLs => new string[1] { "Assembly-CSharp.dll" };

	public static void Patch(AssemblyDefinition assembly)
	{
		//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_0074: Unknown result type (might be due to invalid IL or missing references)
		//IL_0079: Unknown result type (might be due to invalid IL or missing references)
		//IL_016a: Unknown result type (might be due to invalid IL or missing references)
		//IL_016f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0186: Unknown result type (might be due to invalid IL or missing references)
		//IL_018b: Unknown result type (might be due to invalid IL or missing references)
		//IL_019f: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a4: Unknown result type (might be due to invalid IL or missing references)
		//IL_0206: Unknown result type (might be due to invalid IL or missing references)
		//IL_0211: Unknown result type (might be due to invalid IL or missing references)
		//IL_0218: Expected O, but got Unknown
		//IL_0235: Unknown result type (might be due to invalid IL or missing references)
		//IL_023f: Expected O, but got Unknown
		//IL_0251: Unknown result type (might be due to invalid IL or missing references)
		//IL_0264: Unknown result type (might be due to invalid IL or missing references)
		//IL_0279: Unknown result type (might be due to invalid IL or missing references)
		//IL_028e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0293: 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_02c6: Expected O, but got Unknown
		//IL_02cd: Unknown result type (might be due to invalid IL or missing references)
		//IL_02d2: Unknown result type (might be due to invalid IL or missing references)
		//IL_02d8: Unknown result type (might be due to invalid IL or missing references)
		//IL_02dd: 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)
		if (assembly == null || ((AssemblyNameReference)assembly.Name).Name != "Assembly-CSharp")
		{
			return;
		}
		TypeDefinition val = null;
		Enumerator<TypeDefinition> enumerator = assembly.MainModule.Types.GetEnumerator();
		try
		{
			while (enumerator.MoveNext())
			{
				TypeDefinition current = enumerator.Current;
				if (((MemberReference)current).FullName == "MapHandler")
				{
					val = current;
					break;
				}
			}
		}
		finally
		{
			((IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose();
		}
		if (val == null)
		{
			return;
		}
		MethodDefinition val2 = null;
		Enumerator<MethodDefinition> enumerator2 = val.Methods.GetEnumerator();
		try
		{
			while (enumerator2.MoveNext())
			{
				MethodDefinition current2 = enumerator2.Current;
				if (!(((MemberReference)current2).Name != "GoToVoidRoutine"))
				{
					if (((MethodReference)current2).Parameters.Count == 1 && ((MemberReference)((ParameterReference)((MethodReference)current2).Parameters[0]).ParameterType).FullName == "System.Boolean")
					{
						Console.WriteLine("[PEAK 3 bridge] Boolean overload already exists; no change needed.");
						return;
					}
					if (((MethodReference)current2).Parameters.Count == 0)
					{
						val2 = current2;
					}
				}
			}
		}
		finally
		{
			((IDisposable)enumerator2/*cast due to .constrained prefix*/).Dispose();
		}
		if (val2 == null || !val2.IsStatic || !val2.IsPublic || ((MemberReference)((MethodReference)val2).ReturnType).FullName != "System.Collections.IEnumerator" || !val2.HasBody || val2.Body.Instructions.Count != 3)
		{
			return;
		}
		Collection<Instruction> instructions = val2.Body.Instructions;
		object operand = instructions[1].Operand;
		MethodReference val3 = (MethodReference)((operand is MethodReference) ? operand : null);
		if (instructions[0].OpCode != OpCodes.Ldc_I4_0 || instructions[1].OpCode != OpCodes.Newobj || instructions[2].OpCode != OpCodes.Ret || val3 == null || ((MemberReference)((MemberReference)val3).DeclaringType).FullName != "MapHandler/<GoToVoidRoutine>d__66" || val3.Parameters.Count != 1 || ((MemberReference)((ParameterReference)val3.Parameters[0]).ParameterType).FullName != "System.Int32")
		{
			return;
		}
		MethodDefinition val4 = new MethodDefinition(((MemberReference)val2).Name, val2.Attributes, ((MethodReference)val2).ReturnType);
		((MethodReference)val4).Parameters.Add(new ParameterDefinition("clearStatus", (ParameterAttributes)0, assembly.MainModule.TypeSystem.Boolean));
		ILProcessor iLProcessor = val4.Body.GetILProcessor();
		iLProcessor.Append(iLProcessor.Create(OpCodes.Ldc_I4_0));
		iLProcessor.Append(iLProcessor.Create(OpCodes.Newobj, val3));
		iLProcessor.Append(iLProcessor.Create(OpCodes.Ret));
		Enumerator<CustomAttribute> enumerator3 = val2.CustomAttributes.GetEnumerator();
		try
		{
			while (enumerator3.MoveNext())
			{
				CustomAttribute current3 = enumerator3.Current;
				if (((MemberReference)current3.AttributeType).FullName != "System.Runtime.CompilerServices.IteratorStateMachineAttribute")
				{
					continue;
				}
				CustomAttribute val5 = new CustomAttribute(current3.Constructor);
				Enumerator<CustomAttributeArgument> enumerator4 = current3.ConstructorArguments.GetEnumerator();
				try
				{
					while (enumerator4.MoveNext())
					{
						CustomAttributeArgument current4 = enumerator4.Current;
						val5.ConstructorArguments.Add(current4);
					}
				}
				finally
				{
					((IDisposable)enumerator4/*cast due to .constrained prefix*/).Dispose();
				}
				val4.CustomAttributes.Add(val5);
			}
		}
		finally
		{
			((IDisposable)enumerator3/*cast due to .constrained prefix*/).Dispose();
		}
		val.Methods.Add(val4);
		Console.WriteLine("[PEAK 3 bridge] Added MapHandler.GoToVoidRoutine(bool) compatibility overload.");
	}
}

patchers/ThunderfenProfilePreloader.dll

Decompiled a week ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Configuration;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Mono.Cecil;
using PoisonForestSolo;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyVersion("0.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
public static class ThunderfenProfilePreloader
{
	public static IEnumerable<string> TargetDLLs => new string[0];

	public static void Patch(AssemblyDefinition assembly)
	{
	}

	public static void Initialize()
	{
		PreloaderStatus.MarkStarted();
		string pluginPath = Paths.PluginPath;
		string text;
		try
		{
			text = FindPackage(pluginPath);
		}
		catch (Exception ex)
		{
			PreloaderStatus.Report(ex.Message);
			return;
		}
		if (text == null)
		{
			PreloaderStatus.Report("Could not find Thunderfen's ThunderfenSolo and PLL_Biomes folders in BepInEx/plugins. Reinstall Thunderfen.");
		}
		try
		{
			ProfileBiome.RemoveLegacyCopy(pluginPath, text);
		}
		catch (Exception ex2)
		{
			Console.WriteLine("[Thunderfen] Could not remove the copy staged by Thunderfen 1.0.3 or earlier: " + ex2.Message);
		}
		if (text == null)
		{
			return;
		}
		try
		{
			ProfileBiome.Install(pluginPath, text);
		}
		catch (Exception ex3)
		{
			PreloaderStatus.Report("Could not prepare the PLL biome: " + ex3.Message);
		}
		try
		{
			ReleaseRoute.Install(Paths.ConfigPath);
		}
		catch (Exception ex4)
		{
			PreloaderStatus.Report("Could not prepare the PLL route: " + ex4.Message);
		}
	}

	private static string FindPackage(string plugins)
	{
		string[] array = new string[1] { plugins }.Concat(Directory.EnumerateDirectories(plugins)).Where(HasPackage).ToArray();
		if (array.Length > 1)
		{
			throw new InvalidOperationException("Found more than one Thunderfen install in BepInEx/plugins (" + string.Join(", ", array.Select(Describe)) + "). Keep one and remove the other.");
		}
		return array.FirstOrDefault();
	}

	private static string Describe(string folder)
	{
		return string.Equals(Path.GetFullPath(folder), Path.GetFullPath(Paths.PluginPath), StringComparison.OrdinalIgnoreCase) ? "a manual install" : Path.GetFileName(folder);
	}

	private static bool HasPackage(string folder)
	{
		return File.Exists(Path.Combine(folder, "ThunderfenSolo", "PoisonForestSolo.dll")) && File.Exists(Path.Combine(folder, "PLL_Biomes", "prototype-first-ridge.pll"));
	}
}
namespace PoisonForestSolo
{
	internal static class PreloaderStatus
	{
		private const string RanKey = "THUNDERFEN_PRELOADER_RAN";

		private const string IssueKey = "THUNDERFEN_PRELOADER_ISSUE";

		internal static void MarkStarted()
		{
			Environment.SetEnvironmentVariable("THUNDERFEN_PRELOADER_RAN", "1");
		}

		internal static void Report(string message)
		{
			Console.WriteLine("[Thunderfen] " + message);
			string environmentVariable = Environment.GetEnvironmentVariable("THUNDERFEN_PRELOADER_ISSUE");
			Environment.SetEnvironmentVariable("THUNDERFEN_PRELOADER_ISSUE", string.IsNullOrEmpty(environmentVariable) ? message : (environmentVariable + " " + message));
		}

		internal static string Describe(string failure)
		{
			if (Environment.GetEnvironmentVariable("THUNDERFEN_PRELOADER_RAN") != "1")
			{
				return failure + " Thunderfen's preloader did not run. Install Thunderfen with a mod manager, or copy its patchers folder into BepInEx/patchers.";
			}
			string environmentVariable = Environment.GetEnvironmentVariable("THUNDERFEN_PRELOADER_ISSUE");
			return failure + " " + (string.IsNullOrEmpty(environmentVariable) ? "See the [Thunderfen] lines near the top of BepInEx/LogOutput.log." : environmentVariable);
		}
	}
	internal static class ProfileBiome
	{
		private const string BundleName = "prototype-first-ridge.pll";

		private const string Folder = "PLL_Biomes";

		private const string ExpectedHash = "2D0E0B6FD6D57EB649A4731AFA5AA39F5A1749DFF9E88A877ACDC30C12333A5E";

		private const string DiscoveryKey = "THUNDERFEN_PLL_PROFILE_BUNDLE";

		private const StringComparison PathComparison = StringComparison.OrdinalIgnoreCase;

		private static string discoveryFolder;

		private static string bundle;

		private static string hidden;

		internal static void Install(string plugins, string package)
		{
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Expected O, but got Unknown
			string text = RootFolder(plugins);
			string fullPath = Path.GetFullPath(Path.Combine(package, "PLL_Biomes", "prototype-first-ridge.pll"));
			RequireBundle(fullPath);
			string text2 = Path.Combine(text, "prototype-first-ridge.pll");
			if (string.Equals(text2, fullPath, StringComparison.OrdinalIgnoreCase) || (File.Exists(text2) && Hash(text2) == "2D0E0B6FD6D57EB649A4731AFA5AA39F5A1749DFF9E88A877ACDC30C12333A5E"))
			{
				Environment.SetEnvironmentVariable("THUNDERFEN_PLL_PROFILE_BUNDLE", text2);
				return;
			}
			Directory.CreateDirectory(text);
			Harmony val = new Harmony("local.peak.thunderfen.profile-biome");
			try
			{
				PatchQueries(val, typeof(Directory), "GetFiles", typeof(string[]), "StaticFiles");
				PatchQueries(val, typeof(Directory), "EnumerateFiles", typeof(IEnumerable<string>), "StaticEnumerable");
				PatchQueries(val, typeof(DirectoryInfo), "GetFiles", typeof(FileInfo[]), "InfoFiles");
				PatchQueries(val, typeof(DirectoryInfo), "EnumerateFiles", typeof(IEnumerable<FileInfo>), "InfoEnumerable");
				discoveryFolder = text;
				bundle = fullPath;
				hidden = (File.Exists(text2) ? text2 : null);
				CheckVisible(plugins, bundle);
				Environment.SetEnvironmentVariable("THUNDERFEN_PLL_PROFILE_BUNDLE", bundle);
				if (hidden != null)
				{
					Console.WriteLine("[Thunderfen] Ignored a different prototype-first-ridge.pll in PLL_Biomes. Delete " + hidden + " unless another mod needs it.");
				}
				Console.WriteLine("[Thunderfen] Exposed the managed package bundle to PLL_Biomes without a copy.");
			}
			catch
			{
				discoveryFolder = (bundle = (hidden = null));
				val.UnpatchSelf();
				throw;
			}
		}

		private static void PatchQueries(Harmony harmony, Type owner, string name, Type result, string callback)
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Expected O, but got Unknown
			BindingFlags bindingAttr = (BindingFlags)(0x10 | ((owner == typeof(Directory)) ? 8 : 4));
			HarmonyMethod val = new HarmonyMethod(AccessTools.DeclaredMethod(typeof(ProfileBiome), callback, (Type[])null, (Type[])null));
			MethodInfo[] methods = owner.GetMethods(bindingAttr);
			foreach (MethodInfo methodInfo in methods)
			{
				if (methodInfo.Name == name && methodInfo.ReturnType == result)
				{
					harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				}
			}
		}

		private static bool Include(string path, string pattern)
		{
			if (discoveryFolder == null || string.IsNullOrEmpty(path) || !string.Equals(Path.GetFullPath(path).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar), discoveryFolder, StringComparison.OrdinalIgnoreCase) || !File.Exists(bundle))
			{
				return false;
			}
			if (string.IsNullOrEmpty(pattern) || pattern == "*" || pattern == "*.*")
			{
				return true;
			}
			return Regex.IsMatch("prototype-first-ridge.pll", "^" + Regex.Escape(pattern).Replace("\\*", ".*").Replace("\\?", ".") + "$", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
		}

		private static bool Same(string path, string expected)
		{
			if (expected == null || string.IsNullOrEmpty(path))
			{
				return false;
			}
			try
			{
				return string.Equals(Path.GetFullPath(path), expected, StringComparison.OrdinalIgnoreCase);
			}
			catch (ArgumentException)
			{
				return false;
			}
			catch (NotSupportedException)
			{
				return false;
			}
		}

		private static string Pattern(object[] args, int index)
		{
			return (args.Length > index) ? (args[index] as string) : null;
		}

		private static IEnumerable<T> WithBundle<T>(IEnumerable<T> files, Func<T, string> path, Func<string, T> create)
		{
			bool present = false;
			foreach (T file in files)
			{
				string name = path(file);
				if (!Same(name, hidden))
				{
					present |= Same(name, bundle);
					yield return file;
				}
			}
			if (!present)
			{
				yield return create(bundle);
			}
		}

		private static void StaticFiles(object[] __args, ref string[] __result)
		{
			if (Include(__args[0] as string, Pattern(__args, 1)))
			{
				__result = WithBundle(__result, (string file) => file, (string path) => path).ToArray();
			}
		}

		private static void StaticEnumerable(object[] __args, ref IEnumerable<string> __result)
		{
			if (Include(__args[0] as string, Pattern(__args, 1)))
			{
				__result = WithBundle(__result, (string file) => file, (string path) => path);
			}
		}

		private static void InfoFiles(DirectoryInfo __instance, object[] __args, ref FileInfo[] __result)
		{
			if (Include(__instance.FullName, Pattern(__args, 0)))
			{
				__result = WithBundle(__result, (FileInfo file) => file.FullName, (string path) => new FileInfo(path)).ToArray();
			}
		}

		private static void InfoEnumerable(DirectoryInfo __instance, object[] __args, ref IEnumerable<FileInfo> __result)
		{
			if (Include(__instance.FullName, Pattern(__args, 0)))
			{
				__result = WithBundle(__result, (FileInfo file) => file.FullName, (string path) => new FileInfo(path));
			}
		}

		internal static void Verify(string plugins)
		{
			string environmentVariable = Environment.GetEnvironmentVariable("THUNDERFEN_PLL_PROFILE_BUNDLE");
			if (string.IsNullOrEmpty(environmentVariable))
			{
				throw new InvalidOperationException(PreloaderStatus.Describe("Thunderfen's PLL biome was not prepared."));
			}
			CheckVisible(plugins, environmentVariable);
		}

		private static void CheckVisible(string plugins, string expected)
		{
			string[] files = Directory.GetFiles(RootFolder(plugins), "*.pll");
			if (!files.Contains<string>(expected, StringComparer.OrdinalIgnoreCase))
			{
				throw new InvalidOperationException("Thunderfen is missing from PLL's biome search in BepInEx/plugins/PLL_Biomes.");
			}
			if (files.Count((string file) => string.Equals(Path.GetFileName(file), "prototype-first-ridge.pll", StringComparison.OrdinalIgnoreCase)) != 1)
			{
				throw new InvalidOperationException("PLL would load two copies of Thunderfen's biome. Remove the extra prototype-first-ridge.pll.");
			}
		}

		internal static void RemoveLegacyCopy(string plugins, string package)
		{
			string text = Path.Combine(RootFolder(plugins), "prototype-first-ridge.pll");
			string path = text + ".thunderfen-owned";
			if (!File.Exists(path) || (package != null && string.Equals(text, Path.GetFullPath(Path.Combine(package, "PLL_Biomes", "prototype-first-ridge.pll")), StringComparison.OrdinalIgnoreCase)))
			{
				return;
			}
			string b = File.ReadAllText(path).Trim();
			if (File.Exists(text))
			{
				if (!string.Equals(Hash(text), b, StringComparison.OrdinalIgnoreCase))
				{
					return;
				}
				File.Delete(text);
			}
			File.Delete(path);
		}

		private static string RootFolder(string plugins)
		{
			return Path.GetFullPath(Path.Combine(plugins, "PLL_Biomes"));
		}

		private static void RequireBundle(string path)
		{
			if (!File.Exists(path))
			{
				throw new FileNotFoundException("Thunderfen's biome bundle is missing at " + path + ". Reinstall Thunderfen.");
			}
			if (Hash(path) != "2D0E0B6FD6D57EB649A4731AFA5AA39F5A1749DFF9E88A877ACDC30C12333A5E")
			{
				throw new InvalidDataException("Thunderfen's biome bundle at " + path + " is damaged or from another version. Reinstall Thunderfen.");
			}
		}

		private static string Hash(string path)
		{
			using SHA256 sHA = SHA256.Create();
			using FileStream inputStream = File.OpenRead(path);
			return BitConverter.ToString(sHA.ComputeHash(inputStream)).Replace("-", "");
		}
	}
	internal static class ReleaseRoute
	{
		private const string Layout = "Beach > Tropics > prototype/first-ridge > Volcano > Nadir";

		private const string ProfileRouteKey = "THUNDERFEN_PLL_ROUTE_CONFIG";

		private const string Schema = "29";

		private static string original;

		private static string overlay;

		internal static void Install(string configRoot)
		{
			//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)
			//IL_0084: Expected O, but got Unknown
			//IL_0190: Unknown result type (might be due to invalid IL or missing references)
			//IL_0198: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a6: Expected O, but got Unknown
			original = Path.GetFullPath(Path.Combine(configRoot, "AF", "PLL_Library", "config.cfg"));
			string directoryName = Path.GetDirectoryName(original);
			Directory.CreateDirectory(directoryName);
			overlay = Path.Combine(directoryName, ".thunderfen-route-" + Guid.NewGuid().ToString("N") + ".cfg");
			try
			{
				ConfigFile val = ProfileSettings();
				if (val == null)
				{
					val = new ConfigFile(overlay, false)
					{
						SaveOnConfigSet = false
					};
					val.Bind<string>("Version", "SchemaRevision", "29", (ConfigDescription)null);
				}
				val.Bind<string>("Map", "LayoutOrder", "Beach > Tropics > prototype/first-ridge > Volcano > Nadir", (ConfigDescription)null).Value = "Beach > Tropics > prototype/first-ridge > Volcano > Nadir";
				val.Bind<bool>("Map", "DoOrder", true, (ConfigDescription)null).Value = true;
				val.Bind<bool>("Map", "Generative Map", false, (ConfigDescription)null).Value = false;
				val.Bind<bool>("Map", "InfiniteMap", false, (ConfigDescription)null).Value = false;
				val.Save();
				ConstructorInfo constructor = typeof(ConfigFile).GetConstructor(new Type[3]
				{
					typeof(string),
					typeof(bool),
					typeof(BepInPlugin)
				});
				if (constructor == null)
				{
					throw new MissingMethodException(typeof(ConfigFile).FullName, ".ctor");
				}
				MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(ReleaseRoute), "RedirectConfig", (Type[])null, (Type[])null);
				new Harmony("local.peak.thunderfen.profile-route").Patch((MethodBase)constructor, new HarmonyMethod(methodInfo), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				Environment.SetEnvironmentVariable("THUNDERFEN_PLL_ROUTE_CONFIG", overlay);
				AppDomain.CurrentDomain.ProcessExit += delegate
				{
					RemoveOverlay();
				};
				Console.WriteLine("[Thunderfen] Prepared the PLL route before plugin startup.");
			}
			catch
			{
				RemoveOverlay();
				throw;
			}
		}

		private static ConfigFile ProfileSettings()
		{
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Expected O, but got Unknown
			if (!File.Exists(original))
			{
				return null;
			}
			string text;
			try
			{
				File.Copy(original, overlay);
				File.SetAttributes(overlay, FileAttributes.Normal);
				ConfigFile val = new ConfigFile(overlay, false)
				{
					SaveOnConfigSet = false
				};
				string value = val.Bind<string>("Version", "SchemaRevision", "29", (ConfigDescription)null).Value;
				if (value == "29")
				{
					return val;
				}
				text = "use PLL config schema " + value + " instead of 29";
			}
			catch (Exception ex)
			{
				text = "could not be read (" + ex.Message + ")";
			}
			RemoveOverlay();
			Console.WriteLine("[Thunderfen] The profile's saved PLL settings " + text + ". Thunderfen uses PLL's defaults with its route for this session and leaves the saved file unchanged.");
			return null;
		}

		private static void RedirectConfig(ref string __0)
		{
			if (!string.IsNullOrEmpty(__0) && string.Equals(Path.GetFullPath(__0), original, StringComparison.OrdinalIgnoreCase))
			{
				__0 = overlay;
			}
		}

		internal static void Verify(ConfigEntry<string> layout, ConfigEntry<bool> order, ConfigEntry<bool> generative, ConfigEntry<bool> infinite)
		{
			string environmentVariable = Environment.GetEnvironmentVariable("THUNDERFEN_PLL_ROUTE_CONFIG");
			if (string.IsNullOrEmpty(environmentVariable) || ((layout != null) ? ((ConfigEntryBase)layout).ConfigFile.ConfigFilePath : null) != environmentVariable || layout.Value != "Beach > Tropics > prototype/first-ridge > Volcano > Nadir" || order == null || !order.Value || generative == null || generative.Value || infinite == null || infinite.Value)
			{
				throw new InvalidOperationException(PreloaderStatus.Describe("PLL did not load Thunderfen's route."));
			}
		}

		private static void RemoveOverlay()
		{
			if (overlay == null)
			{
				return;
			}
			try
			{
				File.Delete(overlay);
			}
			catch (IOException)
			{
			}
			catch (UnauthorizedAccessException)
			{
			}
		}
	}
}

plugins/Peak3CalderaTrial.dll

Decompiled a week ago
using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using BepInEx;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyVersion("0.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
[BepInPlugin("local.peak3.caldera.trial", "PEAK 3 Caldera Trial", "0.1.0")]
[BepInDependency(/*Could not decode attribute arguments.*/)]
public sealed class Peak3CalderaTrial : BaseUnityPlugin
{
	private const string ExactError = "PEAK's Caldera tide is unsupported. Update PLL_Library.";

	private static ManualLogSource trialLog;

	private static int suppressed;

	private void Awake()
	{
		//IL_0074: Unknown result type (might be due to invalid IL or missing references)
		//IL_007e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0089: Expected O, but got Unknown
		trialLog = ((BaseUnityPlugin)this).Logger;
		Type type = AccessTools.TypeByName("PLL.Library.NativeSegmentPorts");
		if (type == null)
		{
			((BaseUnityPlugin)this).Logger.LogWarning((object)"Caldera trial inactive: target type not found.");
			return;
		}
		MethodInfo methodInfo = AccessTools.DeclaredMethod(type, "CalderaTideCeiling", (Type[])null, (Type[])null);
		if (methodInfo == null)
		{
			((BaseUnityPlugin)this).Logger.LogWarning((object)"Caldera trial inactive: target method not found.");
			return;
		}
		MethodInfo method = typeof(Peak3CalderaTrial).GetMethod("OnCalderaException", BindingFlags.Static | BindingFlags.NonPublic);
		new Harmony("local.peak3.caldera.trial").Patch((MethodBase)methodInfo, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(method), (HarmonyMethod)null);
		((BaseUnityPlugin)this).Logger.LogInfo((object)("Caldera trial active. Method returns " + methodInfo.ReturnType.FullName + "."));
	}

	private static Exception OnCalderaException(Exception __exception)
	{
		if (__exception == null || !(__exception is InvalidOperationException) || __exception.Message != "PEAK's Caldera tide is unsupported. Update PLL_Library.")
		{
			return __exception;
		}
		if (suppressed++ == 0)
		{
			trialLog.LogWarning((object)"Suppressed the known Caldera tide compatibility check for this local run. Caldera is absent from the selected route.");
		}
		return null;
	}
}

plugins/Peak3PllKeyRelay/Peak3PllKeyRelay.dll

Decompiled a week ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security.Cryptography;
using System.Text;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Steamworks;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyVersion("0.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace Peak3PllKeyRelay
{
	public enum RelayRead
	{
		UseNative,
		UseRelay,
		MismatchKeepNative,
		Missing
	}
	public static class KeyRelayPolicy
	{
		public const string Namespace = "af.pll.library/";

		public const string AliasPrefix = "relay_";

		public const int MaxKey = 255;

		public static bool Eligible(string key)
		{
			return key != null && key.StartsWith("af.pll.library/") && key.Length > "af.pll.library/".Length && Alias(key) != null;
		}

		public static HashSet<string> ParseKeys(string csv, List<string> rejected)
		{
			HashSet<string> hashSet = new HashSet<string>();
			string[] array = (csv ?? "").Split(',');
			foreach (string text in array)
			{
				string text2 = text.Trim();
				if (text2.Length != 0)
				{
					if (Eligible(text2))
					{
						hashSet.Add(text2);
					}
					else
					{
						rejected?.Add(text2);
					}
				}
			}
			return hashSet;
		}

		public static string Alias(string key)
		{
			if (key == null)
			{
				return null;
			}
			StringBuilder stringBuilder = new StringBuilder("relay_");
			byte[] bytes = Encoding.UTF8.GetBytes(key);
			foreach (byte b in bytes)
			{
				stringBuilder.Append(b.ToString("x2"));
			}
			return (stringBuilder.Length <= 255) ? stringBuilder.ToString() : null;
		}

		public static string FromAlias(string alias)
		{
			if (alias == null || !alias.StartsWith("relay_") || (alias.Length - "relay_".Length) % 2 != 0)
			{
				return null;
			}
			byte[] array = new byte[(alias.Length - "relay_".Length) / 2];
			for (int i = 0; i < array.Length; i++)
			{
				int num = Hex(alias["relay_".Length + 2 * i]);
				int num2 = Hex(alias["relay_".Length + 2 * i + 1]);
				if (num < 0 || num2 < 0)
				{
					return null;
				}
				array[i] = (byte)(num * 16 + num2);
			}
			return Encoding.UTF8.GetString(array);
		}

		private static int Hex(char c)
		{
			if (c >= '0' && c <= '9')
			{
				return c - 48;
			}
			if (c >= 'a' && c <= 'f')
			{
				return c - 97 + 10;
			}
			return -1;
		}

		public static bool MirrorLobbyWrite(bool keyRelayed, bool originalAccepted, bool localIsOwner, int reentrancy)
		{
			return keyRelayed && originalAccepted && localIsOwner && reentrancy == 0;
		}

		public static bool MirrorMemberWrite(bool keyRelayed, bool localIsMember, int reentrancy)
		{
			return keyRelayed && localIsMember && reentrancy == 0;
		}

		public static RelayRead Decide(string native, string relayed)
		{
			if (native == null)
			{
				return RelayRead.UseNative;
			}
			if (native.Length > 0)
			{
				return (relayed != null && relayed.Length > 0 && relayed != native) ? RelayRead.MismatchKeepNative : RelayRead.UseNative;
			}
			return (relayed != null && relayed.Length > 0) ? RelayRead.UseRelay : RelayRead.Missing;
		}
	}
	[BepInPlugin("local.peak3.pll.keyrelay", "PEAK 3 PLL Key Relay (candidate)", "0.0.3")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public sealed class PllKeyRelay : BaseUnityPlugin
	{
		public const string Version = "0.0.3";

		public const string Guid = "local.peak3.pll.keyrelay";

		private const string PllSha = "C8A19DEB990089E0BAB9FBE21CF29146937C098945EB7204EF4D883BB9B955E7";

		private static HashSet<string> keys = new HashSet<string>();

		private static int reentrancy;

		private static string logPath;

		private static int lines;

		private static readonly HashSet<string> once = new HashSet<string>();

		private void Awake()
		{
			//IL_031c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0323: Expected O, but got Unknown
			//IL_0339: Unknown result type (might be due to invalid IL or missing references)
			//IL_0346: Expected O, but got Unknown
			//IL_035c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0369: Expected O, but got Unknown
			//IL_037f: Unknown result type (might be due to invalid IL or missing references)
			//IL_038c: Expected O, but got Unknown
			//IL_03a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_03af: Expected O, but got Unknown
			//IL_03c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_03d2: Expected O, but got Unknown
			ConfigEntry<bool> val = ((BaseUnityPlugin)this).Config.Bind<bool>("Relay", "Enabled", false, "Off by default. Enable only after the v2 diagnostic confirmed slash-key replication loss.");
			ConfigEntry<string> val2 = ((BaseUnityPlugin)this).Config.Bind<string>("Relay", "Keys", "af.pll.library/admission", "Comma-separated PLL keys (must start with af.pll.library/). Add only keys the v2 probe observed PLL writing.");
			logPath = Path.Combine(Application.persistentDataPath, "Thunderfen/pll-key-relay.jsonl");
			Directory.CreateDirectory(Path.GetDirectoryName(logPath));
			List<string> list = new List<string>();
			keys = KeyRelayPolicy.ParseKeys(val2.Value, list);
			PluginInfo val3 = ((IEnumerable<PluginInfo>)Chainloader.PluginInfos.Values).FirstOrDefault((Func<PluginInfo, bool>)((PluginInfo p) => p.Metadata.GUID == "af.pll.library"));
			string text = ((!val.Value) ? "disabled in config" : ((val3 == null || val3.Metadata.Version.ToString() != "5.9.10" || Sha(val3.Location) != "C8A19DEB990089E0BAB9FBE21CF29146937C098945EB7204EF4D883BB9B955E7") ? "different PLL build" : ((keys.Count == 0) ? "no eligible keys" : null)));
			if (list.Count > 0)
			{
				Log("rejected-keys", string.Join(",", list.ToArray()), "", "");
			}
			if (text != null)
			{
				((BaseUnityPlugin)this).Logger.LogInfo((object)("PLL key relay inactive: " + text + "."));
				Log("inactive", text, "", "");
				return;
			}
			Type typeFromHandle = typeof(SteamMatchmaking);
			MethodInfo methodInfo;
			MethodInfo methodInfo2;
			MethodInfo methodInfo3;
			MethodInfo methodInfo4;
			MethodInfo methodInfo5;
			try
			{
				methodInfo = Required(typeFromHandle, "SetLobbyData", typeof(bool), typeof(CSteamID), typeof(string), typeof(string));
				methodInfo2 = Required(typeFromHandle, "DeleteLobbyData", typeof(bool), typeof(CSteamID), typeof(string));
				methodInfo3 = Required(typeFromHandle, "GetLobbyData", typeof(string), typeof(CSteamID), typeof(string));
				methodInfo4 = Required(typeFromHandle, "SetLobbyMemberData", typeof(void), typeof(CSteamID), typeof(string), typeof(string));
				methodInfo5 = Required(typeFromHandle, "GetLobbyMemberData", typeof(string), typeof(CSteamID), typeof(CSteamID), typeof(string));
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)("PLL relay inactive: " + ex));
				Log("inactive", "Steamworks API changed", "", "");
				return;
			}
			Harmony val4 = new Harmony("local.peak3.pll.keyrelay");
			try
			{
				val4.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(PllKeyRelay), "PostSetLobbyData", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				val4.Patch((MethodBase)methodInfo2, (HarmonyMethod)null, new HarmonyMethod(typeof(PllKeyRelay), "PostDeleteLobbyData", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				val4.Patch((MethodBase)methodInfo3, (HarmonyMethod)null, new HarmonyMethod(typeof(PllKeyRelay), "PostGetLobbyData", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				val4.Patch((MethodBase)methodInfo4, (HarmonyMethod)null, new HarmonyMethod(typeof(PllKeyRelay), "PostSetLobbyMemberData", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				val4.Patch((MethodBase)methodInfo5, (HarmonyMethod)null, new HarmonyMethod(typeof(PllKeyRelay), "PostGetLobbyMemberData", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			catch (Exception ex2)
			{
				val4.UnpatchSelf();
				((BaseUnityPlugin)this).Logger.LogError((object)("PLL relay inactive: " + ex2));
				Log("inactive", "Steamworks patch failed", "", "");
				return;
			}
			((BaseUnityPlugin)this).Logger.LogInfo((object)("PLL key relay active for: " + string.Join(", ", keys.ToArray())));
			Log("active", string.Join(",", keys.ToArray()), "", "");
		}

		private static MethodInfo Required(Type t, string name, Type result, params Type[] args)
		{
			BindingFlags bindingAttr = BindingFlags.Static | BindingFlags.Public | BindingFlags.ExactBinding;
			MethodInfo method = t.GetMethod(name, bindingAttr, null, args, null);
			if (method == null || method.ReturnType != result)
			{
				throw new MissingMethodException(t.FullName, name);
			}
			return method;
		}

		private static void PostSetLobbyData(CSteamID __0, string __1, string __2, bool __result)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			if (reentrancy > 0 || !keys.Contains(__1))
			{
				return;
			}
			bool localIsOwner = SteamMatchmaking.GetLobbyOwner(__0) == SteamUser.GetSteamID();
			if (!KeyRelayPolicy.MirrorLobbyWrite(keyRelayed: true, __result, localIsOwner, reentrancy))
			{
				Log("mirror-skipped", __1, __0.m_SteamID.ToString(), "accepted=" + __result + " owner=" + localIsOwner);
				return;
			}
			reentrancy++;
			try
			{
				bool flag = SteamMatchmaking.SetLobbyData(__0, KeyRelayPolicy.Alias(__1), __2);
				Log("mirror-lobby", __1, __0.m_SteamID.ToString(), "ok=" + flag);
			}
			finally
			{
				reentrancy--;
			}
		}

		private static void PostDeleteLobbyData(CSteamID __0, string __1, bool __result)
		{
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			if (reentrancy > 0 || !keys.Contains(__1) || !__result)
			{
				return;
			}
			reentrancy++;
			try
			{
				SteamMatchmaking.DeleteLobbyData(__0, KeyRelayPolicy.Alias(__1));
				Log("mirror-delete", __1, __0.m_SteamID.ToString(), "");
			}
			finally
			{
				reentrancy--;
			}
		}

		private static void PostGetLobbyData(CSteamID __0, string __1, ref string __result)
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			if (reentrancy <= 0 && keys.Contains(__1))
			{
				reentrancy++;
				string lobbyData;
				try
				{
					lobbyData = SteamMatchmaking.GetLobbyData(__0, KeyRelayPolicy.Alias(__1));
				}
				finally
				{
					reentrancy--;
				}
				Apply(KeyRelayPolicy.Decide(__result, lobbyData), ref __result, lobbyData, "lobby", __1, __0.m_SteamID.ToString());
			}
		}

		private static void PostSetLobbyMemberData(CSteamID __0, string __1, string __2)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: 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_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			if (reentrancy > 0 || !keys.Contains(__1))
			{
				return;
			}
			CSteamID steamID = SteamUser.GetSteamID();
			bool flag = false;
			int numLobbyMembers = SteamMatchmaking.GetNumLobbyMembers(__0);
			for (int i = 0; i < numLobbyMembers; i++)
			{
				if (flag)
				{
					break;
				}
				flag = SteamMatchmaking.GetLobbyMemberByIndex(__0, i) == steamID;
			}
			if (!KeyRelayPolicy.MirrorMemberWrite(keyRelayed: true, flag, reentrancy))
			{
				return;
			}
			reentrancy++;
			try
			{
				SteamMatchmaking.SetLobbyMemberData(__0, KeyRelayPolicy.Alias(__1), __2);
				Log("mirror-member", __1, __0.m_SteamID.ToString(), "");
			}
			finally
			{
				reentrancy--;
			}
		}

		private static void PostGetLobbyMemberData(CSteamID __0, CSteamID __1, string __2, ref string __result)
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			if (reentrancy <= 0 && keys.Contains(__2))
			{
				reentrancy++;
				string lobbyMemberData;
				try
				{
					lobbyMemberData = SteamMatchmaking.GetLobbyMemberData(__0, __1, KeyRelayPolicy.Alias(__2));
				}
				finally
				{
					reentrancy--;
				}
				Apply(KeyRelayPolicy.Decide(__result, lobbyMemberData), ref __result, lobbyMemberData, "member:" + __1.m_SteamID, __2, __0.m_SteamID.ToString());
			}
		}

		private static void Apply(RelayRead d, ref string result, string relayed, string scope, string key, string lobby)
		{
			switch (d)
			{
			case RelayRead.UseRelay:
				result = relayed;
				Log("read-relayed", key, lobby, scope);
				break;
			case RelayRead.MismatchKeepNative:
				Log("read-mismatch-kept-native", key, lobby, scope);
				break;
			}
		}

		private static string Sha(string p)
		{
			try
			{
				using SHA256 sHA = SHA256.Create();
				return BitConverter.ToString(sHA.ComputeHash(File.ReadAllBytes(p))).Replace("-", "");
			}
			catch
			{
				return null;
			}
		}

		private static void Log(string what, string key, string lobby, string detail)
		{
			if (!once.Add(what + "|" + key + "|" + lobby + "|" + detail) || lines++ > 2000)
			{
				return;
			}
			try
			{
				File.AppendAllText(logPath, "{\"version\":\"0.0.3\",\"utc\":\"" + DateTime.UtcNow.ToString("O") + "\",\"event\":\"" + what + "\",\"key\":\"" + key + "\",\"lobby\":\"" + lobby + "\",\"detail\":\"" + detail + "\"}" + Environment.NewLine);
			}
			catch
			{
			}
		}
	}
}

plugins/ThunderfenCaveBugs/PoisonForestCaveBugs.dll

Decompiled a week ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security.Cryptography;
using BepInEx;
using Microsoft.CodeAnalysis;
using Photon.Pun;
using PoisonForest;
using PoisonForestGeneration;
using PoisonForestLightning;
using PoisonForestSolo;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.SceneManagement;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyVersion("0.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace PoisonForestCaveBugs
{
	public sealed class SwarmClock
	{
		public readonly double Period;

		public readonly double Phase;

		public readonly double Duration;

		public double TransferRemaining;

		public int Transfers;

		public SwarmClock(double period, double phase, double duration, double transferInterval)
		{
			if (!Finite(period) || !Finite(phase) || !Finite(duration) || period <= duration || phase < 0.0 || phase >= period || duration <= 0.0 || transferInterval <= 0.0)
			{
				throw new ArgumentException("Invalid swarm timing");
			}
			Period = period;
			Phase = phase;
			Duration = duration;
			TransferRemaining = transferInterval;
		}

		public static bool Finite(double n)
		{
			return !double.IsNaN(n) && !double.IsInfinity(n);
		}

		private static double Ease(double t)
		{
			t = Math.Max(0.0, Math.Min(1.0, t));
			return t * t * (3.0 - 2.0 * t);
		}

		public double Pulse(double elapsed)
		{
			double num = (Math.Max(0.0, elapsed) + Phase) % Period;
			if (num >= Duration)
			{
				return 0.0;
			}
			return Math.Min(Ease(num / Math.Min(1.0, Duration * 0.25)), Ease((Duration - num) / Math.Min(1.5, Duration * 0.35)));
		}

		public bool TickDose(double dt, double interval)
		{
			if (!Finite(dt) || dt < 0.0 || !Finite(interval) || interval <= 0.0)
			{
				throw new ArgumentException("Invalid swarm step");
			}
			TransferRemaining -= dt;
			if (TransferRemaining > 1E-06)
			{
				return false;
			}
			TransferRemaining = interval + TransferRemaining % interval;
			if (TransferRemaining <= 1E-06)
			{
				TransferRemaining = interval;
			}
			Transfers++;
			return true;
		}
	}
	public sealed class Chamber
	{
		public int id;

		public float x;

		public float y;

		public float height;

		public float width;

		public float depth;

		public float mouth;

		public float throat;

		public float[] front;

		public Vector3[] portals;

		public Bounds Bounds
		{
			get
			{
				//IL_0043: 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_00aa: Unknown result type (might be due to invalid IL or missing references)
				//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
				//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
				//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
				//IL_00e2: 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_00f4: 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)
				//IL_0124: Unknown result type (might be due to invalid IL or missing references)
				//IL_0125: Unknown result type (might be due to invalid IL or missing references)
				//IL_0129: Unknown result type (might be due to invalid IL or missing references)
				float num = float.PositiveInfinity;
				float num2 = float.NegativeInfinity;
				float[] array = front;
				foreach (float num3 in array)
				{
					num = Mathf.Min(num, num3);
					num2 = Mathf.Max(num2, num3);
				}
				Bounds result = default(Bounds);
				((Bounds)(ref result)).SetMinMax(new Vector3(x - width - 10f, y - 10f, num - 10f), new Vector3(x + width + 10f, y + height + 10f, num2 + depth + 10f));
				Vector3[] array2 = portals;
				foreach (Vector3 val in array2)
				{
					((Bounds)(ref result)).Encapsulate(val + new Vector3(25f, 14f, 25f));
					((Bounds)(ref result)).Encapsulate(val - new Vector3(25f, 14f, 25f));
				}
				return result;
			}
		}

		public float Front(float at)
		{
			float num = Mathf.Clamp01((at - y) / height) * 16f;
			int num2 = Math.Min(15, (int)num);
			return Mathf.Lerp(front[num2], front[num2 + 1], num - (float)num2);
		}

		private static float Smooth(float v)
		{
			v = Mathf.Clamp01(v);
			return v * v * (3f - 2f * v);
		}

		public float Weight(Vector3 p)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: 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_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ea: 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_00fb: 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_00ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0101: Unknown result type (might be due to invalid IL or missing references)
			//IL_0106: Unknown result type (might be due to invalid IL or missing references)
			//IL_0108: Unknown result type (might be due to invalid IL or missing references)
			//IL_010f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0116: Unknown result type (might be due to invalid IL or missing references)
			//IL_011b: 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)
			//IL_012a: Unknown result type (might be due to invalid IL or missing references)
			//IL_012f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0131: Unknown result type (might be due to invalid IL or missing references)
			//IL_0132: Unknown result type (might be due to invalid IL or missing references)
			//IL_0134: Unknown result type (might be due to invalid IL or missing references)
			//IL_0139: Unknown result type (might be due to invalid IL or missing references)
			//IL_014e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0154: Unknown result type (might be due to invalid IL or missing references)
			//IL_015c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0165: Unknown result type (might be due to invalid IL or missing references)
			//IL_016b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0173: Unknown result type (might be due to invalid IL or missing references)
			//IL_0183: Unknown result type (might be due to invalid IL or missing references)
			//IL_0189: Unknown result type (might be due to invalid IL or missing references)
			//IL_0190: Unknown result type (might be due to invalid IL or missing references)
			float num = Mathf.Abs(p.x - x) / (width + 4f);
			float num2 = Mathf.Abs(p.z - Front(p.y) - depth / 2f) / (depth / 2f + 4f);
			float num3 = Mathf.Pow(Mathf.Pow(num, 3.5f) + Mathf.Pow(num2, 3.5f), 0.2857143f);
			float num4 = Smooth((1.1f - num3) / 0.16f) * Smooth((p.y - y + 5f) / 7f) * Smooth((y + height + 5f - p.y) / 7f);
			for (int i = 0; i < 4; i += 2)
			{
				Vector3 val = portals[i];
				Vector3 val2 = portals[i + 1];
				Vector3 val3 = val2 - val;
				Vector2 val4 = new Vector2(val3.x, val3.z);
				float magnitude = ((Vector2)(ref val4)).magnitude;
				Vector3 val5 = val3 / magnitude;
				float num5 = Vector3.Dot(p - val, val5);
				float num6 = Mathf.Clamp01(num5 / magnitude);
				float num7 = Mathf.Abs((p.x - val.x) * (0f - val5.z) + (p.z - val.z) * val5.x);
				float num8 = p.y - Mathf.Lerp(val.y, val2.y, num6);
				float num9 = Mathf.Lerp(mouth, throat, num6) + 4f;
				float num10 = Smooth((num9 + 3f - num7) / 6f) * Smooth((11f - num8) / 5f) * Smooth((num8 + 8f) / 5f);
				float num11 = ((i == 0) ? Smooth((num5 - 8f) / 12f) : Smooth((magnitude - num5 - 8f) / 12f));
				num4 = Mathf.Max(num4, num10 * num11 * Smooth((num5 + 5f) / 5f) * Smooth((magnitude + 5f - num5) / 5f));
			}
			return num4;
		}
	}
	public sealed class SwarmSite
	{
		public int id;

		public int room;

		public Vector3 position;

		public Vector3 normal;

		public float interval;

		public float phase;

		public float duration;
	}
	public sealed class SwarmCatalog
	{
		public int seed;

		public Chamber[] rooms;

		public SwarmSite[] sites;

		private static int Count(BinaryReader r, int min, int max)
		{
			int num = r.ReadInt32();
			if (num < min || num > max)
			{
				throw new InvalidDataException("Invalid swarm catalog count");
			}
			return num;
		}

		private static float Number(BinaryReader r)
		{
			float num = r.ReadSingle();
			if (!SwarmClock.Finite(num) || Math.Abs(num) > 20000f)
			{
				throw new InvalidDataException("Invalid swarm catalog number");
			}
			return num;
		}

		private static Vector3 Point(BinaryReader r)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			return new Vector3(Number(r), Number(r), Number(r));
		}

		public static SwarmCatalog Read(byte[] bytes)
		{
			//IL_02e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_02fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_0203: Unknown result type (might be due to invalid IL or missing references)
			//IL_0208: Unknown result type (might be due to invalid IL or missing references)
			//IL_022e: Unknown result type (might be due to invalid IL or missing references)
			//IL_023c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0241: Unknown result type (might be due to invalid IL or missing references)
			//IL_0246: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_03cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_03d3: Unknown result type (might be due to invalid IL or missing references)
			if (bytes == null || bytes.Length > 10000)
			{
				throw new InvalidDataException("Invalid swarm catalog size");
			}
			using MemoryStream memoryStream = new MemoryStream(bytes);
			using BinaryReader binaryReader = new BinaryReader(memoryStream);
			if (binaryReader.ReadUInt32() != 1195525712 || binaryReader.ReadInt32() != 2)
			{
				throw new InvalidDataException("Unknown swarm catalog");
			}
			SwarmCatalog swarmCatalog = new SwarmCatalog();
			swarmCatalog.seed = binaryReader.ReadInt32();
			swarmCatalog.rooms = new Chamber[Count(binaryReader, 2, 2)];
			SwarmCatalog swarmCatalog2 = swarmCatalog;
			for (int i = 0; i < swarmCatalog2.rooms.Length; i++)
			{
				Chamber chamber = new Chamber();
				chamber.id = Count(binaryReader, i, i);
				chamber.x = Number(binaryReader);
				chamber.y = Number(binaryReader);
				chamber.height = Number(binaryReader);
				chamber.width = Number(binaryReader);
				chamber.depth = Number(binaryReader);
				chamber.mouth = Number(binaryReader);
				chamber.throat = Number(binaryReader);
				chamber.front = new float[Count(binaryReader, 17, 17)];
				chamber.portals = (Vector3[])(object)new Vector3[4];
				Chamber chamber2 = chamber;
				if (chamber2.height < 80f || chamber2.height > 110f || chamber2.width < 25f || chamber2.width > 45f || chamber2.depth < 45f || chamber2.depth > 80f || chamber2.mouth < 10f || chamber2.mouth > 25f || chamber2.throat < 5f || chamber2.throat > 20f)
				{
					throw new InvalidDataException("Invalid swarm chamber");
				}
				for (int j = 0; j < 17; j++)
				{
					chamber2.front[j] = Number(binaryReader);
				}
				for (int k = 0; k < 4; k++)
				{
					chamber2.portals[k] = Point(binaryReader);
				}
				for (int l = 0; l < 4; l += 2)
				{
					Vector3 val = chamber2.portals[l + 1] - chamber2.portals[l];
					if (((Vector3)(ref val)).sqrMagnitude < 4f)
					{
						throw new InvalidDataException("Degenerate swarm portal");
					}
				}
				swarmCatalog2.rooms[i] = chamber2;
			}
			swarmCatalog2.sites = new SwarmSite[Count(binaryReader, 8, 24)];
			int[] array = new int[2];
			int num = 0;
			while (num < swarmCatalog2.sites.Length)
			{
				SwarmSite swarmSite = new SwarmSite
				{
					id = Count(binaryReader, num, num),
					room = Count(binaryReader, 0, 1),
					position = Point(binaryReader),
					normal = Point(binaryReader),
					interval = Number(binaryReader),
					phase = Number(binaryReader),
					duration = Number(binaryReader)
				};
				if (!(((Vector3)(ref swarmSite.normal)).sqrMagnitude < 0.98f) && !(((Vector3)(ref swarmSite.normal)).sqrMagnitude > 1.02f) && !(swarmSite.interval < 8f) && !(swarmSite.interval > 40f) && !(swarmSite.phase < 0f) && !(swarmSite.phase >= swarmSite.interval) && !(swarmSite.duration < 1f) && !(swarmSite.duration > 8f) && !(swarmSite.interval <= swarmSite.duration))
				{
					Bounds bounds = swarmCatalog2.rooms[swarmSite.room].Bounds;
					if (((Bounds)(ref bounds)).Contains(swarmSite.position))
					{
						swarmCatalog2.sites[num] = swarmSite;
						array[swarmSite.room]++;
						num++;
						continue;
					}
				}
				throw new InvalidDataException("Invalid swarm site");
			}
			if (array[0] < 4 || array[1] < 4 || memoryStream.Position != memoryStream.Length)
			{
				throw new InvalidDataException("Incomplete swarm catalog");
			}
			return swarmCatalog2;
		}

		public float Weight(Vector3 p)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			float num = 0f;
			Chamber[] array = rooms;
			foreach (Chamber chamber in array)
			{
				num = Mathf.Max(num, chamber.Weight(p));
			}
			return num;
		}
	}
	public sealed class SwarmVisuals : IDisposable
	{
		public sealed class Swarm
		{
			public SwarmSite site;

			public GameObject node;

			public ParticleSystem particles;

			public Light light;

			public ElectricRibbon discharge;

			public readonly Particle[] points = (Particle[])(object)new Particle[144];

			public float pulse;

			public float arcUntil;

			public Vector3 arcTarget;

			public Func<Vector3> arcEndpoint;

			public Vector3[] strikePoints;

			public ParticleSystemRenderer renderer;

			public ElectricRibbon[] sparks;
		}

		private readonly Swarm[] swarms;

		private readonly Material material;

		private readonly SwarmSettings settings;

		private float nextParticles;

		private Swarm shadowOwner;

		public int ActiveBurstLights { get; private set; }

		public Swarm[] Swarms => swarms;

		public int ActiveLights { get; private set; }

		public SwarmVisuals(Transform frame, SwarmCatalog catalog, Material template, SwarmSettings values)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Expected O, but got Unknown
			//IL_003c: 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_008e: Expected O, but got Unknown
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: 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_0116: Unknown result type (might be due to invalid IL or missing references)
			//IL_011b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0128: Unknown result type (might be due to invalid IL or missing references)
			//IL_012d: Unknown result type (might be due to invalid IL or missing references)
			//IL_013a: Unknown result type (might be due to invalid IL or missing references)
			//IL_013f: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fe: Expected O, but got Unknown
			//IL_0246: Unknown result type (might be due to invalid IL or missing references)
			//IL_024b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0252: Unknown result type (might be due to invalid IL or missing references)
			//IL_0257: Unknown result type (might be due to invalid IL or missing references)
			//IL_0287: Unknown result type (might be due to invalid IL or missing references)
			//IL_028e: Expected O, but got Unknown
			//IL_02d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_02db: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e7: Unknown result type (might be due to invalid IL or missing references)
			settings = values;
			material = new Material(template)
			{
				name = "PF_CaveBugParticles_Owned",
				hideFlags = (HideFlags)61
			};
			material.SetColor("_BaseColor", Color.white);
			swarms = new Swarm[catalog.sites.Length];
			SwarmSite[] sites = catalog.sites;
			foreach (SwarmSite swarmSite in sites)
			{
				GameObject val = new GameObject("PF_ElectricalSwarm_" + swarmSite.id.ToString("D2"));
				val.transform.SetParent(frame, false);
				val.transform.localPosition = swarmSite.position;
				ParticleSystem val2 = val.AddComponent<ParticleSystem>();
				MainModule main = val2.main;
				((MainModule)(ref main)).playOnAwake = false;
				((MainModule)(ref main)).loop = true;
				((MainModule)(ref main)).startSpeed = MinMaxCurve.op_Implicit(0f);
				((MainModule)(ref main)).startLifetime = MinMaxCurve.op_Implicit(2f);
				((MainModule)(ref main)).maxParticles = 144;
				((MainModule)(ref main)).cullingMode = (ParticleSystemCullingMode)3;
				((MainModule)(ref main)).simulationSpace = (ParticleSystemSimulationSpace)0;
				EmissionModule emission = val2.emission;
				((EmissionModule)(ref emission)).enabled = false;
				ShapeModule shape = val2.shape;
				((ShapeModule)(ref shape)).enabled = false;
				CollisionModule collision = val2.collision;
				((CollisionModule)(ref collision)).enabled = false;
				ParticleSystemRenderer component = ((Component)val2).GetComponent<ParticleSystemRenderer>();
				((Renderer)component).sharedMaterial = material;
				((Renderer)component).shadowCastingMode = (ShadowCastingMode)0;
				((Renderer)component).receiveShadows = false;
				component.renderMode = (ParticleSystemRenderMode)0;
				val2.Play();
				Light val3 = val.AddComponent<Light>();
				val3.type = (LightType)2;
				val3.range = settings.faintLightRadius;
				val3.intensity = settings.faintLightIntensity;
				val3.color = new Color(0.48f, 0.56f, 1f);
				val3.shadows = (LightShadows)1;
				val3.renderMode = (LightRenderMode)1;
				((Behaviour)val3).enabled = false;
				GameObject val4 = new GameObject("DischargeArc");
				val4.transform.SetParent(val.transform, false);
				ElectricRibbon val5 = val4.AddComponent<ElectricRibbon>();
				val5.sharedMaterial = material;
				val5.widthMultiplier = 0.055f;
				val5.startColor = new Color(0.55f, 0.68f, 1f);
				val5.endColor = Color.white;
				((Behaviour)val5).enabled = false;
				ElectricRibbon[] array = (ElectricRibbon[])(object)new ElectricRibbon[4];
				for (int j = 0; j < array.Length; j++)
				{
					GameObject val6 = new GameObject("CloudSpark_" + j);
					val6.transform.SetParent(val.transform, false);
					ElectricRibbon val7 = val6.AddComponent<ElectricRibbon>();
					val7.sharedMaterial = material;
					val7.widthMultiplier = 0.035f;
					val7.startColor = new Color(0.48f, 0.6f, 1f);
					val7.endColor = Color.white;
					((Behaviour)val7).enabled = false;
					array[j] = val7;
				}
				swarms[swarmSite.id] = new Swarm
				{
					site = swarmSite,
					node = val,
					particles = val2,
					renderer = component,
					light = val3,
					discharge = val5,
					sparks = array
				};
			}
		}

		public void Strike(int id, Func<Vector3> bodyCenter)
		{
			if (bodyCenter == null)
			{
				throw new ArgumentNullException("bodyCenter");
			}
			Swarm swarm = swarms[id];
			swarm.arcUntil = Time.time + 0.48f;
			swarm.arcEndpoint = bodyCenter;
			RenderStrike(swarm);
		}

		private static Vector3[] Arc(Vector3 a, Vector3 b, int count, float amount, float phase)
		{
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			Vector3[] array = (Vector3[])(object)new Vector3[count];
			for (int i = 0; i < count; i++)
			{
				float num = (float)i / (float)(count - 1);
				float num2 = Mathf.Sin(num * MathF.PI) * amount;
				array[i] = Vector3.Lerp(a, b, num) + new Vector3(Mathf.Sin((float)i * 15.3f + phase), Mathf.Sin((float)i * 23.1f + phase * 0.93f), Mathf.Cos((float)i * 19.7f + phase * 0.97f)) * num2;
			}
			array[0] = a;
			array[count - 1] = b;
			return array;
		}

		private static void RenderStrike(Swarm s)
		{
			//IL_000c: 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_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			Vector3 position = s.node.transform.position;
			s.strikePoints = Arc(position, s.arcTarget = ((s.arcEndpoint != null) ? s.arcEndpoint() : s.arcTarget), 13, 0.32f, Time.time * 40f);
			s.discharge.SetPositions(s.strikePoints);
			((Behaviour)s.discharge).enabled = true;
		}

		private static void CloudSparks(Swarm s, double elapsed, bool visible)
		{
			//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0100: 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_013a: Unknown result type (might be due to invalid IL or missing references)
			//IL_013f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0143: Unknown result type (might be due to invalid IL or missing references)
			//IL_014d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0152: Unknown result type (might be due to invalid IL or missing references)
			//IL_0154: Unknown result type (might be due to invalid IL or missing references)
			//IL_0156: Unknown result type (might be due to invalid IL or missing references)
			//IL_017f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0184: Unknown result type (might be due to invalid IL or missing references)
			//IL_0189: Unknown result type (might be due to invalid IL or missing references)
			float num = (float)elapsed;
			bool flag = s.pulse > 0.1f;
			float num2 = (flag ? 0.18f : 0.45f);
			for (int i = 0; i < s.sparks.Length; i++)
			{
				ElectricRibbon val = s.sparks[i];
				float num3 = num + (float)s.site.id * 0.131f + (float)i * 0.083f;
				if (!visible || (!flag && i >= 2) || !(Mathf.Repeat(num3 / num2, 1f) < (flag ? 0.75f : 0.3f)))
				{
					((Behaviour)val).enabled = false;
					continue;
				}
				float num4 = Mathf.Floor(num3 / num2);
				float num5 = num4 * 2.17f + (float)s.site.id * 11.3f + (float)i * 5.7f;
				Vector3 val2 = new Vector3(Mathf.Sin(num5), Mathf.Cos(num5 * 1.31f), Mathf.Sin(num5 * 0.73f));
				Vector3 a = ((Vector3)(ref val2)).normalized * 1.7f;
				val2 = new Vector3(Mathf.Sin(num5 + 2.1f), Mathf.Cos(num5 * 1.17f + 1.8f), Mathf.Sin(num5 * 0.91f - 2f));
				Vector3 b = ((Vector3)(ref val2)).normalized * 1.7f;
				Vector3[] array = Arc(a, b, 7, 0.16f, num5);
				for (int j = 0; j < array.Length; j++)
				{
					array[j] = s.node.transform.TransformPoint(array[j]);
				}
				val.widthMultiplier = (flag ? 0.05f : 0.035f);
				val.SetPositions(array);
				((Behaviour)val).enabled = true;
			}
		}

		public void Tick(Transform frame, SwarmClock[] clocks, double elapsed, Vector3 observer)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: 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_0162: Unknown result type (might be due to invalid IL or missing references)
			//IL_0169: Unknown result type (might be due to invalid IL or missing references)
			//IL_017f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0184: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_0250: Unknown result type (might be due to invalid IL or missing references)
			//IL_0255: Unknown result type (might be due to invalid IL or missing references)
			//IL_0589: Unknown result type (might be due to invalid IL or missing references)
			//IL_059d: Unknown result type (might be due to invalid IL or missing references)
			//IL_05a9: Unknown result type (might be due to invalid IL or missing references)
			bool flag = Time.unscaledTime >= nextParticles;
			if (flag)
			{
				nextParticles = Time.unscaledTime + 0.05f;
			}
			ActiveLights = 0;
			ActiveBurstLights = 0;
			Swarm[] array = swarms;
			Vector3 val2 = default(Vector3);
			foreach (Swarm swarm in array)
			{
				swarm.pulse = (float)clocks[swarm.site.id].Pulse(elapsed);
				Vector3 val = swarm.node.transform.position - observer;
				float sqrMagnitude = ((Vector3)(ref val)).sqrMagnitude;
				bool flag2 = sqrMagnitude < settings.visualDistance * settings.visualDistance;
				((Renderer)swarm.renderer).enabled = flag2;
				if (flag2 && flag)
				{
					for (int j = 0; j < swarm.points.Length; j++)
					{
						float time = Time.time;
						float num = (float)swarm.site.id * 19.17f + (float)j * 2.399963f;
						float num2 = 0.65f + (float)(j % 7) * 0.13f;
						((Vector3)(ref val2))..ctor(Mathf.Sin(time * num2 + num), Mathf.Sin(time * num2 * 0.73f + num * 1.7f), Mathf.Cos(time * num2 * 0.83f + num * 1.3f));
						val2 = Vector3.ClampMagnitude(val2, 1f) * (1.4f + (float)(j % 5) * 0.2f);
						float num3 = 0.85f + 0.15f * Mathf.Sin(time * (float)(2 + j % 4) + num);
						((Particle)(ref swarm.points[j])).position = val2;
						((Particle)(ref swarm.points[j])).startSize = Mathf.Lerp(0.09f, 0.23f, swarm.pulse) * (0.7f + (float)(j % 4) * 0.15f);
						((Particle)(ref swarm.points[j])).startColor = Color32.op_Implicit(new Color(Mathf.Lerp(0.62f, 0.85f, swarm.pulse), Mathf.Lerp(0.7f, 0.91f, swarm.pulse), 1f, Mathf.Lerp(0.65f, 0.95f, swarm.pulse) * num3));
						((Particle)(ref swarm.points[j])).startLifetime = 2f;
						((Particle)(ref swarm.points[j])).remainingLifetime = 2f;
					}
					swarm.particles.SetParticles(swarm.points, swarm.points.Length);
				}
				((Behaviour)swarm.light).enabled = sqrMagnitude < settings.lightCullDistance * settings.lightCullDistance;
				swarm.light.range = settings.faintLightRadius;
				swarm.light.intensity = settings.faintLightIntensity;
				swarm.light.color = new Color(0.58f, 0.66f, 1f);
				swarm.light.shadows = (LightShadows)0;
				if (((Behaviour)swarm.light).enabled)
				{
					ActiveLights++;
				}
				if (flag2 && flag)
				{
					CloudSparks(swarm, elapsed, visible: true);
				}
				else if (!flag2)
				{
					ElectricRibbon[] sparks = swarm.sparks;
					foreach (ElectricRibbon val3 in sparks)
					{
						((Behaviour)val3).enabled = false;
					}
				}
				if (Time.time < swarm.arcUntil)
				{
					RenderStrike(swarm);
				}
				else if (((Behaviour)swarm.discharge).enabled)
				{
					((Behaviour)swarm.discharge).enabled = false;
					swarm.arcEndpoint = null;
				}
			}
			if (shadowOwner == null || !((Behaviour)shadowOwner.light).enabled || shadowOwner.pulse <= 0.001f)
			{
				shadowOwner = swarms.Where((Swarm s) => ((Behaviour)s.light).enabled && s.pulse > 0.001f).OrderBy(delegate(Swarm s)
				{
					//IL_000b: 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_0016: Unknown result type (might be due to invalid IL or missing references)
					//IL_001b: Unknown result type (might be due to invalid IL or missing references)
					Vector3 val4 = s.node.transform.position - observer;
					return ((Vector3)(ref val4)).sqrMagnitude;
				}).FirstOrDefault();
			}
			foreach (Swarm item in swarms.Where((Swarm s) => ((Behaviour)s.light).enabled && s.pulse > 0.001f))
			{
				float num4 = 1f + 0.015f * Mathf.Sin(Time.time * 3.2f + item.site.phase) * item.pulse;
				item.light.range = Mathf.Lerp(settings.faintLightRadius, settings.burstLightRadius, item.pulse);
				item.light.intensity = Mathf.Lerp(settings.faintLightIntensity, settings.burstLightIntensity, item.pulse) * num4;
				item.light.color = Color.Lerp(new Color(0.58f, 0.66f, 1f), new Color(0.83f, 0.88f, 1f), item.pulse);
				item.light.shadows = (LightShadows)((item == shadowOwner) ? 2 : 0);
				item.light.shadowStrength = item.pulse;
				ActiveBurstLights++;
			}
		}

		private static void Release(Object value)
		{
			if (Application.isPlaying)
			{
				Object.Destroy(value);
			}
			else
			{
				Object.DestroyImmediate(value);
			}
		}

		public void Dispose()
		{
			Swarm[] array = swarms;
			foreach (Swarm swarm in array)
			{
				if (swarm == null || !Object.op_Implicit((Object)(object)swarm.node))
				{
					continue;
				}
				if (!Application.isPlaying)
				{
					MeshFilter[] componentsInChildren = swarm.node.GetComponentsInChildren<MeshFilter>();
					foreach (MeshFilter val in componentsInChildren)
					{
						if (Object.op_Implicit((Object)(object)val.sharedMesh))
						{
							Release((Object)(object)val.sharedMesh);
						}
					}
				}
				Release((Object)(object)swarm.node);
			}
			if (Object.op_Implicit((Object)(object)material))
			{
				Release((Object)(object)material);
			}
		}
	}
	public sealed class CaveLighting : IDisposable
	{
		private struct LanternState
		{
			public Light light;

			public Color color;

			public bool temperature;

			public float intensity;

			public float range;

			public LightShadows shadows;

			public LightRenderMode mode;
		}

		private struct GlowState
		{
			public Renderer renderer;

			public bool enabled;
		}

		private struct Region
		{
			public int x;

			public int y;

			public int z;

			public int nx;

			public int ny;

			public int nz;
		}

		public Vector3 ViewerPosition;

		public Light[] FillLights;

		public Light[] LanternLights;

		private readonly List<LanternState> tintedLanterns = new List<LanternState>();

		public Renderer[] LanternGlows;

		private readonly List<GlowState> hiddenGlows = new List<GlowState>();

		private readonly ComputeShader compute;

		private readonly SwarmCatalog catalog;

		private readonly Transform frame;

		private readonly float darkness;

		private RenderTexture map;

		private Texture original;

		private Texture boundOriginal;

		private float boundMinimum;

		private bool bound;

		private bool subscribed;

		private readonly List<Region> regions = new List<Region>();

		private readonly Vector4[] swarmSources = (Vector4[])(object)new Vector4[12];

		private readonly Vector4[] swarmFill = (Vector4[])(object)new Vector4[12];

		private readonly Vector4[] itemSources = (Vector4[])(object)new Vector4[16];

		private readonly Vector4[] itemFill = (Vector4[])(object)new Vector4[16];

		private double nextIndirect;

		private int kernel;

		private Matrix4x4 matrix;

		private Vector4 grid;

		private float spacing;

		public float ViewerWeight;

		public Light PersonalLight;

		private Light adjustedLight;

		private bool personalWasEnabled;

		private float personalIntensity;

		private float personalRange;

		private Color personalColor;

		private LightShadows personalShadows;

		private LightRenderMode personalMode;

		private readonly float restingIntensity;

		private readonly float restingRadius;

		private readonly float lanternIntensity;

		private readonly float lanternRadius;

		public int LastItemFills { get; private set; }

		public int LastTintedLanterns { get; private set; }

		public int LastHiddenGlows { get; private set; }

		public int VoxelsChanged { get; private set; }

		public bool Ready => Object.op_Implicit((Object)(object)map);

		public string SourceFormat { get; private set; }

		public static Renderer[] FindLanternGlows(ParticleSystem glow, ParticleSystem fire, ParticleSystemRenderer[] descendants)
		{
			ParticleSystemRenderer direct = (Object.op_Implicit((Object)(object)glow) ? ((Component)glow).GetComponent<ParticleSystemRenderer>() : null);
			return (from r in ((IEnumerable<ParticleSystemRenderer>)(((object)descendants) ?? ((object)new ParticleSystemRenderer[0]))).Concat((IEnumerable<ParticleSystemRenderer>)(object)new ParticleSystemRenderer[1] { direct })
				where Object.op_Implicit((Object)(object)r) && ((Object)(object)r == (Object)(object)direct || ((Object)r).name == "FakeLight") && (!Object.op_Implicit((Object)(object)fire) || (Object)(object)((Component)r).gameObject != (Object)(object)((Component)fire).gameObject)
				select r).Distinct().Cast<Renderer>().ToArray();
		}

		public CaveLighting(ComputeShader template, SwarmCatalog data, Transform authoringFrame, float level, float faintIntensity = 0.28f, float faintRadius = 7f, float burstIntensity = 3.2f, float burstRadius = 36f)
		{
			compute = Object.Instantiate<ComputeShader>(template);
			catalog = data;
			frame = authoringFrame;
			darkness = level;
			restingIntensity = faintIntensity;
			restingRadius = faintRadius;
			lanternIntensity = burstIntensity;
			lanternRadius = burstRadius;
			RenderPipelineManager.beginFrameRendering += Begin;
			RenderPipelineManager.endFrameRendering += End;
			subscribed = true;
		}

		public bool Refresh()
		{
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0110: Unknown result type (might be due to invalid IL or missing references)
			//IL_0116: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0201: Unknown result type (might be due to invalid IL or missing references)
			//IL_0203: Unknown result type (might be due to invalid IL or missing references)
			//IL_020e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0219: Expected O, but got Unknown
			//IL_024d: Unknown result type (might be due to invalid IL or missing references)
			//IL_024e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0261: Unknown result type (might be due to invalid IL or missing references)
			//IL_0266: Unknown result type (might be due to invalid IL or missing references)
			//IL_026d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0272: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_030a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0461: Unknown result type (might be due to invalid IL or missing references)
			//IL_0466: Unknown result type (might be due to invalid IL or missing references)
			//IL_0489: Unknown result type (might be due to invalid IL or missing references)
			//IL_048e: Unknown result type (might be due to invalid IL or missing references)
			//IL_04bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_04c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_0597: Unknown result type (might be due to invalid IL or missing references)
			//IL_059c: Unknown result type (might be due to invalid IL or missing references)
			//IL_05b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_05b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_05bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_04ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_04f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_04f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0663: Unknown result type (might be due to invalid IL or missing references)
			//IL_0665: Unknown result type (might be due to invalid IL or missing references)
			//IL_0666: Unknown result type (might be due to invalid IL or missing references)
			//IL_066b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0671: Unknown result type (might be due to invalid IL or missing references)
			//IL_0676: Unknown result type (might be due to invalid IL or missing references)
			//IL_0678: Unknown result type (might be due to invalid IL or missing references)
			//IL_067a: Unknown result type (might be due to invalid IL or missing references)
			//IL_067b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0680: Unknown result type (might be due to invalid IL or missing references)
			//IL_0686: Unknown result type (might be due to invalid IL or missing references)
			//IL_068b: Unknown result type (might be due to invalid IL or missing references)
			//IL_068d: Unknown result type (might be due to invalid IL or missing references)
			//IL_06ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_06c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_06e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0705: Unknown result type (might be due to invalid IL or missing references)
			//IL_0723: Unknown result type (might be due to invalid IL or missing references)
			//IL_05e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_05d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_0602: Unknown result type (might be due to invalid IL or missing references)
			//IL_05f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_0622: Unknown result type (might be due to invalid IL or missing references)
			//IL_0614: Unknown result type (might be due to invalid IL or missing references)
			//IL_062c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0631: Unknown result type (might be due to invalid IL or missing references)
			//IL_0636: Unknown result type (might be due to invalid IL or missing references)
			//IL_0638: Unknown result type (might be due to invalid IL or missing references)
			//IL_063a: Unknown result type (might be due to invalid IL or missing references)
			//IL_063c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0641: Unknown result type (might be due to invalid IL or missing references)
			//IL_0643: Unknown result type (might be due to invalid IL or missing references)
			//IL_0645: Unknown result type (might be due to invalid IL or missing references)
			//IL_0647: Unknown result type (might be due to invalid IL or missing references)
			//IL_064c: Unknown result type (might be due to invalid IL or missing references)
			if (!Object.op_Implicit((Object)(object)frame))
			{
				return false;
			}
			Texture globalTexture = Shader.GetGlobalTexture("_LightMap");
			if ((Object)(object)globalTexture == (Object)(object)map)
			{
				globalTexture = original;
			}
			if (!Object.op_Implicit((Object)(object)globalTexture))
			{
				return false;
			}
			Texture3D val = (Texture3D)(object)((globalTexture is Texture3D) ? globalTexture : null);
			if (!Object.op_Implicit((Object)(object)val))
			{
				throw new InvalidOperationException("Native cave lighting expects PEAK's Texture3D light volume.");
			}
			Vector4 globalVector = Shader.GetGlobalVector("_GridOffset");
			float globalFloat = Shader.GetGlobalFloat("_RaySpacing");
			if (globalFloat <= 0f || !SwarmClock.Finite(globalFloat))
			{
				return false;
			}
			if (Object.op_Implicit((Object)(object)map) && (Object)(object)globalTexture == (Object)(object)original && matrix == frame.localToWorldMatrix && grid == globalVector && spacing == globalFloat)
			{
				return true;
			}
			End(default(ScriptableRenderContext), null);
			ReleaseMap();
			long num = (long)((Texture)val).width * (long)((Texture)val).height * val.depth;
			if (num <= 0 || num > 33554432)
			{
				throw new InvalidOperationException("Native light volume exceeds the trial's 256 MB GPU-copy budget.");
			}
			if (!SystemInfo.supportsComputeShaders || !SystemInfo.supports3DRenderTextures)
			{
				throw new InvalidOperationException("Native cave-lighting trial requires compute and 3D render textures.");
			}
			RenderTextureDescriptor val2 = default(RenderTextureDescriptor);
			((RenderTextureDescriptor)(ref val2))..ctor(((Texture)val).width, ((Texture)val).height);
			((RenderTextureDescriptor)(ref val2)).dimension = (TextureDimension)3;
			((RenderTextureDescriptor)(ref val2)).volumeDepth = val.depth;
			((RenderTextureDescriptor)(ref val2)).graphicsFormat = ((Texture)val).graphicsFormat;
			((RenderTextureDescriptor)(ref val2)).enableRandomWrite = true;
			((RenderTextureDescriptor)(ref val2)).msaaSamples = 1;
			((RenderTextureDescriptor)(ref val2)).mipCount = 1;
			((RenderTextureDescriptor)(ref val2)).depthBufferBits = 0;
			RenderTextureDescriptor val3 = val2;
			RenderTexture val4 = new RenderTexture(val3)
			{
				name = "PF_Cave_NativeLightVolume_Copy",
				filterMode = (FilterMode)2,
				wrapMode = ((Texture)val).wrapMode,
				hideFlags = (HideFlags)61
			};
			if (!val4.Create())
			{
				Release((Object)(object)val4);
				throw new InvalidOperationException("Could not allocate private native light volume.");
			}
			map = val4;
			original = globalTexture;
			grid = globalVector;
			spacing = globalFloat;
			matrix = frame.localToWorldMatrix;
			SourceFormat = ((object)((Texture)val).graphicsFormat/*cast due to .constrained prefix*/).ToString();
			Graphics.CopyTexture((Texture)(object)val, 0, 0, (Texture)(object)map, 0, 0);
			kernel = compute.FindKernel("DarkenCaves");
			compute.SetTexture(kernel, "_NativeLightMap", (Texture)(object)val);
			compute.SetTexture(kernel, "_CaveLightMap", (Texture)(object)map);
			compute.SetMatrix("_WorldToAuthoring", frame.worldToLocalMatrix);
			compute.SetVector("_NativeOffset", globalVector);
			compute.SetFloat("_NativeSpacing", globalFloat);
			compute.SetFloat("_DarkLevel", darkness);
			compute.SetInts("_NativeDimensions", new int[3]
			{
				((Texture)val).width,
				((Texture)val).height,
				val.depth
			});
			compute.SetInt("_ItemCount", 0);
			compute.SetVectorArray("_ItemSources", itemSources);
			compute.SetVectorArray("_ItemFill", itemFill);
			compute.SetInt("_SwarmCount", 0);
			compute.SetVectorArray("_SwarmSources", swarmSources);
			compute.SetVectorArray("_SwarmFill", swarmFill);
			regions.Clear();
			nextIndirect = 0.0;
			Vector4[] array = (Vector4[])(object)new Vector4[2];
			Vector4[] array2 = (Vector4[])(object)new Vector4[2];
			Vector4[] array3 = (Vector4[])(object)new Vector4[34];
			Vector4[] array4 = (Vector4[])(object)new Vector4[8];
			for (int i = 0; i < 2; i++)
			{
				Chamber chamber = catalog.rooms[i];
				array[i] = new Vector4(chamber.x, chamber.y, chamber.height, chamber.width);
				array2[i] = new Vector4(chamber.depth, chamber.mouth, chamber.throat, 0f);
				for (int j = 0; j < 17; j++)
				{
					array3[i * 17 + j] = new Vector4(chamber.front[j], 0f, 0f, 0f);
				}
				for (int k = 0; k < 4; k++)
				{
					array4[i * 4 + k] = Vector4.op_Implicit(chamber.portals[k]);
				}
			}
			compute.SetVectorArray("_RoomsA", array);
			compute.SetVectorArray("_RoomsB", array2);
			compute.SetVectorArray("_Fronts", array3);
			compute.SetVectorArray("_Portals", array4);
			VoxelsChanged = 0;
			Chamber[] rooms = catalog.rooms;
			Vector3 val5 = default(Vector3);
			foreach (Chamber chamber2 in rooms)
			{
				Bounds bounds = chamber2.Bounds;
				((Vector3)(ref val5))..ctor(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity);
				Vector3 val6 = -val5;
				for (int m = 0; m < 8; m++)
				{
					Vector3 val7 = frame.TransformPoint(new Vector3(((m & 1) == 0) ? ((Bounds)(ref bounds)).min.x : ((Bounds)(ref bounds)).max.x, ((m & 2) == 0) ? ((Bounds)(ref bounds)).min.y : ((Bounds)(ref bounds)).max.y, ((m & 4) == 0) ? ((Bounds)(ref bounds)).min.z : ((Bounds)(ref bounds)).max.z));
					val5 = Vector3.Min(val5, val7);
					val6 = Vector3.Max(val6, val7);
				}
				val5 = (val5 - Vector4.op_Implicit(globalVector)) / globalFloat;
				val6 = (val6 - Vector4.op_Implicit(globalVector)) / globalFloat;
				int num2 = Mathf.Clamp(Mathf.FloorToInt(val5.x) - 1, 0, ((Texture)val).width - 1);
				int num3 = Mathf.Clamp(Mathf.FloorToInt(val5.y) - 1, 0, ((Texture)val).height - 1);
				int num4 = Mathf.Clamp(Mathf.FloorToInt(val5.z) - 1, 0, val.depth - 1);
				int num5 = Mathf.Clamp(Mathf.CeilToInt(val6.x) + 1, 0, ((Texture)val).width - 1);
				int num6 = Mathf.Clamp(Mathf.CeilToInt(val6.y) + 1, 0, ((Texture)val).height - 1);
				int num7 = Mathf.Clamp(Mathf.CeilToInt(val6.z) + 1, 0, val.depth - 1);
				int num8 = num5 - num2 + 1;
				int num9 = num6 - num3 + 1;
				int num10 = num7 - num4 + 1;
				regions.Add(new Region
				{
					x = num2,
					y = num3,
					z = num4,
					nx = num8,
					ny = num9,
					nz = num10
				});
				VoxelsChanged += num8 * num9 * num10;
			}
			Dispatch();
			return true;
		}

		private void Dispatch()
		{
			foreach (Region region in regions)
			{
				compute.SetInts("_RegionStart", new int[3] { region.x, region.y, region.z });
				compute.SetInts("_RegionSize", new int[3] { region.nx, region.ny, region.nz });
				compute.Dispatch(kernel, (region.nx + 7) / 8, (region.ny + 7) / 8, (region.nz + 3) / 4);
			}
		}

		public bool UpdateIndirect(SwarmVisuals effects, double now, bool force = false)
		{
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_010a: Unknown result type (might be due to invalid IL or missing references)
			//IL_010f: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b9: 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_01c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0206: Unknown result type (might be due to invalid IL or missing references)
			//IL_0244: Unknown result type (might be due to invalid IL or missing references)
			//IL_023b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0249: Unknown result type (might be due to invalid IL or missing references)
			//IL_0252: Unknown result type (might be due to invalid IL or missing references)
			//IL_0259: Unknown result type (might be due to invalid IL or missing references)
			//IL_0260: Unknown result type (might be due to invalid IL or missing references)
			//IL_0269: Unknown result type (might be due to invalid IL or missing references)
			//IL_026e: Unknown result type (might be due to invalid IL or missing references)
			//IL_027a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0281: Unknown result type (might be due to invalid IL or missing references)
			//IL_0288: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b0: Unknown result type (might be due to invalid IL or missing references)
			if (!Ready || effects == null || (!force && now < nextIndirect))
			{
				return false;
			}
			nextIndirect = now + 0.05;
			SwarmVisuals.Swarm[] swarms = effects.Swarms;
			if (swarms.Length > 12)
			{
				throw new InvalidOperationException("Swarm fill-light budget exceeded");
			}
			for (int i = 0; i < swarms.Length; i++)
			{
				SwarmVisuals.Swarm swarm = swarms[i];
				float pulse = swarm.pulse;
				Vector3 val = frame.InverseTransformPoint(swarm.node.transform.position);
				swarmSources[i] = new Vector4(val.x, val.y, val.z, Mathf.Lerp(14f, 44f, pulse));
				swarmFill[i] = new Vector4(0.58f, 0.66f, 1f, Mathf.Lerp(0.02f * restingIntensity / 0.28f, 0.16f * lanternIntensity / 3.2f, pulse));
			}
			int num = 0;
			Light[] array = (Light[])(((object)LanternLights) ?? ((object)new Light[0]));
			foreach (Light item in (from l in array.Concat((IEnumerable<Light>)(((object)FillLights) ?? ((object)new Light[0])))
				where Object.op_Implicit((Object)(object)l) && ((Behaviour)l).enabled && ((Component)l).gameObject.activeInHierarchy && l.intensity > 0f
				select l).Distinct().OrderBy(delegate(Light l)
			{
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				//IL_000c: 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_0016: Unknown result type (might be due to invalid IL or missing references)
				Vector3 val4 = ((Component)l).transform.position - ViewerPosition;
				return ((Vector3)(ref val4)).sqrMagnitude;
			}).Take(16))
			{
				Vector3 val2 = frame.InverseTransformPoint(((Component)item).transform.position);
				if (!(catalog.Weight(val2) <= 0.05f))
				{
					float num2 = (item.range - spacing * 1.733f) / Mathf.Max(0.001f, frame.lossyScale.x);
					if (!(num2 <= 0.1f))
					{
						Color val3 = (array.Contains(item) ? ItemLampAPI.Tint(item) : item.color);
						itemSources[num] = new Vector4(val2.x, val2.y, val2.z, num2);
						itemFill[num] = new Vector4(val3.r, val3.g, val3.b, Mathf.Clamp(item.intensity * 0.025f, 0f, 0.1f));
						num++;
					}
				}
			}
			LastItemFills = num;
			compute.SetInt("_ItemCount", num);
			compute.SetVectorArray("_ItemSources", itemSources);
			compute.SetVectorArray("_ItemFill", itemFill);
			compute.SetInt("_SwarmCount", swarms.Length);
			compute.SetVectorArray("_SwarmSources", swarmSources);
			compute.SetVectorArray("_SwarmFill", swarmFill);
			Dispatch();
			return true;
		}

		private void Begin(ScriptableRenderContext context, Camera[] cameras)
		{
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_013e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0143: Unknown result type (might be due to invalid IL or missing references)
			//IL_014f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0154: Unknown result type (might be due to invalid IL or missing references)
			//IL_0160: Unknown result type (might be due to invalid IL or missing references)
			//IL_0165: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0295: Unknown result type (might be due to invalid IL or missing references)
			//IL_029a: Unknown result type (might be due to invalid IL or missing references)
			//IL_02cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_02db: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0310: Unknown result type (might be due to invalid IL or missing references)
			//IL_0316: Invalid comparison between Unknown and I4
			//IL_0253: Unknown result type (might be due to invalid IL or missing references)
			//IL_0258: Unknown result type (might be due to invalid IL or missing references)
			//IL_03b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_03b5: Unknown result type (might be due to invalid IL or missing references)
			LastTintedLanterns = 0;
			LastHiddenGlows = 0;
			if (!Ready || !Object.op_Implicit((Object)(object)frame) || !((Component)frame).gameObject.activeInHierarchy)
			{
				return;
			}
			if (bound)
			{
				End(context, cameras);
			}
			Texture globalTexture = Shader.GetGlobalTexture("_LightMap");
			if ((Object)(object)globalTexture != (Object)(object)original)
			{
				return;
			}
			boundOriginal = globalTexture;
			boundMinimum = Shader.GetGlobalFloat("_AmbienceMin");
			bound = true;
			Shader.SetGlobalTexture("_LightMap", (Texture)(object)map);
			Shader.SetGlobalFloat("_AmbienceMin", Mathf.Lerp(boundMinimum, Mathf.Min(boundMinimum, 0.008f), ViewerWeight));
			if (ViewerWeight > 0.5f && Object.op_Implicit((Object)(object)PersonalLight))
			{
				adjustedLight = PersonalLight;
				personalWasEnabled = ((Behaviour)adjustedLight).enabled;
				personalIntensity = adjustedLight.intensity;
				personalRange = adjustedLight.range;
				personalColor = adjustedLight.color;
				personalShadows = adjustedLight.shadows;
				personalMode = adjustedLight.renderMode;
				adjustedLight.intensity = restingIntensity;
				adjustedLight.range = restingRadius;
				adjustedLight.color = new Color(0.58f, 0.66f, 1f);
				adjustedLight.shadows = (LightShadows)0;
				adjustedLight.renderMode = (LightRenderMode)1;
				((Behaviour)adjustedLight).enabled = true;
			}
			if (ViewerWeight > 0.5f && LanternLights != null)
			{
				Light[] lanternLights = LanternLights;
				foreach (Light val in lanternLights)
				{
					if (Object.op_Implicit((Object)(object)val) && ((Behaviour)val).enabled && ((Component)val).gameObject.activeInHierarchy && !((Object)(object)val == (Object)(object)PersonalLight) && !(catalog.Weight(frame.InverseTransformPoint(((Component)val).transform.position)) <= 0.05f))
					{
						tintedLanterns.Add(new LanternState
						{
							light = val,
							color = val.color,
							temperature = val.useColorTemperature,
							intensity = val.intensity,
							range = val.range,
							shadows = val.shadows,
							mode = val.renderMode
						});
						val.color = ItemLampAPI.Tint(val);
						val.useColorTemperature = false;
						val.renderMode = (LightRenderMode)1;
						if ((int)val.shadows > 0)
						{
							val.shadows = (LightShadows)2;
						}
					}
				}
			}
			LastTintedLanterns = tintedLanterns.Count;
			if (ViewerWeight > 0.5f && LanternGlows != null)
			{
				Renderer[] lanternGlows = LanternGlows;
				foreach (Renderer val2 in lanternGlows)
				{
					if (Object.op_Implicit((Object)(object)val2) && ((Component)val2).gameObject.activeInHierarchy && !(catalog.Weight(frame.InverseTransformPoint(((Component)val2).transform.position)) <= 0.05f))
					{
						hiddenGlows.Add(new GlowState
						{
							renderer = val2,
							enabled = val2.enabled
						});
						val2.enabled = false;
					}
				}
			}
			LastHiddenGlows = hiddenGlows.Count;
		}

		private void End(ScriptableRenderContext context, Camera[] cameras)
		{
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_010d: Unknown result type (might be due to invalid IL or missing references)
			//IL_017f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0191: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a3: Unknown result type (might be due to invalid IL or missing references)
			if (!bound)
			{
				return;
			}
			foreach (GlowState hiddenGlow in hiddenGlows)
			{
				if (Object.op_Implicit((Object)(object)hiddenGlow.renderer))
				{
					hiddenGlow.renderer.enabled = hiddenGlow.enabled;
				}
			}
			hiddenGlows.Clear();
			foreach (LanternState tintedLantern in tintedLanterns)
			{
				if (Object.op_Implicit((Object)(object)tintedLantern.light))
				{
					tintedLantern.light.color = tintedLantern.color;
					tintedLantern.light.useColorTemperature = tintedLantern.temperature;
					tintedLantern.light.intensity = tintedLantern.intensity;
					tintedLantern.light.range = tintedLantern.range;
					tintedLantern.light.shadows = tintedLantern.shadows;
					tintedLantern.light.renderMode = tintedLantern.mode;
				}
			}
			tintedLanterns.Clear();
			if (Object.op_Implicit((Object)(object)adjustedLight))
			{
				adjustedLight.intensity = personalIntensity;
				adjustedLight.range = personalRange;
				adjustedLight.color = personalColor;
				adjustedLight.shadows = personalShadows;
				adjustedLight.renderMode = personalMode;
				((Behaviour)adjustedLight).enabled = personalWasEnabled;
			}
			adjustedLight = null;
			if ((Object)(object)Shader.GetGlobalTexture("_LightMap") == (Object)(object)map)
			{
				Shader.SetGlobalTexture("_LightMap", boundOriginal);
			}
			Shader.SetGlobalFloat("_AmbienceMin", boundMinimum);
			bound = false;
			boundOriginal = null;
		}

		private static void Release(Object value)
		{
			if (Application.isPlaying)
			{
				Object.Destroy(value);
			}
			else
			{
				Object.DestroyImmediate(value);
			}
		}

		private void ReleaseMap()
		{
			if (Object.op_Implicit((Object)(object)map))
			{
				map.Release();
				Release((Object)(object)map);
			}
			map = null;
			original = null;
		}

		public void Dispose()
		{
			//IL_0004: 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)
			End(default(ScriptableRenderContext), null);
			if (subscribed)
			{
				RenderPipelineManager.beginFrameRendering -= Begin;
				RenderPipelineManager.endFrameRendering -= End;
				subscribed = false;
			}
			ReleaseMap();
			if (Object.op_Implicit((Object)(object)compute))
			{
				Release((Object)(object)compute);
			}
		}
	}
	[BepInPlugin("local.peak.poisonforest.cavebugs", "Thunderfen Cave Swarms", "1.0.0")]
	[BepInDependency("local.peak.poisonforest.electrical", "0.1.5")]
	[BepInDependency("local.peak.poisonforest.lightning", "0.1.7")]
	[BepInDependency("local.peak.poisonforest.solo", "0.5.0")]
	[DefaultExecutionOrder(1100)]
	public sealed class SwarmTrial : BaseUnityPlugin
	{
		[Serializable]
		private sealed class Report
		{
			public string utc;

			public string version = "1.0.0";

			public string message;

			public string error;

			public string lightFormat;

			public int seed;

			public int revision;

			public int clusters;

			public int activeLights;

			public int lightVoxels;

			public int transfers;

			public int lanternLights;

			public int lanternGlows;

			public int tintedLanterns;

			public int hiddenLanternGlows;

			public int disabledExteriorLanterns;

			public int litFlareLights;

			public int itemFillLights;

			public bool solo;

			public bool pending;

			public bool nativeLightMapCopyReady;

			public bool inside;

			public bool personalLightFound;

			public bool viewFromCamera;

			public float caveWeight;

			public float charge;

			public float[] burstStrength;

			public float[] transferRemaining;
		}

		public const string Id = "local.peak.poisonforest.cavebugs";

		public const string Version = "1.0.0";

		private PortableItemLighting portable;

		private LanternPresentation lanterns;

		private float nextLanternScan;

		private SwarmSettings settings;

		private AssetBundle bundle;

		private ComputeShader compute;

		private Material particle;

		private SwarmCatalog catalog;

		private SwarmClock[] clocks;

		private SharedPulse[] sharedPulses;

		private SwarmVisuals visuals;

		private CaveLighting lighting;

		private Transform frame;

		private int revision = -1;

		private int transfers;

		private float nextPoll;

		private float nextLighting;

		private float nextReport;

		private float began;

		private bool ready;

		private bool inside;

		private bool viewFromCamera;

		private string error;

		private string message = "Waiting for a new solo run";

		private string folder;

		private float weight;

		private readonly RaycastHit[] hits = (RaycastHit[])(object)new RaycastHit[64];

		private static readonly FieldInfo electricalReady = typeof(ElectricalTrial).GetField("ready", BindingFlags.Instance | BindingFlags.NonPublic);

		private static readonly FieldInfo electricalFailed = typeof(ElectricalTrial).GetField("failed", BindingFlags.Instance | BindingFlags.NonPublic);

		private static readonly FieldInfo electricalCompatible = typeof(ElectricalTrial).GetField("compatible", BindingFlags.Instance | BindingFlags.NonPublic);

		private void Awake()
		{
			folder = Path.Combine(Application.persistentDataPath, "ThunderfenCave");
			Directory.CreateDirectory(folder);
			try
			{
				string directoryName = Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location);
				settings = JsonUtility.FromJson<SwarmSettings>(File.ReadAllText(Path.Combine(directoryName, "PoisonForestCaveBugs.settings.json")));
				if (settings != null)
				{
					settings.Upgrade();
				}
				ValidateSettings(settings);
				bundle = AssetBundle.LoadFromFile(Path.Combine(directoryName, "pf-cavebugs"));
				if (!Object.op_Implicit((Object)(object)bundle))
				{
					throw new Exception("Cave lighting bundle missing");
				}
				compute = bundle.LoadAsset<ComputeShader>("NativeCaveDarkness");
				particle = bundle.LoadAsset<Material>("CaveBugParticles");
				Shader val = bundle.LoadAsset<Shader>("OwlberryGlow");
				if (!Object.op_Implicit((Object)(object)compute) || !Object.op_Implicit((Object)(object)particle) || !Object.op_Implicit((Object)(object)particle.shader) || !particle.shader.isSupported || !Object.op_Implicit((Object)(object)val) || !val.isSupported)
				{
					throw new Exception("Cave lighting/particle assets unsupported");
				}
				portable = new PortableItemLighting();
				lanterns = new LanternPresentation
				{
					InCave = (Vector3 p) => Object.op_Implicit((Object)(object)frame) && ((Component)frame).gameObject.activeInHierarchy && catalog != null && catalog.Weight(frame.InverseTransformPoint(p)) > 0.05f
				};
				SharedWorld.Message += OnShared;
				ready = true;
				((BaseUnityPlugin)this).Logger.LogInfo((object)"Cave swarms ready: native light-volume copy, real point lights, persistent faint glow; solo first version. No input bindings.");
			}
			catch (Exception e)
			{
				Fail(e);
			}
		}

		public static void ValidateSettings(SwarmSettings s)
		{
			if (s == null)
			{
				throw new Exception("Cave swarm settings missing");
			}
			float[] array = new float[10] { s.darkness, s.chargeRadius, s.transferAmount, s.transferInterval, s.faintLightIntensity, s.faintLightRadius, s.burstLightIntensity, s.burstLightRadius, s.visualDistance, s.lightCullDistance };
			foreach (float num in array)
			{
				if (!SwarmClock.Finite(num))
				{
					throw new Exception("Non-finite cave swarm setting");
				}
			}
			if (s.darkness < 0.001f || s.darkness > 0.25f || s.chargeRadius < 1f || s.chargeRadius > 8f || s.transferAmount <= 0f || s.transferAmount > 0.25f || s.transferInterval < 0.25f || s.transferInterval > 30f || s.faintLightIntensity <= 0f || s.faintLightIntensity > 1f || s.faintLightRadius < 1f || s.faintLightRadius > 12f || s.burstLightIntensity < 0.5f || s.burstLightIntensity > 8f || s.burstLightRadius < 10f || s.burstLightRadius > 48f || s.visualDistance < 30f || s.visualDistance > 150f || s.lightCullDistance < s.burstLightRadius || s.lightCullDistance > 100f)
			{
				throw new Exception("Cave swarm settings outside supported ranges");
			}
		}

		private static string Hash(byte[] b)
		{
			using SHA256 sHA = SHA256.Create();
			return BitConverter.ToString(sHA.ComputeHash(b)).Replace("-", "");
		}

		private void Update()
		{
			//IL_011f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0124: Unknown result type (might be due to invalid IL or missing references)
			//IL_035d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0362: Unknown result type (might be due to invalid IL or missing references)
			//IL_0350: Unknown result type (might be due to invalid IL or missing references)
			//IL_0348: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_03af: Unknown result type (might be due to invalid IL or missing references)
			//IL_042c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0431: Unknown result type (might be due to invalid IL or missing references)
			//IL_0424: Unknown result type (might be due to invalid IL or missing references)
			//IL_0417: Unknown result type (might be due to invalid IL or missing references)
			//IL_0460: Unknown result type (might be due to invalid IL or missing references)
			//IL_0482: Unknown result type (might be due to invalid IL or missing references)
			//IL_0484: Unknown result type (might be due to invalid IL or missing references)
			//IL_069f: Unknown result type (might be due to invalid IL or missing references)
			//IL_06b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_06b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_06ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_06e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_06ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_0779: Unknown result type (might be due to invalid IL or missing references)
			//IL_077e: Unknown result type (might be due to invalid IL or missing references)
			//IL_058a: Unknown result type (might be due to invalid IL or missing references)
			//IL_059b: Unknown result type (might be due to invalid IL or missing references)
			//IL_05a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_05a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_05d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_05db: Unknown result type (might be due to invalid IL or missing references)
			if (!ready)
			{
				return;
			}
			try
			{
				lanterns.Active = PhotonNetwork.InRoom && SharedWorld.Ready;
				lanterns.CaveVisible = false;
				if (Time.unscaledTime >= nextLanternScan)
				{
					nextLanternScan = Time.unscaledTime + 1f;
					Lantern[] source = Resources.FindObjectsOfTypeAll<Lantern>().Where(delegate(Lantern l)
					{
						//IL_000e: Unknown result type (might be due to invalid IL or missing references)
						//IL_0013: Unknown result type (might be due to invalid IL or missing references)
						int result;
						if (Object.op_Implicit((Object)(object)l))
						{
							Scene scene = ((Component)l).gameObject.scene;
							result = (((Scene)(ref scene)).IsValid() ? 1 : 0);
						}
						else
						{
							result = 0;
						}
						return (byte)result != 0;
					}).ToArray();
					portable.Scan();
					lanterns.Lights = portable.LanternLights.Concat(portable.FlareLights).Distinct().ToArray();
					lanterns.Glows = source.SelectMany((Lantern l) => CaveLighting.FindLanternGlows(l.lightParticle, l.fireParticle, ((Component)l).GetComponentsInChildren<ParticleSystemRenderer>(true))).Distinct().ToArray();
				}
				portable.Tick();
				Scene sceneByName = SceneManager.GetSceneByName("WilIsland");
				bool isLoaded = ((Scene)(ref sceneByName)).isLoaded;
				if (!isLoaded || !PhotonNetwork.InRoom || RunData.Pending)
				{
					if (Object.op_Implicit((Object)(object)frame) || catalog != null)
					{
						Clear();
					}
					message = ((!isLoaded) ? "Waiting for a run" : ((!PhotonNetwork.OfflineMode) ? "Cave swarms: solo trial only" : "Waiting for fresh terrain"));
					ReportNow();
					return;
				}
				if (revision != RunData.Revision)
				{
					Clear();
					revision = RunData.Revision;
				}
				if (Time.unscaledTime >= nextPoll)
				{
					nextPoll = Time.unscaledTime + 0.5f;
					Transform val = FindFrame();
					if ((Object)(object)val != (Object)(object)frame)
					{
						Clear();
						frame = val;
						if (Object.op_Implicit((Object)(object)frame))
						{
							Build();
						}
					}
				}
				if (!Object.op_Implicit((Object)(object)frame) || !((Component)frame).gameObject.activeInHierarchy || visuals == null)
				{
					message = "Waiting for Poison Forest";
					ReportNow();
					return;
				}
				if (Time.unscaledTime >= nextLighting)
				{
					nextLighting = Time.unscaledTime + 1f;
					lighting.Refresh();
					lighting.LanternLights = portable.LanternLights;
					Transform val2 = (Object.op_Implicit((Object)(object)Character.localCharacter) ? ((Component)Character.localCharacter).transform.Find("Scout/Misc/CharacterLight") : null);
					lighting.PersonalLight = ((settings.managePersonalLight && Object.op_Implicit((Object)(object)val2)) ? ((Component)val2).GetComponent<Light>() : null);
				}
				Character localCharacter = Character.localCharacter;
				Camera main = Camera.main;
				viewFromCamera = Object.op_Implicit((Object)(object)main);
				Vector3 val3 = (Object.op_Implicit((Object)(object)main) ? ((Component)main).transform.position : (Object.op_Implicit((Object)(object)localCharacter) ? localCharacter.Center : frame.position));
				inside = Object.op_Implicit((Object)(object)localCharacter) && (Object)(object)localCharacter.data != (Object)null && !localCharacter.data.dead;
				weight = (inside ? catalog.Weight(frame.InverseTransformPoint(val3)) : 0f);
				inside &= weight > 0.05f;
				lighting.ViewerWeight = weight;
				lanterns.CaveVisible = weight > 0.5f;
				Vector3 observer = (Object.op_Implicit((Object)(object)localCharacter) ? localCharacter.Center : (Object.op_Implicit((Object)(object)main) ? ((Component)main).transform.position : frame.position));
				visuals.Tick(frame, clocks, SharedWorld.Online ? SharedWorld.Elapsed : ((double)(Time.time - began)), observer);
				if (weight > 0.01f)
				{
					lighting.ViewerPosition = val3;
					lighting.FillLights = portable.FlareLights.Concat(ItemLampAPI.FillLights).ToArray();
					lighting.UpdateIndirect(visuals, Time.unscaledTime);
				}
				if (!SharedWorld.Ready)
				{
					ReportNow();
					return;
				}
				bool flag = ElectricalReady(localCharacter) && ElectricalTrial.Instance.Model.Charge < 0.99999f;
				for (int num = 0; num < clocks.Length; num++)
				{
					Vector3 val4;
					if (SharedWorld.Online)
					{
						bool flag2 = sharedPulses[num].Tick(SharedWorld.Elapsed);
						if (!(SharedWorld.Authority && flag2))
						{
							continue;
						}
						SwarmVisuals.Swarm swarm = visuals.Swarms[num];
						foreach (Character allCharacter in Character.AllCharacters)
						{
							if (ElectricalTrial.CanReceive(allCharacter) && ElectricalTrial.ChargeFor(allCharacter) < 0.99999f)
							{
								val4 = allCharacter.Center - swarm.node.transform.position;
								if (((Vector3)(ref val4)).sqrMagnitude <= settings.chargeRadius * settings.chargeRadius && LineClear(swarm.node.transform.position, allCharacter.Center))
								{
									SharedWorld.Charge("swarm:" + num, ((MonoBehaviourPun)allCharacter).photonView.ViewID, settings.transferAmount, 0f, sharedPulses[num].Serial);
								}
							}
						}
					}
					else
					{
						if (!clocks[num].TickDose(Mathf.Min(1f, Time.deltaTime), settings.transferInterval))
						{
							continue;
						}
						SwarmVisuals.Swarm swarm2 = visuals.Swarms[num];
						if (!flag)
						{
							continue;
						}
						val4 = localCharacter.Center - swarm2.node.transform.position;
						if (!(((Vector3)(ref val4)).sqrMagnitude <= settings.chargeRadius * settings.chargeRadius) || !LineClear(swarm2.node.transform.position, localCharacter.Center))
						{
							continue;
						}
						ElectricalModel model = ElectricalTrial.Instance.Model;
						float charge = model.Charge;
						model.Set(charge + settings.transferAmount);
						float num2 = model.Charge - charge;
						if (num2 > 0f)
						{
							localCharacter.ClampStamina();
							ElectricalTrial.RefreshBar();
							Character struck = localCharacter;
							Vector3 lastCenter = struck.Center;
							visuals.Strike(num, () => Object.op_Implicit((Object)(object)struck) ? struck.Center : lastCenter);
							transfers++;
							((BaseUnityPlugin)this).Logger.LogInfo((object)("Swarm " + num + " discharged " + (num2 * 100f).ToString("F1") + " electrical points; area dose to every eligible player; independent one-second clock."));
						}
					}
				}
				message = (inside ? "Cave swarms: steady glow between illumination bursts" : "Electrical swarms active inside the mountain");
				ReportNow();
			}
			catch (Exception e)
			{
				Fail(e);
			}
		}

		private void OnShared(string kind, string id, object[] data)
		{
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			if (!SharedWorld.Online || kind != "charge" || data.Length != 5 || visuals == null || !(data[0] is string text) || !text.StartsWith("swarm:", StringComparison.Ordinal) || !int.TryParse(text.Substring(6), out var result) || result < 0 || result >= visuals.Swarms.Length)
			{
				return;
			}
			Character target = SharedWorld.CharacterFor(Convert.ToInt32(data[1]));
			if (Object.op_Implicit((Object)(object)target))
			{
				Vector3 center = target.Center;
				visuals.Strike(result, () => Object.op_Implicit((Object)(object)target) ? target.Center : center);
			}
		}

		private bool ElectricalReady(Character c)
		{
			ElectricalTrial instance = ElectricalTrial.Instance;
			return Object.op_Implicit((Object)(object)c) && Object.op_Implicit((Object)(object)((MonoBehaviourPun)c).photonView) && Object.op_Implicit((Object)(object)instance) && electricalReady != null && electricalFailed != null && electricalCompatible != null && (bool)electricalReady.GetValue(instance) && !(bool)electricalFailed.GetValue(instance) && (bool)electricalCompatible.GetValue(instance) && ((MonoBehaviourPun)c).photonView.ViewID > 0;
		}

		private bool LineClear(Vector3 from, Vector3 to)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: 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_0026: 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)
			Vector3 val = to - from;
			float magnitude = ((Vector3)(ref val)).magnitude;
			if (magnitude < 0.001f)
			{
				return true;
			}
			int num = Physics.RaycastNonAlloc(from, val / magnitude, hits, magnitude, -5, (QueryTriggerInteraction)1);
			if (num >= hits.Length)
			{
				return false;
			}
			for (int i = 0; i < num; i++)
			{
				Collider collider = ((RaycastHit)(ref hits[i])).collider;
				if (Object.op_Implicit((Object)(object)collider) && !collider.isTrigger && !Object.op_Implicit((Object)(object)((Component)collider).GetComponentInParent<Character>()) && !Object.op_Implicit((Object)(object)((Component)collider).GetComponentInParent<Bodypart>()) && !Object.op_Implicit((Object)(object)((Component)collider).GetComponentInParent<Item>()))
				{
					return false;
				}
			}
			return true;
		}

		private Transform FindFrame()
		{
			//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)
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Expected O, but got Unknown
			Scene sceneByName = SceneManager.GetSceneByName("WilIsland");
			if (!((Scene)(ref sceneByName)).IsValid() || !((Scene)(ref sceneByName)).isLoaded)
			{
				return null;
			}
			GameObject val = ((IEnumerable<GameObject>)((Scene)(ref sceneByName)).GetRootGameObjects()).FirstOrDefault((Func<GameObject, bool>)((GameObject o) => ((Object)o).name == "Map"));
			if (!Object.op_Implicit((Object)(object)val))
			{
				return null;
			}
			Transform val2 = val.transform.Find("Global");
			if (!Object.op_Implicit((Object)(object)val2))
			{
				return null;
			}
			foreach (Transform item in val2)
			{
				Transform val3 = item;
				if (((Object)val3).name.Contains("first-ridge"))
				{
					Transform val4 = ((IEnumerable<Transform>)((Component)val3).GetComponentsInChildren<Transform>(true)).FirstOrDefault((Func<Transform, bool>)((Transform x) => ((Object)x).name == "PF_HybridTerrain" && Object.op_Implicit((Object)(object)x.parent) && ((Object)x.parent).name == "RootsTerrain"));
					if (Object.op_Implicit((Object)(object)val4) && ((Component)val4).gameObject.activeInHierarchy)
					{
						return val4;
					}
				}
			}
			return null;
		}

		private void Build()
		{
			catalog = SwarmCatalog.Read(GeneratedData.Read("cave-bugs.bin"));
			if (RunData.Dynamic && catalog.seed != RunData.Seed)
			{
				throw new Exception("Swarm seed differs from fresh terrain");
			}
			clocks = catalog.sites.Select((SwarmSite s) => new SwarmClock(s.interval, s.phase, s.duration, settings.transferInterval)).ToArray();
			sharedPulses = ((IEnumerable<SwarmSite>)catalog.sites).Select((Func<SwarmSite, SharedPulse>)((SwarmSite site) => new SharedPulse(catalog.seed * 997 + site.id, (double)settings.transferInterval, (double)settings.transferInterval, SharedWorld.Elapsed))).ToArray();
			visuals = new SwarmVisuals(frame, catalog, particle, settings);
			lighting = new CaveLighting(compute, catalog, frame, settings.darkness, settings.faintLightIntensity, settings.faintLightRadius, settings.burstLightIntensity, settings.burstLightRadius);
			began = Time.time;
			transfers = 0;
			nextLighting = 0f;
			((BaseUnityPlugin)this).Logger.LogInfo((object)("Generated cave swarms: " + catalog.sites.Length + " in " + catalog.rooms.Length + " chambers, seed=" + catalog.seed + ". Burst periods 18..24s (12..18s resting), illumination 6s, resting glow persists."));
		}

		private void Clear()
		{
			lighting?.Dispose();
			lighting = null;
			visuals?.Dispose();
			visuals = null;
			catalog = null;
			clocks = null;
			frame = null;
			inside = false;
			weight = 0f;
			if (lanterns != null)
			{
				lanterns.CaveVisible = false;
			}
		}

		private void ReportNow()
		{
			if (!RuntimeDiagnostics.PeriodicSnapshots || Time.unscaledTime < nextReport)
			{
				return;
			}
			nextReport = Time.unscaledTime + 2f;
			try
			{
				string path = Path.Combine(folder, "cave-bugs-state.json");
				Report obj = new Report
				{
					utc = DateTime.UtcNow.ToString("O"),
					message = message,
					error = error,
					solo = PhotonNetwork.OfflineMode,
					pending = RunData.Pending,
					revision = revision,
					seed = (catalog?.seed ?? 0)
				};
				SwarmCatalog swarmCatalog = catalog;
				obj.clusters = ((swarmCatalog != null) ? swarmCatalog.sites.Length : 0);
				obj.nativeLightMapCopyReady = lighting != null && lighting.Ready;
				obj.personalLightFound = lighting != null && Object.op_Implicit((Object)(object)lighting.PersonalLight);
				obj.viewFromCamera = viewFromCamera;
				obj.lightFormat = lighting?.SourceFormat;
				obj.lightVoxels = lighting?.VoxelsChanged ?? 0;
				obj.inside = inside;
				obj.caveWeight = weight;
				obj.charge = (Object.op_Implicit((Object)(object)Character.localCharacter) ? ElectricalTrial.ChargeFor(Character.localCharacter) : 0f);
				obj.transfers = transfers;
				obj.activeLights = visuals?.ActiveLights ?? 0;
				obj.lanternLights = (lanterns?.Lights?.Length).GetValueOrDefault();
				obj.lanternGlows = (lanterns?.Glows?.Length).GetValueOrDefault();
				obj.tintedLanterns = lighting?.LastTintedLanterns ?? 0;
				obj.hiddenLanternGlows = lanterns?.LastHiddenGlows ?? 0;
				obj.disabledExteriorLanterns = lanterns?.LastDisabledLights ?? 0;
				obj.litFlareLights = portable?.LitFlares ?? 0;
				obj.itemFillLights = lighting?.LastItemFills ?? 0;
				obj.burstStrength = visuals?.Swarms.Select((SwarmVisuals.Swarm s) => s.pulse).ToArray();
				obj.transferRemaining = clocks?.Select((SwarmClock c) => (float)c.TransferRemaining).ToArray();
				File.WriteAllText(path, JsonUtility.ToJson((object)obj, true));
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)ex.Message);
			}
		}

		private void Fail(Exception e)
		{
			error = e.ToString();
			message = "Cave swarm trial stopped; see diagnostic log";
			ready = false;
			Clear();
			lanterns?.Dispose();
			lanterns = null;
			portable?.Dispose();
			portable = null;
			((BaseUnityPlugin)this).Logger.LogError((object)error);
			ReportNow();
		}

		private void OnDestroy()
		{
			SharedWorld.Message -= OnShared;
			Clear();
			lanterns?.Dispose();
			lanterns = null;
			portable?.Dispose();
			portable = null;
			if (Object.op_Implicit((Object)(object)bundle))
			{
				bundle.Unload(false);
			}
		}
	}
	[Serializable]
	public sealed class SwarmSettings
	{
		public float darkness = 0.025f;

		public float chargeRadius = 6.75f;

		public float transferAmount = 0.05f;

		public float transferInterval = 1f;

		public float faintLightIntensity = 0.28f;

		public float faintLightRadius = 7f;

		public float burstLightIntensity = 3.2f;

		public float burstLightRadius = 36f;

		public float visualDistance = 90f;

		public float lightCullDistance = 50f;

		public int revision = 1;

		public bool managePersonalLight = true;

		public void Upgrade()
		{
			if (revision < 2)
			{
				if (Math.Abs(faintLightIntensity - 0.055f) < 1E-05f)
				{
					faintLightIntensity = 0.28f;
				}
				if (Math.Abs(faintLightRadius - 2.8f) < 1E-05f)
				{
					faintLightRadius = 7f;
				}
				if (burstLightRadius == 18f)
				{
					burstLightRadius = 36f;
				}
				if (visualDistance == 70f)
				{
					visualDistance = 90f;
				}
				if (lightCullDistance == 40f)
				{
					lightCullDistance = 50f;
				}
				revision = 2;
			}
			if (revision < 3)
			{
				if (Math.Abs(chargeRadius - 4.5f) < 1E-05f)
				{
					chargeRadius = 6.75f;
				}
				if (Math.Abs(transferAmount - 0.1f) < 1E-05f)
				{
					transferAmount = 0.05f;
				}
				if (transferInterval == 8f)
				{
					transferInterval = 1f;
				}
				revision = 3;
			}
			if (revision < 4)
			{
				revision = 4;
			}
		}
	}
	public sealed class LanternPresentation : IDisposable
	{
		private struct LightState
		{
			public Light light;

			public bool enabled;
		}

		private struct GlowState
		{
			public Renderer renderer;

			public bool enabled;
		}

		public bool Active;

		public bool CaveVisible;

		public Func<Vector3, bool> InCave;

		public Light[] Lights;

		public Renderer[] Glows;

		private readonly List<LightState> lights = new List<LightState>();

		private readonly List<GlowState> glows = new List<GlowState>();

		private bool bound;

		public int LastDisabledLights { get; private set; }

		public int LastHiddenGlows { get; private set; }

		public LanternPresentation()
		{
			RenderPipelineManager.beginFrameRendering += Begin;
			RenderPipelineManager.endFrameRendering += End;
		}

		private void Begin(ScriptableRenderContext context, Camera[] cameras)
		{
			//IL_000c: 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)
			if (bound)
			{
				End(context, cameras);
			}
			LastDisabledLights = 0;
			LastHiddenGlows = 0;
			if (!Active)
			{
				return;
			}
			bound = true;
			if (Lights != null)
			{
				Light[] array = Lights;
				foreach (Light val in array)
				{
					if (Object.op_Implicit((Object)(object)val) && ((Component)val).gameObject.activeInHierarchy && (!CaveVisible || InCave == null || !InCave(((Component)val).transform.position)))
					{
						lights.Add(new LightState
						{
							light = val,
							enabled = ((Behaviour)val).enabled
						});
						((Behaviour)val).enabled = false;
					}
				}
			}
			if (Glows != null)
			{
				Renderer[] array2 = Glows;
				foreach (Renderer val2 in array2)
				{
					if (Object.op_Implicit((Object)(object)val2) && ((Component)val2).gameObject.activeInHierarchy)
					{
						glows.Add(new GlowState
						{
							renderer = val2,
							enabled = val2.enabled
						});
						val2.enabled = false;
					}
				}
			}
			LastDisabledLights = lights.Count;
			LastHiddenGlows = glows.Count;
		}

		private void End(ScriptableRenderContext context, Camera[] cameras)
		{
			if (!bound)
			{
				return;
			}
			foreach (LightState light in lights)
			{
				if (Object.op_Implicit((Object)(object)light.light))
				{
					((Behaviour)light.light).enabled = light.enabled;
				}
			}
			foreach (GlowState glow in glows)
			{
				if (Object.op_Implicit((Object)(object)glow.renderer))
				{
					glow.renderer.enabled = glow.enabled;
				}
			}
			lights.Clear();
			glows.Clear();
			bound = false;
		}

		public void Dispose()
		{
			//IL_0004: 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)
			End(default(ScriptableRenderContext), null);
			RenderPipelineManager.beginFrameRendering -= Begin;
			RenderPipelineManager.endFrameRendering -= End;
		}
	}
	public static class ItemLampAPI
	{
		public static readonly Color WarmColor = new Color(1f, 0.72f, 0.42f);

		public static readonly Color FaerieColor = new Color(0.16f, 1f, 0.4f);

		public static readonly Color ColdColor = new Color(0.6f, 0.82f, 1f);

		private static readonly HashSet<Light> fills = new HashSet<Light>();

		private static readonly Dictionary<Light, Color> tints = new Dictionary<Light, Color>();

		private static readonly Dictionary<Light, float> multipliers = new Dictionary<Light, float>();

		public const float NativeCaveLanternIntensity = 3.2f;

		public const float NativeCaveLanternRange = 36f;

		public static Light[] FillLights => fills.Where((Light l) => Object.op_Implicit((Object)(object)l)).ToArray();

		public static void RegisterFill(Light l)
		{
			if (Object.op_Implicit((Object)(object)l))
			{
				fills.Add(l);
			}
		}

		public static void RemoveFill(Light l)
		{
			if (l != null)
			{
				fills.Remove(l);
			}
		}

		public static void Register(Light light, float scale)
		{
			if (Object.op_Implicit((Object)(object)light))
			{
				multipliers[light] = Mathf.Clamp(scale, 1f, 1.5f);
			}
		}

		public static void Remove(Light light)
		{
			if (light != null)
			{
				multipliers.Remove(light);
				tints.Remove(light);
			}
		}

		public static float Multiplier(Light light)
		{
			float value;
			return (Object.op_Implicit((Object)(object)light) && multipliers.TryGetValue(light, out value)) ? value : 1f;
		}

		public static void SetTint(Light light, Color color)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			if (Object.op_Implicit((Object)(object)light))
			{
				tints[light] = color;
			}
		}

		public static void RemoveTint(Light light)
		{
			if (light != null)
			{
				tints.Remove(light);
			}
		}

		public static Color Tint(Light light)
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			Color value;
			return (Multiplier(light) > 1f) ? ColdColor : ((Object.op_Implicit((Object)(object)light) && tints.TryGetValue(light, out value)) ? value : WarmColor);
		}
	}
	public sealed class PortableItemLighting : IDisposable
	{
		private readonly Dictionary<Flare, Light> flares = new Dictionary<Flare, Light>();

		private readonly HashSet<Light> tinted = new HashSet<Light>();

		public Light[] LanternLights { get; private set; } = (Light[])(object)new Light[0];

		public Light[] FlareLights => flares.Values.Where((Light l) => Object.op_Implicit((Object)(object)l)).ToArray();

		public int LitFlares { get; private set; }

		public void Scan()
		{
			Lantern[] lamps = Resources.FindObjectsOfTypeAll<Lantern>().Where(delegate(Lantern l)
			{
				//IL_000e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0013: Unknown result type (might be due to invalid IL or missing references)
				int result;
				if (Object.op_Implicit((Object)(object)l))
				{
					Scene scene = ((Component)l).gameObject.scene;
					result = (((Scene)(ref scene)).IsValid() ? 1 : 0);
				}
				else
				{
					result = 0;
				}
				return (byte)result != 0;
			}).ToArray();
			Scan(lamps, Resources.FindObjectsOfTypeAll<Flare>().Where(delegate(Flare f)
			{
				//IL_000e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0013: Unknown result type (might be due to invalid IL or missing references)
				int result;
				if (Object.op_Implicit((Object)(object)f))
				{
					Scene scene = ((Component)f).gameObject.scene;
					result = (((Scene)(ref scene)).IsValid() ? 1 : 0);
				}
				else
				{
					result = 0;
				}
				return (byte)result != 0;
			}).ToArray());
		}

		public void Scan(Lantern[] lamps, Flare[] sources)
		{
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_0251: Unknown result type (might be due to invalid IL or missing references)
			//IL_027d: Unknown result type (might be due to invalid IL or missing references)
			HashSet<Light> hashSet = new HashSet<Light>();
			foreach (Lantern val in lamps)
			{
				if (Object.op_Implicit((Object)(object)val) && Object.op_Implicit((Object)(object)val.lanternLight))
				{
					Light lanternLight = val.lanternLight;
					hashSet.Add(lanternLight);
					Item component = ((Component)val).GetComponent<Item>();
					if (!Object.op_Implicit((Object)(object)component) || component.itemID != 62104)
					{
						ItemLampAPI.SetTint(lanternLight, (((Object)val).name.StartsWith("Lantern_Faerie", StringComparison.OrdinalIgnoreCase) || Object.op_Implicit((Object)(object)((Component)val).transform.Find("FaerieLantern"))) ? ItemLampAPI.FaerieColor : ItemLampAPI.WarmColor);
						tinted.Add(lanternLight);
					}
				}
			}
			Light[] array = tinted.ToArray();
			foreach (Light val2 in array)
			{
				if (!hashSet.Contains(val2))
				{
					ItemLampAPI.RemoveTint(val2);
					tinted.Remove(val2);
				}
			}
			LanternLights = hashSet.ToArray();
			HashSet<Flare> hashSet2 = new HashSet<Flare>(sources.Where((Flare f) => Object.op_Implicit((Object)(object)f)));
			KeyValuePair<Flare, Light>[] array2 = flares.ToArray();
			for (int num = 0; num < array2.Length; num++)
			{
				KeyValuePair<Flare, Light> keyValuePair = array2[num];
				if (!Object.op_Implicit((Object)(object)keyValuePair.Key) || !hashSet2.Contains(keyValuePair.Key))
				{
					if (Object.op_Implicit((Object)(object)keyValuePair.Value))
					{
						Object.Destroy((Object)(object)((Component)keyValuePair.Value).gameObject);
					}
					flares.Remove(keyValuePair.Key);
				}
			}
			foreach (Flare item in hashSet2)
			{
				if (!flares.TryGetValue(item, out var value) || !Object.op_Implicit((Object)(object)value))
				{
					Transform val3 = ((Component)item).transform.Find("TF_Flare_TrueLight");
					GameObject val4 = (GameObject)(Object.op_Implicit((Object)(object)val3) ? ((object)((Component)val3).gameObject) : ((object)new GameObject("TF_Flare_TrueLight")));
					val4.transform.SetParent(((Component)item).transform, false);
					val4.transform.localPosition = Vector3.zero;
					Light val5 = val4.GetComponent<Light>();
					if (!Object.op_Implicit((Object)(object)val5))
					{
						val5 = val4.AddComponent<Light>();
					}
					val5.type = (LightType)2;
					val5.range = 9f;
					val5.intensity = 1.2f;
					val5.shadows = (LightShadows)0;
					val5.renderMode = (LightRenderMode)1;
					((Behaviour)val5).enabled = false;
					flares[item] = val5;
				}
			}
			Tick();
		}

		public static bool ReadFlare(Item item, Color fallback, out Color color)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			color = fallback;
			BoolItemData val = default(BoolItemData);
			if (!Object.op_Implicit((Object)(object)item) || item.data == null || !item.data.TryGetDataEntry<BoolItemData>((DataEntryKey)3, ref val) || !val.Value)
			{
				return false;
			}
			ColorItemData val2 = default(ColorItemData);
			if (item.data.TryGetDataEntry<ColorItemData>((DataEntryKey)9, ref val2))
			{
				color = val2.Value;
			}
			return Finite(color.r) && Finite(color.g) && Finite(color.b);
		}

		private static bool Finite(float n)
		{
			return !float.IsNaN(n) && !float.IsInfinity(n) && n >= 0f && n <= 1f;
		}

		public static bool Emitting(Flare flare)
		{
			if (!Object.op_Implicit((Object)(object)flare))
			{
				return false;
			}
			TrackableNetworkObject component = ((Component)flare).GetComponent<TrackableNetworkObject>();
			TrackNetworkedObject val = (Object.op_Implicit((Object)(object)component) ? component.currentTracker : null);
			if (!Object.op_Implicit((Object)(object)val) || !((Component)val).gameObject.activeInHierarchy)
			{
				return false;
			}
			ParticleSystem component2 = ((Component)val).GetComponent<ParticleSystem>();
			return Object.op_Implicit((Object)(object)component2) && component2.isEmitting;
		}

		public void Tick()
		{
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			LitFlares = 0;
			foreach (KeyValuePair<Flare, Light> flare in flares)
			{
				if (Object.op_Implicit((Object)(object)flare.Value))
				{
					Flare key = flare.Key;
					Color color = Color.white;
					bool flag = Object.op_Implicit((Object)(object)key) && ((Component)key).gameObject.activeInHierarchy && ReadFlare(((Component)key).GetComponent<Item>(), key.flareColor, out color) && Emitting(key);
					((Behaviour)flare.Value).enabled = flag;
					if (flag)
					{
						color.a = 1f;
						flare.Value.color = color;
						LitFlares++;
					}
				}
			}
		}

		public void Dispose()
		{
			foreach (KeyValuePair<Flare, Light> flare in flares)
			{
				if (Object.op_Implicit((Object)(object)flare.Value))
				{
					Object.Destroy((Object)(object)((Component)flare.Value).gameObject);
				}
			}
			flares.Clear();
			foreach (Light item in tinted)
			{
				ItemLampAPI.RemoveTint(item);
			}
			tinted.Clear();
			LanternLights = (Light[])(object)new Light[0];
		}
	}
}

plugins/ThunderfenCrocodile/PoisonForestCrocodile.dll

Decompiled a week ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security.Cryptography;
using System.Text;
using BepInEx;
using ExitGames.Client.Photon;
using Microsoft.CodeAnalysis;
using Photon.Pun;
using Photon.Realtime;
using PoisonForestGeneration;
using PoisonForestSolo;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.SceneManagement;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyVersion("0.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace PoisonForestCrocodile
{
	[Serializable]
	public struct P
	{
		public float x;

		public float y;

		public float z;

		public P(float x, float y, float z)
		{
			this.x = x;
			this.y = y;
			this.z = z;
		}

		public static float Flat(P a, P b)
		{
			float num = a.x - b.x;
			float num2 = a.z - b.z;
			return (float)Math.Sqrt(num * num + num2 * num2);
		}

		public static P Lerp(P a, P b, float t)
		{
			return new P(a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t, a.z + (b.z - a.z) * t);
		}
	}
	public sealed class NavGrid
	{
		private sealed class Heap
		{
			private readonly List<KeyValuePair<int, float>> a = new List<KeyValuePair<int, float>>();

			public int Count => a.Count;

			public void Push(int i, float f)
			{
				a.Add(new KeyValuePair<int, float>(i, f));
				int num = a.Count - 1;
				while (num > 0)
				{
					int num2 = (num - 1) / 2;
					if (a[num2].Value <= f)
					{
						break;
					}
					a[num] = a[num2];
					num = num2;
				}
				a[num] = new KeyValuePair<int, float>(i, f);
			}

			public int Pop()
			{
				int key = a[0].Key;
				KeyValuePair<int, float> value = a[a.Count - 1];
				a.RemoveAt(a.Count - 1);
				if (a.Count > 0)
				{
					int num = 0;
					while (num * 2 + 1 < a.Count)
					{
						int num2 = num * 2 + 1;
						if (num2 + 1 < a.Count && a[num2 + 1].Value < a[num2].Value)
						{
							num2++;
						}
						if (a[num2].Value >= value.Value)
						{
							break;
						}
						a[num] = a[num2];
						num = num2;
					}
					a[num] = value;
				}
				return key;
			}
		}

		public int nx;

		public int nz;

		public float x0;

		public float z0;

		public float dx;

		public float dz;

		public float[] height;

		public float[] water;

		public byte[] open;

		public P[] nests;

		public static NavGrid Read(byte[] bytes)
		{
			using BinaryReader binaryReader = new BinaryReader(new MemoryStream(bytes));
			if (new string(binaryReader.ReadChars(4)) != "PFC1")
			{
				throw new Exception("Navigation signature");
			}
			NavGrid navGrid = new NavGrid
			{
				nx = binaryReader.ReadInt32(),
				nz = binaryReader.ReadInt32(),
				x0 = binaryReader.ReadSingle(),
				z0 = binaryReader.ReadSingle(),
				dx = binaryReader.ReadSingle(),
				dz = binaryReader.ReadSingle()
			};
			if (navGrid.nx < 2 || navGrid.nx > 512 || navGrid.nz < 2 || navGrid.nz > 512 || navGrid.dx <= 0f || navGrid.dz <= 0f)
			{
				throw new Exception("Navigation dimensions");
			}
			int num = navGrid.nx * navGrid.nz;
			navGrid.height = new float[num];
			navGrid.water = new float[num];
			for (int i = 0; i < num; i++)
			{
				navGrid.height[i] = binaryReader.ReadSingle();
			}
			for (int j = 0; j < num; j++)
			{
				navGrid.water[j] = binaryReader.ReadSingle();
			}
			navGrid.open = binaryReader.ReadBytes(num);
			int num2 = binaryReader.ReadInt32();
			if (num2 < 4 || num2 > 12 || navGrid.open.Length != num)
			{
				throw new Exception("Navigation nest count");
			}
			navGrid.nests = new P[num2];
			for (int k = 0; k < num2; k++)
			{
				navGrid.nests[k] = new P(binaryReader.ReadSingle(), binaryReader.ReadSingle(), binaryReader.ReadSingle());
			}
			if (binaryReader.BaseStream.Position != binaryReader.BaseStream.Length || navGrid.height.Any((float v) => float.IsNaN(v) || float.IsInfinity(v)))
			{
				throw new Exception("Navigation values");
			}
			return navGrid;
		}

		public int Index(P p)
		{
			int num = (int)Math.Round((p.x - x0) / dx);
			int num2 = (int)Math.Round((p.z - z0) / dz);
			return (num >= 0 && num < nx && num2 >= 0 && num2 < nz) ? (num2 * nx + num) : (-1);
		}

		public P Point(int i)
		{
			return new P(x0 + (float)(i % nx) * dx, height[i], z0 + (float)(i / nx) * dz);
		}

		public bool Surface(float x, float z, out float y)
		{
			y = 0f;
			float num = (x - x0) / dx;
			float num2 = (z - z0) / dz;
			if (float.IsNaN(num) || float.IsNaN(num2) || num < 0f || num2 < 0f || num >= (float)(nx - 1) || num2 >= (float)(nz - 1))
			{
				return false;
			}
			int num3 = (int)Math.Floor(num);
			int num4 = (int)Math.Floor(num2);
			int num5 = num4 * nx + num3;
			float num6 = num - (float)num3;
			float num7 = num2 - (float)num4;
			int a = ((num6 + num7 > 1f) ? (num5 + 1) : num5);
			int num8 = num5 + nx;
			int b = ((num6 + num7 > 1f) ? (num5 + nx + 1) : (num5 + 1));
			if (!Edge(a, num8) || !Edge(num8, b) || !Edge(a, b))
			{
				return false;
			}
			y = ((num6 + num7 > 1f) ? (height[num5 + 1] * (1f - num7) + height[num5 + nx] * (1f - num6) + height[num5 + nx + 1] * (num6 + num7 - 1f)) : (height[num5] * (1f - num6 - num7) + height[num5 + nx] * num7 + height[num5 + 1] * num6));
			return true;
		}

		public int Snap(P p, float radius = 5f)
		{
			int result = -1;
			float num = radius;
			int num2 = Index(p);
			if (num2 < 0)
			{
				return -1;
			}
			int num3 = (int)Math.Ceiling(radius / dx);
			for (int i = Math.Max(0, num2 / nx - num3); i <= Math.Min(nz - 1, num2 / nx + num3); i++)
			{
				for (int j = Math.Max(0, num2 % nx - num3); j <= Math.Min(nx - 1, num2 % nx + num3); j++)
				{
					int num4 = i * nx + j;
					if (open[num4] != 0)
					{
						float num5 = P.Flat(p, Point(num4));
						if (num5 <= num && Math.Abs(p.y - height[num4]) < 5f)
						{
							result = num4;
							num = num5;
						}
					}
				}
			}
			return result;
		}

		public bool Edge(int a, int b)
		{
			if (a < 0 || b < 0 || open[a] == 0 || open[b] == 0)
			{
				return false;
			}
			int num = b % nx - a % nx;
			int num2 = b / nx - a / nx;
			if (Math.Abs(num) > 1 || Math.Abs(num2) > 1)
			{
				return false;
			}
			float num3 = (float)Math.Sqrt((float)(num * num) * dx * dx + (float)(num2 * num2) * dz * dz);
			if (num3 == 0f || Math.Abs(height[a] - height[b]) > num3 * 0.81f)
			{
				return false;
			}
			if (num != 0 && num2 != 0 && (open[a + num] == 0 || open[a + num2 * nx] == 0))
			{
				return false;
			}
			return true;
		}

		public List<P> Path(P from, P to, P nest, float leash)
		{
			int num = Snap(from);
			int num2 = Snap(to);
			if (num < 0 || num2 < 0 || P.Flat(Point(num2), nest) > leash)
			{
				return null;
			}
			int num3 = height.Length;
			float[] array = new float[num3];
			int[] array2 = new int[num3];
			bool[] array3 = new bool[num3];
			for (int i = 0; i < num3; i++)
			{
				array[i] = float.PositiveInfinity;
				array2[i] = -1;
			}
			array[num] = 0f;
			Heap heap = new Heap();
			heap.Push(num, 0f);
			int num4 = 0;
			while (heap.Count > 0 && num4++ < 25000)
			{
				int num5 = heap.Pop();
				if (array3[num5])
				{
					continue;
				}
				array3[num5] = true;
				if (num5 == num2)
				{
					List<P> list = new List<P>();
					for (int num6 = num2; num6 >= 0; num6 = array2[num6])
					{
						list.Add(Point(num6));
						if (num6 == num)
						{
							break;
						}
					}
					list.Reverse();
					return list;
				}
				for (int j = -1; j <= 1; j++)
				{
					for (int k = -1; k <= 1; k++)
					{
						int num7 = num5 % nx + k;
						int num8 = num5 / nx + j;
						if (num7 < 0 || num7 >= nx || num8 < 0 || num8 >= nz)
						{
							continue;
						}
						int num9 = num8 * nx + num7;
						if (!array3[num9] && Edge(num5, num9) && !(P.Flat(Point(num9), nest) > leash))
						{
							float num10 = array[num5] + P.Flat(Point(num5), Point(num9));
							if (num10 < array[num9])
							{
								array[num9] = num10;
								array2[num9] = num5;
								heap.Push(num9, num10 + P.Flat(Point(num9), Point(num2)));
							}
						}
					}
				}
			}
			return null;
		}
	}
	public sealed class ObstacleMemory
	{
		private readonly NavGrid nav;

		private readonly Dictionary<int, double> expiry = new Dictionary<int, double>();

		public int Count => expiry.Count;

		public ObstacleMemory(NavGrid nav)
		{
			this.nav = nav;
		}

		public void Expire(double now)
		{
			int[] array = (from p in expiry
				where p.Value <= now
				select p.Key).ToArray();
			foreach (int num2 in array)
			{
				nav.open[num2] = 1;
				expiry.Remove(num2);
			}
		}

		public void Mark(P contact, P agent, double now)
		{
			int num = nav.Index(contact);
			int num2 = nav.Index(agent);
			if (num < 0)
			{
				return;
			}
			for (int i = -1; i <= 1; i++)
			{
				for (int j = -1; j <= 1; j++)
				{
					int num3 = num % nav.nx + j;
					int num4 = num / nav.nx + i;
					if (num3 >= 0 && num4 >= 0 && num3 < nav.nx && num4 < nav.nz)
					{
						int num5 = num4 * nav.nx + num3;
						if (num5 != num2 && !(P.Flat(nav.Point(num5), contact) >= 1.25f) && !(Math.Abs(nav.height[num5] - contact.y) > 2.5f) && (nav.open[num5] != 0 || expiry.ContainsKey(num5)))
						{
							nav.open[num5] = 0;
							expiry[num5] = now + 3.0;
						}
					}
				}
			}
		}
	}
	public enum Mode
	{
		Wander,
		Chase,
		Windup,
		Drag,
		Return,
		Cooldown,
		Lunge
	}
	public static class PopulationRule
	{
		public static int Choose(Random random, int candidates, int maximum)
		{
			if (candidates < 4 || candidates > 12 || maximum < 4 || maximum > 12)
			{
				throw new ArgumentOutOfRangeException("Crocodile population requires four to twelve usable nests");
			}
			return candidates;
		}
	}
	[Serializable]
	public sealed class Rules
	{
		public float wanderRadius = 11f;

		public float detectRadius = 20f;

		public float chaseRadius = 60f;

		public float biteDistance = 2.7f;

		public float biteWindup = 0.12f;

		public float cooldown = 20f;

		public float wanderSpeedRatio = 0.38f;

		public float maxDragSeconds = 55f;

		public float releaseKnockdownSeconds = 5f;

		public float biteLungeDistance = 2.8f;

		public float biteLungeSeconds = 0.34f;

		public float biteHopHeight = 0.6f;

		public float biteRecovery = 0.6f;

		public int nestCount = 5;
	}
	[Serializable]
	public sealed class Agent
	{
		public int id;

		public int target;

		public int serial;

		public int releasedView;

		public int releaseSerial;

		public bool releasedAtNest;

		public double releasedAt;

		public Mode mode;

		public P pos;

		public P nest;

		public float yaw;

		public float speed;

		public float hop;

		public P lungeFrom;

		public P lungeEnd;

		public double lungeAt;

		public double attackReadyAt;

		public double until;

		public double captureAt;

		public double lastProgress;

		public double cooldownUntil;

		public P lastProgressPos;

		[NonSerialized]
		public List<P> path;

		[NonSerialized]
		public int waypoint;

		[NonSerialized]
		public double repath;

		public string reason;
	}
	public sealed class Person
	{
		public int id;

		public P pos;

		public float speed;

		public bool captured;
	}
	public static class MovementPace
	{
		public static float Normal(float force, float drag, float step, float sprintMultiplier = 1f)
		{
			return Math.Max(0.6f, Math.Min(12f, force * Math.Max(1f, sprintMultiplier) * step / Math.Max(0.02f, 1f - drag)));
		}
	}
	public sealed class ReleaseReceipts
	{
		private string epoch;

		private readonly Dictionary<int, int> seen = new Dictionary<int, int>();

		public bool Take(string run, Agent a, int localView, double now, float seconds, out float remaining)
		{
			remaining = 0f;
			if (epoch != run)
			{
				epoch = run;
				seen.Clear();
			}
			if (!a.releasedAtNest || a.releasedView != localView || a.releaseSerial <= 0)
			{
				return false;
			}
			if (seen.TryGetValue(a.id, out var value) && value >= a.releaseSerial)
			{
				return false;
			}
			seen[a.id] = a.releaseSerial;
			double num = now - a.releasedAt;
			if (num < -0.25 || num >= (double)seconds)
			{
				return false;
			}
			remaining = (float)((double)seconds - Math.Max(0.0, num));
			return remaining > 0f;
		}
	}
	public static class Brain
	{
		public static Agent Spawn(int id, P nest)
		{
			return new Agent
			{
				id = id,
				nest = nest,
				pos = nest,
				mode = Mode.Wander,
				lastProgressPos = nest
			};
		}

		private static Person Find(IList<Person> p, int id)
		{
			return p.FirstOrDefault((Person x) => x.id == id);
		}

		public static void Release(Agent a, double now, Rules r, string why)
		{
			a.releasedView = a.target;
			a.releasedAt = now;
			a.releasedAtNest = why == "nest reached";
			a.releaseSerial = ++a.serial;
			a.hop = 0f;
			a.target = 0;
			a.mode = Mode.Cooldown;
			a.cooldownUntil = now + (double)r.cooldown;
			a.until = now;
			a.path = null;
			a.reason = why;
			a.speed = 0f;
		}

		private static void Route(Agent a, List<P> path, Func<P, P, bool> clear)
		{
			a.path = path;
			a.waypoint = 0;
			if (path == null || path.Count < 2)
			{
				return;
			}
			P p = path[0];
			P arg = path[1];
			float num = arg.x - p.x;
			float num2 = arg.z - p.z;
			float num3 = num * num + num2 * num2;
			if (!(num3 < 0.001f))
			{
				float num4 = ((a.pos.x - p.x) * num + (a.pos.z - p.z) * num2) / num3;
				float num5 = Math.Abs((a.pos.x - p.x) * num2 - (a.pos.z - p.z) * num) / (float)Math.Sqrt(num3);
				if (num4 > 0f && num4 <= 1.001f && num5 < 0.55f && clear(a.pos, arg))
				{
					a.waypoint = 1;
				}
			}
		}

		public static float Turn(float current, float desired, float limit)
		{
			float val = ((desired - current) % 360f + 540f) % 360f - 180f;
			return current + Math.Max(0f - limit, Math.Min(limit, val));
		}

		public static void Tick(Agent a, IList<Person> people, NavGrid nav, Rules r, double now, float dt, Random random, Func<P, P, bool> clear, Func<int, bool> acknowledged)
		{
			a.speed = 0f;
			if (a.mode != Mode.Lunge)
			{
				a.hop = Math.Max(0f, a.hop - dt * 3f);
			}
			Person person = Find(people, a.target);
			if (a.mode == Mode.Drag)
			{
				if (person == null)
				{
					Release(a, now, r, "target unavailable");
					return;
				}
				if (now - a.captureAt > (double)r.maxDragSeconds)
				{
					Release(a, now, r, "drag timeout");
					return;
				}
				if (now - a.captureAt > 2.0 && !acknowledged(a.target))
				{
					Release(a, now, r, "capture owner not attached");
					return;
				}
				if (P.Flat(a.pos, a.nest) < 1.1f)
				{
					Release(a, now, r, "nest reached");
					return;
				}
			}
			if (a.mode == Mode.Cooldown && now >= a.cooldownUntil)
			{
				a.mode = Mode.Return;
				a.path = null;
				a.until = now;
			}
			if ((a.mode == Mode.Chase || a.mode == Mode.Windup || a.mode == Mode.Lunge) && (person == null || person.captured || P.Flat(person.pos, a.nest) > r.chaseRadius || P.Flat(a.pos, a.nest) > r.chaseRadius))
			{
				a.mode = Mode.Return;
				a.hop = 0f;
				a.target = 0;
				a.path = null;
				person = null;
			}
			if (a.mode == Mode.Wander)
			{
				person = (from person2 in people
					where !person2.captured && P.Flat(person2.pos, a.pos) < r.detectRadius && P.Flat(person2.pos, a.nest) < r.chaseRadius
					orderby P.Flat(person2.pos, a.pos)
					select person2).FirstOrDefault((Person person2) => nav.Path(a.pos, person2.pos, a.nest, r.chaseRadius) != null);
				if (person != null)
				{
					a.target = person.id;
					a.mode = Mode.Chase;
					a.path = null;
				}
			}
			if (a.mode == Mode.Windup)
			{
				if (P.Flat(a.pos, person.pos) > 0.05f)
				{
					a.yaw = Turn(a.yaw, Angle(a.pos, person.pos), 720f * dt);
				}
				if (now < a.until)
				{
					float num = P.Flat(a.pos, person.pos);
					float num2 = Math.Min(person.speed * dt, Math.Max(0f, num - 1.7f));
					if (!(num > 0.001f))
					{
						return;
					}
					P p = P.Lerp(a.pos, person.pos, num2 / num);
					if (nav.Surface(p.x, p.z, out var y))
					{
						p.y = y;
						if (P.Flat(p, a.nest) <= r.chaseRadius && clear(a.pos, p))
						{
							a.pos = p;
							a.speed = person.speed;
						}
					}
					return;
				}
				double num3 = (double)a.yaw * Math.PI / 180.0;
				a.lungeFrom = a.pos;
				a.lungeEnd = new P(a.pos.x + (float)Math.Sin(num3) * r.biteLungeDistance, a.pos.y, a.pos.z + (float)Math.Cos(num3) * r.biteLungeDistance);
				a.lungeAt = now;
				a.mode = Mode.Lunge;
				a.path = null;
			}
			if (a.mode == Mode.Lunge)
			{
				Lunge(a, person, nav, r, now, clear);
				return;
			}
			if (a.mode == Mode.Chase && now >= a.attackReadyAt && P.Flat(a.pos, person.pos) < r.biteDistance && Math.Abs(a.pos.y - person.pos.y) < 1.5f)
			{
				a.mode = Mode.Windup;
				a.until = now + (double)r.biteWindup;
				a.path = null;
				return;
			}
			P to = a.nest;
			float num4 = person?.speed ?? ((people.Count > 0) ? people[0].speed : 4f);
			bool flag = a.mode == Mode.Wander || a.mode == Mode.Cooldown;
			if (flag)
			{
				num4 *= r.wanderSpeedRatio;
				if (a.path == null || a.waypoint >= a.path.Count)
				{
					if (now < a.until)
					{
						return;
					}
					float leash = r.wanderRadius;
					if (P.Flat(a.pos, a.nest) > r.wanderRadius)
					{
						to = a.nest;
						leash = r.chaseRadius;
					}
					else
					{
						to = a.nest;
					}
					List<P> list = null;
					for (int num5 = 0; num5 < 12; num5++)
					{
						if (list != null)
						{
							break;
						}
						if (P.Flat(a.pos, a.nest) <= r.wanderRadius)
						{
							double num6 = random.NextDouble() * Math.PI * 2.0;
							double num7 = 2.0 + random.NextDouble() * (double)(r.wanderRadius - 2f);
							to = new P(a.nest.x + (float)Math.Cos(num6) * (float)num7, a.nest.y, a.nest.z + (float)Math.Sin(num6) * (float)num7);
						}
						int num8 = nav.Snap(to);
						if (num8 >= 0 && !(P.Flat(nav.Point(num8), a.pos) < 1f))
						{
							list = nav.Path(a.pos, nav.Point(num8), a.nest, leash);
						}
					}
					Route(a, list, clear);
					a.until = now + ((list == null) ? 0.5 : (2.0 + random.NextDouble() * 3.0));
				}
			}
			else if (a.path == null || now >= a.repath)
			{
				if (a.mode == Mode.Chase)
				{
					to = person.pos;
				}
				Route(a, nav.Path(a.pos, to, a.nest, r.chaseRadius), clear);
				a.repath = now + 0.7;
			}
			if (a.path == null)
			{
				if (a.mode == Mode.Drag)
				{
					if (now - a.lastProgress > 6.0)
					{
						Release(a, now, r, "return path blocked");
					}
				}
				else if (a.mode == Mode.Chase)
				{
					a.mode = Mode.Return;
					a.target = 0;
				}
				return;
			}
			if (a.mode == Mode.Drag && P.Flat(Mouth(a), person.pos) > 3.2f)
			{
				if (now - a.lastProgress > 6.0)
				{
					Release(a, now, r, "tether blocked by terrain");
				}
				return;
			}
			P pos = a.pos;
			float num9 = num4 * dt;
			int num10 = 0;
			while (num9 > 0f && a.waypoint < a.path.Count && num10++ < 10)
			{
				P b = a.path[a.waypoint];
				float num11 = P.Flat(a.pos, b);
				if (num11 < 0.04f)
				{
					a.waypoint++;
					continue;
				}
				float num12 = Math.Min(1f, num9 / num11);
				P p2 = P.Lerp(a.pos, b, num12);
				if (!clear(a.pos, p2))
				{
					a.repath = 0.0;
					a.path = null;
					if (a.mode == Mode.Drag && now - a.lastProgress > 6.0)
					{
						Release(a, now, r, "physical obstacle");
					}
					return;
				}
				a.pos = p2;
				a.speed = num4;
				num9 -= num11;
				if (num12 < 1f)
				{
					break;
				}
				a.waypoint++;
			}
			if (P.Flat(pos, a.pos) > 0.02f)
			{
				a.yaw = Turn(a.yaw, Angle(pos, a.pos) + (float)((a.mode == Mode.Drag) ? 180 : 0), 360f * dt);
			}
			if (P.Flat(a.pos, a.lastProgressPos) > 0.6f)
			{
				a.lastProgress = now;
				a.lastProgressPos = a.pos;
			}
			if (a.mode == Mode.Return && P.Flat(a.pos, a.nest) < 1.1f)
			{
				a.mode = Mode.Wander;
				a.path = null;
			}
			if (flag && a.path != null && a.waypoint >= a.path.Count)
			{
				a.path = null;
			}
		}

		private static void Miss(Agent a, Rules r, double now, string reason)
		{
			a.mode = Mode.Chase;
			a.hop = 0f;
			a.path = null;
			a.repath = 0.0;
			a.speed = 0f;
			a.attackReadyAt = now + (double)r.biteRecovery;
			a.reason = reason;
		}

		private static P Air(P ground, float hop)
		{
			return new P(ground.x, ground.y + hop, ground.z);
		}

		public static P Closest(P a, P b, P point)
		{
			float num = b.x - a.x;
			float num2 = b.y - a.y;
			float num3 = b.z - a.z;
			float num4 = num * num + num2 * num2 + num3 * num3;
			float t = ((num4 > 1E-06f) ? Math.Max(0f, Math.Min(1f, ((point.x - a.x) * num + (point.y - a.y) * num2 + (point.z - a.z) * num3) / num4)) : 0f);
			return P.Lerp(a, b, t);
		}

		private static void Lunge(Agent a, Person target, NavGrid nav, Rules r, double now, Func<P, P, bool> clear)
		{
			float num = Math.Max(0f, Math.Min(1f, (float)((now - a.lungeAt) / (double)r.biteLungeSeconds)));
			P b = P.Lerp(a.lungeFrom, a.lungeEnd, num);
			float num2 = P.Flat(a.pos, b);
			int num3 = Math.Max(1, (int)Math.Ceiling(num2 / 0.18f));
			P pos = a.pos;
			for (int i = 1; i <= num3; i++)
			{
				float t = (float)i / (float)num3;
				P p = P.Lerp(pos, b, t);
				if (!nav.Surface(p.x, p.z, out var y) || P.Flat(p, a.nest) > r.chaseRadius)
				{
					Miss(a, r, now, "lunge landing is not walkable");
					return;
				}
				p.y = y;
				float num4 = P.Flat(a.pos, p);
				if (num4 > 0.001f && Math.Abs(p.y - a.pos.y) > num4 * 0.81f + 0.02f)
				{
					Miss(a, r, now, "lunge cannot climb steep terrain");
					return;
				}
				float num5 = Math.Min(1f, P.Flat(a.lungeFrom, p) / r.biteLungeDistance);
				float hop = (float)Math.Sin((double)num5 * Math.PI) * r.biteHopHeight;
				P a2 = Mouth(a);
				if (!clear(Air(a.pos, a.hop), Air(p, hop)))
				{
					Miss(a, r, now, "lunge blocked by solid terrain");
					return;
				}
				a.pos = p;
				a.hop = hop;
				a.speed = r.biteLungeDistance / r.biteLungeSeconds;
				if (num5 >= 0.3f)
				{
					P p2 = new P(target.pos.x, target.pos.y + 0.3f, target.pos.z);
					P p3 = Closest(a2, Mouth(a), p2);
					if (P.Flat(p3, p2) < 1.15f && Math.Abs(p3.y - p2.y) < 1.4f && clear(p3, p2))
					{
						a.mode = Mode.Drag;
						a.captureAt = now;
						a.lastProgress = now;
						a.lastProgressPos = a.pos;
						a.serial++;
						a.path = null;
						a.reason = "lunge bite";
						return;
					}
				}
			}
			if (num >= 1f)
			{
				Miss(a, r, now, "lunge missed");
			}
		}

		public static int[] DropClaimedTargets(IList<Agent> agents)
		{
			HashSet<int> hashSet = new HashSet<int>(from a in agents
				where a.mode == Mode.Drag && a.target > 0
				select a.target);
			List<int> list = new List<int>();
			foreach (Agent agent in agents)
			{
				if ((agent.mode == Mode.Chase || agent.mode == Mode.Windup || agent.mode == Mode.Lunge) && hashSet.Contains(agent.target))
				{
					agent.hop = 0f;
					agent.target = 0;
					agent.mode = Mode.Return;
					agent.path = null;
					agent.repath = 0.0;
					agent.reason = "target grabbed by another crocodile";
					list.Add(agent.id);
				}
			}
			return list.ToArray();
		}

		public static float Angle(P a, P b)
		{
			return (float)(Math.Atan2(b.x - a.x, b.z - a.z) * 180.0 / Math.PI);
		}

		public static P Mouth(Agent a)
		{
			double num = (double)a.yaw * Math.PI / 180.0;
			return new P(a.pos.x + (float)Math.Sin(num) * 1.85f, a.pos.y + a.hop + 0.49f, a.pos.z + (float)Math.Cos(num) * 1.85f);
		}
	}
	[Serializable]
	public sealed class CreatureModel
	{
		public ModelPart[] parts;

		[NonSerialized]
		public readonly SharedCrocMeshes sharedMeshes = new SharedCrocMeshes();

		public static CreatureModel FromBinary(byte[] data)
		{
			MeshData[] source = ModelData.Read(data);
			return new CreatureModel
			{
				parts = source.Select((MeshData p) => new ModelPart
				{
					name = p.name,
					vertices = Vectors(p.positions),
					normals = Vectors(p.normals),
					colors = Enumerable.Range(0, p.colors.Length / 4).Select((Func<int, Color>)((int i) => new Color(p.colors[i * 4], p.colors[i * 4 + 1], p.colors[i * 4 + 2], p.colors[i * 4 + 3]))).ToArray(),
					triangles = p.triangles
				}).ToArray()
			};
		}

		private static Vector3[] Vectors(float[] values)
		{
			return Enumerable.Range(0, values.Length / 3).Select((Func<int, Vector3>)((int i) => new Vector3(values[i * 3], values[i * 3 + 1], values[i * 3 + 2]))).ToArray();
		}
	}
	[Serializable]
	public sealed class ModelPart
	{
		public string name;

		public Vector3[] vertices;

		public Vector3[] normals;

		public Color[] colors;

		public int[] triangles;
	}
	public sealed class SharedCrocMeshes
	{
		private readonly Dictionary<string, Mesh> cache = new Dictionary<string, Mesh>();

		private int leases;

		public void Retain()
		{
			leases++;
		}

		public static Mesh Create(ModelPart p, Vector3 offset)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Expected O, but got Unknown
			Mesh val = new Mesh
			{
				name = "PF_Croc_" + p.name
			};
			val.vertices = p.vertices.Select((Vector3 v) => v - offset).ToArray();
			val.triangles = p.triangles;
			val.normals = p.normals;
			val.colors = p.colors;
			val.RecalculateBounds();
			return val;
		}

		public Mesh Get(ModelPart p, Vector3 offset)
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			if (!cache.TryGetValue(p.name, out var value))
			{
				value = Create(p, offset);
				cache.Add(p.name, value);
			}
			return value;
		}

		public void Release()
		{
			if (leases <= 0)
			{
				throw new InvalidOperationException("Crocodile mesh lease underflow");
			}
			if (--leases != 0)
			{
				return;
			}
			foreach (Mesh value in cache.Values)
			{
				if (Object.op_Implicit((Object)(object)value))
				{
					Object.Destroy((Object)(object)value);
				}
			}
			cache.Clear();
		}
	}
	public sealed class CrocVisual : IDisposable
	{
		public GameObject root;

		private readonly SharedCrocMeshes shared;

		private bool disposed;

		private readonly Transform body;

		private readonly Transform jaw;

		private readonly Material material;

		private readonly List<Mesh> meshes = new List<Mesh>();

		private readonly List<Transform> legs = new List<Transform>();

		private readonly Mesh tail;

		private readonly Vector3[] tailBase;

		private readonly Vector3[] tailWork;

		private readonly AudioSource sound;

		private readonly List<LineRenderer> ripples = new List<LineRenderer>();

		private float phase;

		private double lastAnimation;

		private Mode lastMode;

		private int lastSerial = -1;

		private readonly AudioClip snap;

		public bool Live => !disposed && Object.op_Implicit((Object)(object)root);

		private static Transform Node(string name, Transform parent, Vector3 pos)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Expected O, but got Unknown
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject(name);
			val.layer = 2;
			val.transform.SetParent(parent, false);
			val.transform.localPosition = pos;
			return val.transform;
		}

		public CrocVisual(Transform parent, int id, CreatureModel model, Shader shader, Texture texture)
		{
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Expected O, but got Unknown
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: 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_00e4: 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_00fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_010c: Expected O, but got Unknown
			//IL_0117: Unknown result type (might be due to invalid IL or missing references)
			//IL_012d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0281: Unknown result type (might be due to invalid IL or missing references)
			//IL_0286: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_022a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0323: Unknown result type (might be due to invalid IL or missing references)
			//IL_0355: Unknown result type (might be due to invalid IL or missing references)
			//IL_034a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0564: Unknown result type (might be due to invalid IL or missing references)
			//IL_05dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_05e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_02fc: Unknown result type (might be due to invalid IL or missing references)
			shared = model.sharedMeshes;
			shared.Retain();
			root = new GameObject("PF_Crocodile_" + id.ToString("D2"));
			root.layer = 2;
			root.transform.SetParent(parent, false);
			root.transform.localScale = Vector3.one * 1.25f;
			body = Node("AnimatedBody", root.transform, Vector3.zero);
			jaw = Node("JawPivot", body, new Vector3(0f, 0.43f, 0.55f));
			material = new Material(shader)
			{
				name = "PF_Crocodile_OliveSkin"
			};
			material.SetColor("_BaseColor", Color.white);
			material.SetColor("_BackColor", Color.white);
			material.SetFloat("_NoiseStrength", 0.28f);
			material.SetFloat("_NoiseScale", 1.2f);
			material.SetFloat("_NoiseAspect", 0.65f);
			if (Object.op_Implicit((Object)(object)texture))
			{
				material.SetTexture("_NoiseTex", texture);
			}
			Dictionary<string, Transform> dictionary = new Dictionary<string, Transform>();
			string[] array = new string[4] { "LFront", "LRear", "RFront", "RRear" };
			foreach (string text in array)
			{
				float num = ((text[0] != 'L') ? 1 : (-1));
				float num2 = (text.Contains("Front") ? 0.26f : (-0.56f));
				dictionary[text] = Node(text + "Shoulder", body, new Vector3(num * 0.32f, 0.4f, num2));
				legs.Add(dictionary[text]);
			}
			ModelPart[] parts = model.parts;
			foreach (ModelPart modelPart in parts)
			{
				Transform value = body;
				Vector3 offset = Vector3.zero;
				if (modelPart.name == "LowerJaw")
				{
					value = jaw;
					offset = jaw.localPosition;
				}
				else
				{
					foreach (KeyValuePair<string, Transform> item in dictionary)
					{
						if (modelPart.name.StartsWith(item.Key, StringComparison.Ordinal))
						{
							value = item.Value;
							offset = item.Value.localPosition;
							break;
						}
					}
				}
				Transform val = Node(modelPart.name, value, Vector3.zero);
				Mesh val2 = ((modelPart.name == "Tail") ? SharedCrocMeshes.Create(modelPart, offset) : shared.Get(modelPart, offset));
				if (modelPart.name == "Tail")
				{
					meshes.Add(val2);
				}
				((Component)val).gameObject.AddComponent<MeshFilter>().sharedMesh = val2;
				MeshRenderer val3 = ((Component)val).gameObject.AddComponent<MeshRenderer>();
				((Renderer)val3).sharedMaterial = material;
				((Renderer)val3).shadowCastingMode = (ShadowCastingMode)1;
				((Renderer)val3).receiveShadows = true;
				((Renderer)val3).allowOcclusionWhenDynamic = false;
				if (modelPart.name == "Tail")
				{
					tail = val2;
					tailBase = val2.vertices;
					tailWork = (Vector3[])(object)new Vector3[tailBase.Length];
				}
			}
			sound = root.AddComponent<AudioSource>();
			sound.spatialBlend = 1f;
			sound.rolloffMode = (AudioRolloffMode)1;
			sound.minDistance = 2f;
			sound.maxDistance = 25f;
			sound.volume = 0.5f;
			snap = AudioClip.Create("PF_CrocJawSnap", 8820, 1, 22050, false);
			float[] array2 = new float[8820];
			Random random = new Random(420 + id);
			for (int k = 0; k < array2.Length; k++)
			{
				float num3 = (float)k / 22050f;
				array2[k] = ((float)random.NextDouble() * 2f - 1f) * (float)Math.Exp((0f - num3) * 20f) * 0.5f + (float)Math.Sin(num3 * 500f) * (float)Math.Exp((0f - num3) * 13f) * 0.15f;
			}
			snap.SetData(array2, 0);
			Color val6 = default(Color);
			for (int l = 0; l < 2; l++)
			{
				Transform val4 = Node("Wake" + l, root.transform, Vector3.zero);
				LineRenderer val5 = ((Component)val4).gameObject.AddComponent<LineRenderer>();
				val5.useWorldSpace = false;
				val5.loop = true;
				val5.positionCount = 25;
				float startWidth = (val5.endWidth = 0.035f);
				val5.startWidth = startWidth;
				((Renderer)val5).sharedMaterial = material;
				((Color)(ref val6))..ctor(0.6f, 0.72f, 0.64f);
				val5.endColor = val6;
				val5.startColor = val6;
				((Renderer)val5).shadowCastingMode = (ShadowCastingMode)0;
				((Renderer)val5).enabled = false;
				ripples.Add(val5);
			}
		}

		public bool SetVisible(bool visible)
		{
			if (!Live)
			{
				return false;
			}
			root.SetActive(visible);
			return true;
		}

		public void Tick(Agent a, NavGrid nav, float dt, double now)
		{
			//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)
			//IL_009a: 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_00b3: 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_00d4: 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_0101: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_022d: Unknown result type (might be due to invalid IL or missing references)
			//IL_027a: Unknown result type (might be due to invalid IL or missing references)
			//IL_028b: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0385: Unknown result type (might be due to invalid IL or missing references)
			//IL_038a: Unknown result type (might be due to invalid IL or missing references)
			//IL_038c: Unknown result type (might be due to invalid IL or missing references)
			//IL_03e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_03eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0327: Unknown result type (might be due to invalid IL or missing references)
			//IL_057d: Unknown result type (might be due to invalid IL or missing references)
			if (!Live)
			{
				return;
			}
			Vector3 val = default(Vector3);
			((Vector3)(ref val))..ctor(a.pos.x, a.pos.y + a.hop, a.pos.z);
			Vector3 val2 = root.transform.localPosition - val;
			if (((Vector3)(ref val2)).sqrMagnitude > 36f)
			{
				root.transform.localPosition = val;
			}
			else
			{
				root.transform.localPosition = Vector3.Lerp(root.transform.localPosition, val, 1f - Mathf.Exp((0f - dt) * 14f));
			}
			root.transform.localRotation = Quaternion.Slerp(root.transform.localRotation, Quaternion.Euler(0f, a.yaw, 0f), 1f - Mathf.Exp((0f - dt) * 14f));
			float speed = a.speed;
			phase += dt * ((speed > 0.05f) ? (5f + speed) : 1.2f);
			int num = nav.Index(a.pos);
			bool flag = num >= 0 && nav.water[num] > -90000f && a.pos.y < nav.water[num] - 0.1f;
			body.localPosition = new Vector3(0f, (flag ? 0.012f : 0.018f) * Mathf.Sin(phase * 2f) * ((speed > 0.05f) ? 1f : 0.3f), 0f);
			body.localRotation = Quaternion.Euler((a.mode == Mode.Lunge) ? (-12f * Mathf.Clamp01(a.hop / 0.6f)) : 0f, Mathf.Sin(phase) * Mathf.Min(speed, 3f) * 0.7f, flag ? (Mathf.Sin(phase) * 1.5f) : 0f);
			float num2 = ((a.mode == Mode.Lunge) ? 32 : ((a.mode == Mode.Windup) ? 24 : ((a.mode == Mode.Drag) ? 8 : ((a.mode != Mode.Cooldown) ? 1 : 4))));
			jaw.localRotation = Quaternion.Slerp(jaw.localRotation, Quaternion.Euler(num2, 0f, 0f), 1f - Mathf.Exp((0f - dt) * 18f));
			for (int i = 0; i < legs.Count; i++)
			{
				float num3 = Mathf.Sin(phase + ((i == 0 || i == 3) ? 0f : MathF.PI)) * (float)((speed > 0.1f) ? (flag ? 14 : 22) : 2);
				legs[i].localRotation = Quaternion.Euler((float)((a.mode == Mode.Lunge) ? 40 : (flag ? 15 : 0)), num3, (float)(flag ? ((i < 2) ? 10 : (-10)) : 0));
			}
			if (now - lastAnimation > 0.07)
			{
				lastAnimation = now;
				for (int j = 0; j < tailWork.Length; j++)
				{
					Vector3 val3 = tailBase[j];
					float num4 = Mathf.Clamp01((0f - val3.z - 0.63f) / 1.36f);
					val3.x += Mathf.Sin(phase - num4 * 2.8f) * num4 * num4 * ((speed > 0.1f) ? 0.2f : 0.045f);
					tailWork[j] = val3;
				}
				tail.vertices = tailWork;
				tail.RecalculateNormals();
				tail.RecalculateBounds();
			}
			if (a.serial != lastSerial)
			{
				if (lastSerial >= 0 && a.mode == Mode.Drag)
				{
					sound.PlayOneShot(snap);
				}
				lastSerial = a.serial;
			}
			lastMode = a.mode;
			for (int k = 0; k < ripples.Count; k++)
			{
				LineRenderer val4 = ripples[k];
				((Renderer)val4).enabled = flag && speed > 0.1f && a.hop < 0.1f;
				if (((Renderer)val4).enabled)
				{
					float num5 = (float)((now * 0.6 + (double)k * 0.5) % 1.0);
					float num6 = 0.4f + num5 * 0.8f;
					for (int l = 0; l < 25; l++)
					{
						float num7 = (float)l * MathF.PI * 2f / 25f;
						val4.SetPosition(l, new Vector3(Mathf.Sin(num7) * num6, (nav.water[num] - a.pos.y) / 1.25f + 0.015f, Mathf.Cos(num7) * num6 * 1.4f - 0.5f));
					}
					float startWidth = (val4.endWidth = 0.03f * (1f - num5));
					val4.startWidth = startWidth;
				}
			}
		}

		public void Dispose()
		{
			if (disposed)
			{
				return;
			}
			disposed = true;
			if (Object.op_Implicit((Object)(object)root))
			{
				Object.Destroy((Object)(object)root);
			}
			foreach (Mesh mesh in meshes)
			{
				if (Object.op_Implicit((Object)(object)mesh))
				{
					Object.Destroy((Object)(object)mesh);
				}
			}
			if (Object.op_Implicit((Object)(object)material))
			{
				Object.Destroy((Object)(object)material);
			}
			if (Object.op_Implicit((Object)(object)snap))
			{
				Object.Destroy((Object)(object)snap);
			}
			shared.Release();
		}
	}
	public sealed class LegHold : IDisposable
	{
		private readonly Character person;

		private readonly Rigidbody foot;

		private readonly Rigidbody anchor;

		private readonly ConfigurableJoint joint;

		private readonly int originalIterations;

		private readonly int originalVelocity;

		public int view;

		public int agent;

		public int serial;

		public string epoch;

		public bool Valid => Object.op_Implicit((Object)(object)foot) && Object.op_Implicit((Object)(object)anchor) && Object.op_Implicit((Object)(object)joint) && Object.op_Implicit((Object)(object)person) && Object.op_Implicit((Object)(object)person.data) && !person.data.dead;

		public LegHold(Character c, Agent a, string run)
		{
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Expected O, but got Unknown
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0172: Unknown result type (might be due to invalid IL or missing references)
			//IL_0183: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ac: 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)
			//IL_01b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01da: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e1: Unknown result type (might be due to invalid IL or missing references)
			person = c;
			view = ((MonoBehaviourPun)c).photonView.ViewID;
			agent = a.id;
			serial = a.serial;
			epoch = run;
			if (!c.refs.ragdoll.partDict.TryGetValue((BodypartType)13, out var value) || !Object.op_Implicit((Object)(object)value.Rig))
			{
				throw new Exception("Left foot body missing");
			}
			foot = value.Rig;
			GameObject val = new GameObject("PF_Crocodile_LegAnchor");
			val.layer = 2;
			anchor = val.AddComponent<Rigidbody>();
			anchor.isKinematic = true;
			anchor.useGravity = false;
			anchor.position = foot.position;
			anchor.interpolation = (RigidbodyInterpolation)1;
			originalIterations = foot.solverIterations;
			originalVelocity = foot.solverVelocityIterations;
			foot.solverIterations = Math.Max(16, originalIterations);
			foot.solverVelocityIterations = Math.Max(12, originalVelocity);
			joint = ((Component)foot).gameObject.AddComponent<ConfigurableJoint>();
			((Joint)joint).connectedBody = anchor;
			((Joint)joint).autoConfigureConnectedAnchor = false;
			((Joint)joint).anchor = Vector3.zero;
			((Joint)joint).connectedAnchor = Vector3.zero;
			ConfigurableJoint obj = joint;
			ConfigurableJoint obj2 = joint;
			ConfigurableJoint obj3 = joint;
			ConfigurableJointMotion val2 = (ConfigurableJointMotion)0;
			obj3.zMotion = (ConfigurableJointMotion)0;
			obj.xMotion = (obj2.yMotion = val2);
			ConfigurableJoint obj4 = joint;
			ConfigurableJoint obj5 = joint;
			ConfigurableJoint obj6 = joint;
			val2 = (ConfigurableJointMotion)2;
			obj6.angularZMotion = (ConfigurableJointMotion)2;
			obj4.angularXMotion = (obj5.angularYMotion = val2);
			((Joint)joint).breakForce = float.PositiveInfinity;
			((Joint)joint).breakTorque = float.PositiveInfinity;
			((Joint)joint).enableCollision = false;
			((Joint)joint).enablePreprocessing = false;
			joint.projectionMode = (JointProjectionMode)0;
		}

		public void Tick(Vector3 mouth, float dt)
		{
			//IL_0083: 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_0090: Unknown result type (might be due to invalid IL or missing references)
			if (Valid)
			{
				if (Object.op_Implicit((Object)(object)person.refs.climbing) && person.data.isClimbingAnything)
				{
					person.refs.climbing.StopAnyClimbing();
				}
				person.refs.movement.CapFallDamage(0f, 0.3f);
				anchor.MovePosition(Vector3.MoveTowards(anchor.position, mouth, 12f * dt));
			}
		}

		public void Dispose()
		{
			if (Object.op_Implicit((Object)(object)joint))
			{
				Object.Destroy((Object)(object)joint);
			}
			if (Object.op_Implicit((Object)(object)anchor))
			{
				Object.Destroy((Object)(object)((Component)anchor).gameObject);
			}
			if (Object.op_Implicit((Object)(object)foot))
			{
				foot.solverIterations = originalIterations;
				foot.solverVelocityIterations = originalVelocity;
			}
			if (Object.op_Implicit((Object)(object)person) && person.refs != null && Object.op_Implicit((Object)(object)person.refs.movement))
			{
				person.refs.movement.CapFallDamage(0f, 1f);
			}
		}
	}
	[BepInPlugin("local.peak.poisonforest.crocodile", "Thunderfen Crocodiles", "1.0.0")]
	[BepInDependency("local.peak.poisonforest.solo", "0.6.0")]
	[BepInDependency("local.peak.poisonforest.pools", "0.2.0")]
	public sealed class CrocodilePlugin : BaseUnityPlugin
	{
		[Serializable]
		private sealed class Report
		{
			public string version = "1.0.0";

			public string utc;

			public string error;

			public string message;

			public string protocol;

			public string epoch;

			public bool ready;

			public bool active;

			public bool compatible;

			public bool host;

			public bool holdingLocalPlayer;

			public int nests;

			public int players;

			public int localCapturedBy = -1;

			public int temporaryBlockedCells;

			public int collisionBlocks;

			public string lastObstacle;

			public float normalWalkSpeed;

			public float normalRunningSpeed;

			public float nativeSprintMultiplier;

			public float postReleaseRecoveryRemaining;

			public float nativeFallSeconds;

			public float poolMovementMultiplier = 0.5f;

			public Rules rules;

			public int receivedSnapshots;

			public int acceptedSnapshots;

			public int rejectedSnapshots;

			public int publishedSnapshots;

			public int visualCount;

			public string snapshotSource;

			public string lastSnapshotRejection;

			public Agent[] crocodiles;
		}

		public const string Version = "1.0.0";

		public const string Id = "local.peak.poisonforest.crocodile";

		private const string Key = "PF_CState";

		private const string Proto = "PF_CProtocol";

		private const string Ack = "PF_CGrab";

		private int receivedSnapshots;

		private int acceptedSnapshots;

		private int rejectedSnapshots;

		private int publishedSnapshots;

		private string snapshotSource;

		private string lastSnapshotRejection;

		private string streamedRaw;

		private string lastTransition;

		private float nextRecovery;

		private int dataRevision = -1;

		private ObstacleMemory obstacles;

		private int collisionBlocks;

		private string lastObstacle;

		private NavGrid nav;

		private CreatureModel model;

		private Rules rules;

		private Transform terrain;

		private Flock flock;

		private CrocVisual[] visuals;

		private LegHold hold;

		private string protocol;

		private string error;

		private string lastRaw;

		private string folder;

		private string message = "Waiting for Poison Forest";

		private bool ready;

		private bool compatible;

		private bool wasMaster;

		private double lastTick;

		private float nextScan;

		private float nextPublish;

		private float nextReport;

		private readonly Random random = new Random();

		private readonly RaycastHit[] hits = (RaycastHit[])(object)new RaycastHit[96];

		private int bodyCount;

		private float walkSpeed;

		private float runSpeed;

		private float sprintMultiplier;

		private double recoveryUntil;

		private int recoveryView;

		private string recoveryEpoch;

		private readonly ReleaseReceipts releaseReceipts = new ReleaseReceipts();

		private bool Active => Object.op_Implicit((Object)(object)terrain) && ((Component)terrain).gameObject.activeInHierarchy;

		private static byte[] Resource(string name)
		{
			using Stream stream = typeof(CrocodilePlugin).Assembly.GetManifestResourceStream("PoisonForestCrocodile." + name);
			if (stream == null)
			{
				throw new Exception("Missing resource " + name);
			}
			using MemoryStream memoryStream = new MemoryStream();
			stream.CopyTo(memoryStream);
			return memoryStream.ToArray();
		}

		private static string Sha(byte[] b)
		{
			using SHA256 sHA = SHA256.Create();
			return BitConverter.ToString(sHA.ComputeHash(b)).Replace("-", "");
		}

		private void Awake()
		{
			folder = Path.Combine(Application.persistentDataPath, "PoisonForestCrocodile");
			Directory.CreateDirectory(folder);
			try
			{
				byte[] array = GeneratedData.Read("crocodile-navigation.bin");
				byte[] array2 = GeneratedData.Read("crocodile-model.bin");
				nav = NavGrid.Read(array);
				obstacles = new ObstacleMemory(nav);
				model = CreatureModel.FromBinary(array2);
				((BaseUnityPlugin)this).Logger.LogInfo((object)("Crocodile binary model decoded: " + model.parts.Length + " parts / " + model.parts.Sum((ModelPart part) => part.vertices.Length) + " vertices"));
				string path = Path.Combine(Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location), "PoisonForestCrocodile.settings.json");
				rules = (File.Exists(path) ? JsonUtility.FromJson<Rules>(File.ReadAllText(path)) : new Rules());
				if (rules != null && rules.nestCount < 5)
				{
					rules.nestCount = 5;
				}
				if (rules != null && rules.releaseKnockdownSeconds == 0f)
				{
					rules.releaseKnockdownSeconds = 5f;
				}
				if (rules != null && rules.biteLungeDistance == 0f)
				{
					rules.biteLungeDistance = 2.8f;
					rules.biteLungeSeconds = 0.34f;
					rules.biteHopHeight = 0.6f;
					rules.biteRecovery = 0.6f;
				}
				if (rules == null || rules.nestCount < 4 || rules.nestCount > 12 || rules.wanderRadius < 3f || rules.detectRadius < 2f || rules.chaseRadius < rules.wanderRadius || rules.chaseRadius > 70f || rules.biteDistance < 1f || rules.biteDistance > 3f || (double)rules.biteWindup < 0.05 || rules.cooldown < 1f || rules.maxDragSeconds < 10f || float.IsNaN(rules.releaseKnockdownSeconds) || rules.releaseKnockdownSeconds < 1f || rules.releaseKnockdownSeconds > 15f || !FiniteRange(rules.biteLungeDistance, 0.5f, 5f) || !FiniteRange(rules.biteLungeSeconds, 0.15f, 1f) || !FiniteRange(rules.biteHopHeight, 0.1f, 1.5f) || !FiniteRange(rules.biteRecovery, 0.1f, 3f))
				{
					throw new Exception("Invalid crocodile settings");
				}
				protocol = "0.4.4:" + Sha(array).Substring(0, 12) + ":" + Sha(array2).Substring(0, 12) + ":" + Sha(Encoding.UTF8.GetBytes(JsonUtility.ToJson((object)rules))).Substring(0, 12);
				SharedWorld.Message += OnShared;
				ready = true;
				((BaseUnityPlugin)this).Logger.LogInfo((object)"Crocodiles ready; one crocodile per generated nest (8–10 flat plus optional mountain nests), native running pace, foot tether, 5s native release knockdown, roaming 20s cooldown; no new hotkeys.");
			}
			catch (Exception e)
			{
				Fail(e);
			}
		}

		private static bool Eligible(Character c)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			int result;
			if (Object.op_Implicit((Object)(object)c))
			{
				Scene scene = ((Component)c).gameObject.scene;
				if (((Scene)(ref scene)).IsValid() && Object.op_Implicit((Object)(object)((MonoBehaviourPun)c).photonView) && ((MonoBehaviourPun)c).photonView.Owner != null && !((MonoBehaviourPun)c).photonView.Owner.IsInactive && Object.op_Implicit((Object)(object)c.data) && !c.data.dead && c.refs != null && Object.op_Implicit((Object)(object)c.refs.ragdoll))
				{
					result = (Object.op_Implicit((Object)(object)c.refs.movement) ? 1 : 0);
					goto IL_0093;
				}
			}
			result = 0;
			goto IL_0093;
			IL_0093:
			return (byte)result != 0;
		}

		private static P Point(Vector3 p)
		{
			//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_000c: Unknown result type (might be due to invalid IL or missing references)
			return new P(p.x, p.y, p.z);
		}

		private static Vector3 Vec(P p)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			return new Vector3(p.x, p.y, p.z);
		}

		private static Vector3 Feet(Character c)
		{
			//IL_006c: 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_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: 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_0052: 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)
			Bodypart value;
			bool flag = c.refs.ragdoll.partDict.TryGetValue((BodypartType)13, out value);
			Bodypart value2;
			bool flag2 = c.refs.ragdoll.partDict.TryGetValue((BodypartType)16, out value2);
			return (flag && flag2) ? ((value.transform.position + value2.transform.position) * 0.5f) : (flag ? value.transform.position : (c.Center - Vector3.up * 0.8f));
		}

		public static float WalkingSpeed(float force, float drag, float step)
		{
			return MovementPace.Normal(force, drag, step);
		}

		private static bool FiniteRange(float x, float lo, float hi)
		{
			return !float.IsNaN(x) && !float.IsInfinity(x) && x >= lo && x <= hi;
		}

		private Transform FindTerrain()
		{
			//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)
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Expected O, but got Unknown
			Scene sceneByName = SceneManager.GetSceneByName("WilIsland");
			if (!((Scene)(ref sceneByName)).IsValid() || !((Scene)(ref sceneByName)).isLoaded)
			{
				return null;
			}
			GameObject val = ((IEnumerable<GameObject>)((Scene)(ref sceneByName)).GetRootGameObjects()).FirstOrDefault((Func<GameObject, bool>)((GameObject g) => ((Object)g).name == "Map"));
			if (!Object.op_Implicit((Object)(object)val))
			{
				return null;
			}
			Transform val2 = val.transform.Find("Global");
			if (!Object.op_Implicit((Object)(object)val2))
			{
				return null;
			}
			foreach (Transform item in val2)
			{
				Transform val3 = item;
				if (((Object)val3).name.Contains("first-ridge"))
				{
					Transform val4 = ((IEnumerable<Transform>)((Component)val3).GetComponentsInChildren<Transform>(true)).FirstOrDefault((Func<Transform, bool>)((Transform x) => ((Object)x).name == "PF_HybridTerrain" && Object.op_Implicit((Object)(object)x.parent) && ((Object)x.parent).name == "RootsTerrain"));
					if (Object.op_Implicit((Object)(object)val4))
					{
						return val4;
					}
				}
			}
			return null;
		}

		private void Update()
		{
			//IL_017f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0184: Unknown result type (might be due to invalid IL or missing references)
			//IL_0195: Expected O, but got Unknown
			//IL_019d: Expected O, but got Unknown
			//IL_01e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0227: Unknown result type (might be due to invalid IL or missing references)
			//IL_022c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0238: Expected O, but got Unknown
			//IL_0240: Expected O, but got Unknown
			if (!ready)
			{
				return;
			}
			try
			{
				if (RunData.Pending || !SharedWorld.Ready)
				{
					ReleaseLocal();
					return;
				}
				if (dataRevision != RunData.Revision)
				{
					Reset();
					byte[] array = GeneratedData.Read("crocodile-navigation.bin");
					byte[] array2 = GeneratedData.Read("crocodile-model.bin");
					nav = NavGrid.Read(array);
					obstacles = new ObstacleMemory(nav);
					model = CreatureModel.FromBinary(array2);
					protocol = "0.4.4:" + Sha(array).Substring(0, 12) + ":" + Sha(array2).Substring(0, 12) + ":" + Sha(Encoding.UTF8.GetBytes(JsonUtility.ToJson((object)rules))).Substring(0, 12);
					dataRevision = RunData.Revision;
					nextScan = 0f;
				}
				if (!PhotonNetwork.InRoom)
				{
					Reset();
					ReportNow();
					return;
				}
				if (!(PhotonNetwork.LocalPlayer.CustomProperties[(object)"PF_CProtocol"] is string text) || text != protocol)
				{
					Player localPlayer = PhotonNetwork.LocalPlayer;
					Hashtable val = new Hashtable();
					((Dictionary<object, object>)val).Add((object)"PF_CProtocol", (object)protocol);
					localPlayer.SetCustomProperties(val, (Hashtable)null, (WebFlags)null);
				}
				compatible = PhotonNetwork.PlayerList.Where((Player c) => !c.IsInactive).All((Player c) => c.CustomProperties[(object)"PF_CProtocol"] is string text2 && text2 == protocol);
				Scene sceneByName = SceneManager.GetSceneByName("WilIsland");
				if (!((Scene)(ref sceneByName)).isLoaded)
				{
					if (PhotonNetwork.IsMasterClient && ((RoomInfo)PhotonNetwork.CurrentRoom).CustomProperties[(object)"PF_CState"] != null)
					{
						Room currentRoom = PhotonNetwork.CurrentRoom;
						Hashtable val2 = new Hashtable();
						((Dictionary<object, object>)val2).Add((object)"PF_CState", (object)null);
						currentRoom.SetCustomProperties(val2, (Hashtable)null, (WebFlags)null);
					}
					Reset();
					ReportNow();
					return;
				}
				if (Time.unscaledTime >= nextScan)
				{
					nextScan = Time.unscaledTime + 1f;
					Transform val3 = FindTerrain();
					if ((Object)(object)terrain != (Object)(object)val3 || (!Object.op_Implicit((Object)(object)val3) && visuals != null))
					{
						ClearVisuals();
						flock = null;
						lastRaw = null;
						terrain = val3;
					}
				}
				if (!Active || !compatible)
				{
					PauseVisuals();
					message = ((!Active) ? "Waiting for custom wetland terrain" : "Crocodiles paused: every player needs the same trial");
					lastTick = PhotonNetwork.Time;
					ReportNow();
					return;
				}
				bool isMasterClient = PhotonNetwork.IsMasterClient;
				if (!isMasterClient || !wasMaster || flock == null)
				{
					ReadShared();
				}
				if (isMasterClient && !wasMaster && flock != null)
				{
					Agent[] agents = flock.agents;
					foreach (Agent agent in agents)
					{
						if (agent.mode == Mode.Drag || agent.mode == Mode.Windup || agent.mode == Mode.Lunge)
						{
							Brain.Release(agent, PhotonNetwork.Time, rules, "host changed");
						}
					}
					Publish();
				}
				wasMaster = isMasterClient;
				if (isMasterClient && flock == null)
				{
					P[] source = nav.nests.OrderBy((P _) => random.Next()).Take(PopulationRule.Choose(random, nav.nests.Length, rules.nestCount)).ToArray();
					flock = new Flock
					{
						epoch = (SharedWorld.Online ? SharedWorld.Epoch : Guid.NewGuid().ToString("N")),
						protocol = protocol,
						owner = PhotonNetwork.LocalPlayer.ActorNumber,
						at = PhotonNetwork.Time,
						agents = source.Select((P n, int i) => Brain.Spawn(i, n)).ToArray()
					};
					lastTick = PhotonNetwork.Time;
					Publish();
					((BaseUnityPlugin)this).Logger.LogInfo((object)("Spawned " + flock.agents.Length + " crocodiles at interior pool nests"));
				}
				if (flock != null)
				{
					if (isMasterClient && PhotonNetwork.Time - lastTick >= 0.05)
					{
						float dt = Mathf.Clamp((float)(PhotonNetwork.Time - lastTick), 0f, 0.15f);
						lastTick = PhotonNetwork.Time;
						HostTick(dt);
					}
					if (isMasterClient && Time.unscaledTime >= nextPublish)
					{
						nextPublish = Time.unscaledTime + (flock.agents.Any((Agent a) => a.mode == Mode.Windup || a.mode == Mode.Lunge) ? 0.05f : 0.15f);
						Publish();
					}
					EnsureVisuals();
					if (visuals != null)
					{
						for (int num2 = 0; num2 < visuals.Length; num2++)
						{
							if (visuals[num2].SetVisible(visible: true))
							{
								visuals[num2].Tick(flock.agents[num2], nav, Time.deltaTime, PhotonNetwork.Time);
							}
						}
					}
					UpdateHold();
					ApplyReleaseEffects();
					message = "Crocodiles patrol the pools";
				}
				else
				{
					ReleaseLocal();
					message = "Waiting for host crocodiles";
				}
				ReportNow();
			}
			catch (Exception e)
			{
				Fail(e);
			}
		}

		private List<Person> People()
		{
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			HashSet<int> hashSet = new HashSet<int>(from a in flock.agents
				where a.mode == Mode.Drag
				select a.target);
			List<Person> list = new List<Person>();
			foreach (Character allCharacter in Character.AllCharacters)
			{
				if (Eligible(allCharacter))
				{
					P p = Point(terrain.InverseTransformPoint(Feet(allCharacter)));
					if (nav.Index(p) >= 0 && nav.Snap(p) >= 0)
					{
						list.Add(new Person
						{
							id = ((MonoBehaviourPun)allCharacter).photonView.ViewID,
							pos = p,
							speed = MovementPace.Normal(allCharacter.refs.movement.movementForce, allCharacter.refs.movement.drag, Time.fixedDeltaTime, allCharacter.refs.movement.sprintMultiplier),
							captured = hashSet.Contains(((MonoBehaviourPun)allCharacter).photonView.ViewID)
						});
					}
				}
			}
			bodyCount = list.Count;
			runSpeed = ((list.Count > 0) ? list[0].speed : 0f);
			Character localCharacter = Character.localCharacter;
			if (Eligible(localCharacter))
			{
				CharacterMovement movement = localCharacter.refs.movement;
				walkSpeed = WalkingSpeed(movement.movementForce, movement.drag, Time.fixedDeltaTime);
				sprintMultiplier = movement.sprintMultiplier;
			}
			return list;
		}

		private void HostTick(float dt)
		{
			obstacles.Expire(PhotonNetwork.Time);
			List<Person> list = People();
			Agent[] agents = flock.agents;
			foreach (Agent a in agents)
			{
				Mode mode = a.mode;
				int serial = a.serial;
				Brain.Tick(a, list, nav, rules, PhotonNetwork.Time, dt, random, Clear, (int id) => Attached(id, a));
				if (mode != a.mode)
				{
					nextPublish = 0f;
				}
				if (mode != a.mode || serial != a.serial)
				{
					((BaseUnityPlugin)this).Logger.LogInfo((object)("Croc " + a.id + " " + mode.ToString() + " -> " + a.mode.ToString() + " target=" + a.target + " " + a.reason));
				}
				foreach (Person p in list)
				{
					p.captured = flock.agents.Any((Agent c) => c.mode == Mode.Drag && c.target == p.id);
				}
			}
			int[] array = Brain.DropClaimedTargets(flock.agents);
			foreach (int num2 in array)
			{
				((BaseUnityPlugin)this).Logger.LogInfo((object)("Croc " + num2 + " dropped target: player already grabbed by another crocodile"));
			}
		}

		private bool Attached(int view, Agent a)
		{
			Character val = ((IEnumerable<Character>)Character.AllCharacters).FirstOrDefault((Func<Character, bool>)((Character x) => Eligible(x) && ((MonoBehaviourPun)x).photonView.ViewID == view));
			return Object.op_Implicit((Object)(object)val) && ((MonoBehaviourPun)val).photonView.Owner.CustomProperties[(object)"PF_CGrab"] is string text && text == flock.epoch + ":" + a.id + ":" + a.serial;
		}

		private bool Clear(P from, P to)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_004e: 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_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0113: Unknown result type (might be due to invalid IL or missing references)
			Vector3 val = terrain.TransformPoint(Vec(from) + Vector3.up * 0.75f);
			Vector3 val2 = terrain.TransformPoint(Vec(to) + Vector3.up * 0.75f);
			Vector3 val3 = val2 - val;
			float magnitude = ((Vector3)(ref val3)).magnitude;
			if ((double)magnitude < 0.002)
			{
				return true;
			}
			int num = Physics.SphereCastNonAlloc(val, 0.29f, val3 / magnitude, hits, magnitude, -5, (QueryTriggerInteraction)1);
			for (int i = 0; i < num; i++)
			{
				Collider collider = ((RaycastHit)(ref hits[i])).collider;
				if (Object.op_Implicit((Object)(object)collider) && !collider.isTrigger && !Object.op_Implicit((Object)(object)((Component)collider).GetComponentInParent<Bodypart>()) && !Object.op_Implicit((Object)(object)((Component)collider).GetComponentInParent<Character>()) && !Object.op_Implicit((Object)(object)((Component)collider).GetComponentInParent<Item>()))
				{
					P contact = Point(terrain.InverseTransformPoint(((RaycastHit)(ref hits[i])).point));
					collisionBlocks++;
					lastObstacle = ((Object)collider).name + " at " + contact.x.ToString("F1") + "," + contact.y.ToString("F1") + "," + contact.z.ToString("F1");
					obstacles.Mark(contact, from, PhotonNetwork.Time);
					return false;
				}
			}
			return true;
		}

		private void ReadShared()
		{
			ReadCandidate(streamedRaw, "event");
			ReadCandidate(((RoomInfo)PhotonNetwork.CurrentRoom).CustomProperties[(object)"PF_CState"] as string, "room");
		}

		private void ReadCandidate(string raw, string source)
		{
			if (string.IsNullOrEmpty(raw) || raw == lastRaw)
			{
				return;
			}
			string rejection;
			Flock flock = CrocodileSnapshot.Candidate(raw, this.flock, protocol, SharedWorld.Online ? SharedWorld.Epoch : null, PhotonNetwork.MasterClient.ActorNumber, nav, out rejection);
			if (rejection != null)
			{
				RejectSnapshot(source + ": " + rejection);
			}
			else if (flock != null)
			{
				if (this.flock != null && this.flock.epoch != flock.epoch)
				{
					ClearVisuals();
				}
				this.flock = flock;
				lastRaw = raw;
				snapshotSource = source;
				acceptedSnapshots++;
				lastSnapshotRejection = "";
			}
		}

		private void RejectSnapshot(string reason)
		{
			if (!(lastSnapshotRejection == reason))
			{
				lastSnapshotRejection = reason;
				rejectedSnapshots++;
				((BaseUnityPlugin)this).Logger.LogWarning((object)("Crocodile snapshot rejected: " + reason));
			}
		}

		private void Publish()
		{
			//IL_00e4: 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_00f5: Expected O, but got Unknown
			//IL_00fd: Expected O, but got Unknown
			flock.owner = PhotonNetwork.LocalPlayer.ActorNumber;
			flock.at = PhotonNetwork.Time;
			byte[] array = CrocodileSnapshot.Encode(flock);
			string value = CrocodileSnapshot.Room(array);
			string text = string.Join("|", flock.agents.Select((Agent a) => a.mode.ToString() + ":" + a.target + ":" + a.serial + ":" + a.releaseSerial));
			bool flag = text != lastTransition;
			lastTransition = text;
			if (SharedWorld.Online)
			{
				SharedWorld.Emit("crocodiles", new object[1] { array }, flag);
			}
			if (!SharedWorld.Online || flag || Time.unscaledTime >= nextRecovery)
			{
				nextRecovery = Time.unscaledTime + 2f;
				Room currentRoom = PhotonNetwork.CurrentRoom;
				Hashtable val = new Hashtable();
				((Dictionary<object, object>)val).Add((object)"PF_CState", (object)value);
				currentRoom.SetCustomProperties(val, (Hashtable)null, (WebFlags)null);
			}
			lastRaw = value;
			publishedSnapshots++;
			snapshotSource = "host";
		}

		private void OnShared(string kind, string id, object[] data)
		{
			if (!(kind != "crocodiles"))
			{
				if (data == null || data.Length != 1 || !(data[0] is byte[] array) || array.Length > 32768)
				{
					RejectSnapshot("event: invalid payload");
					return;
				}
				receivedSnapshots++;
				streamedRaw = CrocodileSnapshot.Room(array);
			}
		}

		private void PauseVisuals()
		{
			if (!Object.op_Implicit((Object)(object)terrain))
			{
				ClearVisuals();
				return;
			}
			ReleaseLocal();
			if (visuals != null)
			{
				CrocVisual[] array = visuals;
				for (int i = 0; i < array.Length; i++)
				{
					array[i]?.SetVisible(visible: false);
				}
			}
		}

		private void EnsureVisuals()
		{
			if (visuals != null)
			{
				if (visuals.All((CrocVisual v) => v?.Live ?? false))
				{
					return;
				}
				ClearVisuals();
			}
			Shader shader = Shader.Find("PoisonForest/TwistedTreeLit");
			if (!Object.op_Implicit((Object)(object)shader))
			{
				shader = ((IEnumerable<Shader>)Resources.FindObjectsOfTypeAll<Shader>()).FirstOrDefault((Func<Shader, bool>)((Shader s) => ((Object)s).name == "PoisonForest/TwistedTreeLit"));
			}
			if (!Object.op_Implicit((Object)(object)shader))
			{
				throw new Exception("Authored tree shader missing; load the current Poison Forest bundle");
			}
			Material val = ((IEnumerable<Material>)Resources.FindObjectsOfTypeAll<Material>()).FirstOrDefault((Func<Material, bool>)((Material m) => (Object)(object)m.shader == (Object)(object)shader && m.HasProperty("_NoiseTex")));
			Texture texture = (Object.op_Implicit((Object)(object)val) ? val.GetTexture("_NoiseTex") : null);
			visuals = flock.agents.Select((Agent a) => new CrocVisual(terrain, a.id, model, shader, texture)).ToArray();
		}

		private void UpdateHold()
		{
			//IL_00da: 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_00e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
			Character c = Character.localCharacter;
			Agent agent = (Eligible(c) ? flock.agents.FirstOrDefault((Agent x) => x.mode == Mode.Drag && x.target == ((MonoBehaviourPun)c).photonView.ViewID) : null);
			if (agent == null)
			{
				ReleaseLocal();
				return;
			}
			if (hold != null && (!hold.Valid || hold.agent != agent.id || hold.serial != agent.serial || hold.epoch != flock.epoch))
			{
				ReleaseLocal();
			}
			if (hold == null)
			{
				Vector3 val = terrain.InverseTransformPoint(Feet(c));
				if (!(Vector3.Distance(val, Vec(Brain.Mouth(agent))) > 3.3f))
				{
					hold = new LegHold(c, agent, flock.epoch);
					SetAck(flock.epoch + ":" + agent.id + ":" + agent.serial);
					((BaseUnityPlugin)this).Logger.LogInfo((object)("Local leg caught by crocodile " + agent.id + "; movement/jump inputs remain enabled"));
				}
			}
		}

		private void ApplyReleaseEffects()
		{
			Character localCharacter = Character.localCharacter;
			if (!Eligible(localCharacter))
			{
				return;
			}
			Agent[] agents = flock.agents;
			foreach (Agent agent in agents)
			{
				if (releaseReceipts.Take(flock.epoch, agent, ((MonoBehaviourPun)localCharacter).photonView.ViewID, PhotonNetwork.Time, rules.releaseKnockdownSeconds, out var remaining))
				{
					recoveryUntil = PhotonNetwork.Time + (double)remaining;
					recoveryView = ((MonoBehaviourPun)localCharacter).photonView.ViewID;
					recoveryEpoch = flock.epoch;
					((MonoBehaviourPun)localCharacter).photonView.RPC("RPCA_Fall", (RpcTarget)0, new object[2] { remaining, 0f });
					localCharacter.refs.movement.CapFallDamage(0f, remaining + 0.5f);
					((BaseUnityPlugin)this).Logger.LogInfo((object)("Croc " + agent.id + " nest release: native knockdown " + remaining.ToString("F2") + "s, receipt=" + agent.releaseSerial));
				}
			}
		}

		private void MaintainRecovery()
		{
			double num = recoveryUntil - PhotonNetwork.Time;
			if (!(num <= 0.0))
			{
				Character localCharacter = Character.localCharacter;
				if (!ready || !Active || !compatible || flock == null || flock.epoch != recoveryEpoch || !Eligible(localCharacter) || ((MonoBehaviourPun)localCharacter).photonView.ViewID != recoveryView)
				{
					recoveryUntil = 0.0;
				}
				else
				{
					localCharacter.data.fallSeconds = Mathf.Max(localCharacter.data.fallSeconds, (float)num);
				}
			}
		}

		private void FixedUpdate()
		{
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				MaintainRecovery();
				if (hold == null)
				{
					return;
				}
				if (!ready || !Active || !compatible || flock == null || !hold.Valid || !PhotonNetwork.InRoom || PhotonNetwork.Time - flock.at > 2.0)
				{
					ReleaseLocal();
					return;
				}
				Agent agent = flock.agents.FirstOrDefault((Agent x) => x.id == hold.agent && x.serial == hold.serial && x.mode == Mode.Drag);
				if (agent == null)
				{
					ReleaseLocal();
				}
				else
				{
					hold.Tick(terrain.TransformPoint(Vec(Brain.Mouth(agent))), Time.fixedDeltaTime);
				}
			}
			catch (Exception e)
			{
				Fail(e);
			}
		}

		private void SetAck(string value)
		{
			//IL_000f: 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_0020: Expected O, but got Unknown
			//IL_0028: Expected O, but got Unknown
			if (PhotonNetwork.InRoom)
			{
				Player localPlayer = PhotonNetwork.LocalPlayer;
				Hashtable val = new Hashtable();
				((Dictionary<object, object>)val).Add((object)"PF_CGrab", (object)value);
				localPlayer.SetCustomProperties(val, (Hashtable)null, (WebFlags)null);
			}
		}

		private void ReleaseLocal()
		{
			if (hold != null)
			{
				hold.Dispose();
				hold = null;
				((BaseUnityPlugin)this).Logger.LogInfo((object)"Local leg released");
			}
			if (PhotonNetwork.InRoom && PhotonNetwork.LocalPlayer.CustomProperties[(object)"PF_CGrab"] != null)
			{
				SetAck(null);
			}
		}

		private void ClearVisuals()
		{
			ReleaseLocal();
			if (visuals != null)
			{
				CrocVisual[] array = visuals;
				for (int i = 0; i < array.Length; i++)
				{
					array[i]?.Dispose();
				}
			}
			visuals = null;
		}

		private void Reset()
		{
			recoveryUntil = 0.0;
			ClearVisuals();
			terrain = null;
			flock = null;
			lastRaw = null;
			streamedRaw = null;
			lastTransition = null;
			wasMaster = false;
			bodyCount = 0;
			message = "Waiting for Poison Forest";
		}

		private void Fail(Exception e)
		{
			error = e.ToString();
			ready = false;
			ClearVisuals();
			((BaseUnityPlugin)this).Logger.LogError((object)error);
			ReportNow(force: true);
		}

		private void ReportNow(bool force = false)
		{
			if (!RuntimeDiagnostics.PeriodicSnapshots || (!force && Time.unscaledTime < nextReport))
			{
				return;
			}
			nextReport = Time.unscaledTime + 2f;
			try
			{
				Report obj = new Report
				{
					utc = DateTime.UtcNow.ToString("O"),
					error = error,
					message = message,
					protocol = protocol,
					epoch = flock?.epoch,
					ready = ready,
					active = Active,
					compatible = compatible,
					host = PhotonNetwork.IsMasterClient,
					holdingLocalPlayer = (hold != null)
				};
				Flock obj2 = flock;
				obj.nests = ((obj2 != null) ? obj2.agents.Length : 0);
				obj.players = bodyCount;
				obj.normalWalkSpeed = walkSpeed;
				obj.normalRunningSpeed = runSpeed;
				obj.nativeSprintMultiplier = sprintMultiplier;
				obj.postReleaseRecoveryRemaining = (float)Math.Max(0.0, recoveryUntil - PhotonNetwork.Time);
				obj.nativeFallSeconds = (Eligible(Character.localCharacter) ? Character.localCharacter.data.fallSeconds : 0f);
				obj.localCapturedBy = hold?.agent ?? (-1);
				obj.temporaryBlockedCells = obstacles?.Count ?? 0;
				obj.collisionBlocks = collisionBlocks;
				obj.lastObstacle = lastObstacle;
				obj.receivedSnapshots = receivedSnapshots;
				obj.acceptedSnapshots = acceptedSnapshots;
				obj.rejectedSnapshots = rejectedSnapshots;
				obj.publishedSnapshots = publishedSnapshots;
				CrocVisual[] array = visuals;
				obj.visualCount = ((array != null) ? array.Length : 0);
				obj.snapshotSource = snapshotSource;
				obj.lastSnapshotRejection = lastSnapshotRejection;
				obj.rules = rules;
				obj.crocodiles = flock?.agents;
				string contents = JsonUtility.ToJson((object)obj, true);
				File.WriteAllText(Path.Combine(folder, "crocodile-runtime-state.json"), contents);
				if (Active)
				{
					File.WriteAllText(Path.Combine(folder, "crocodile-last-active.json"), contents);
				}
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)ex.Message);
			}
		}

		private void OnDestroy()
		{
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Expected O, but got Unknown
			//IL_006b: Expected O, but got Unknown
			SharedWorld.Message -= OnShared;
			ready = false;
			ClearVisuals();
			if (PhotonNetwork.InRoom && PhotonNetwork.IsMasterClient && ((RoomInfo)PhotonNetwork.CurrentRoom).CustomProperties[(object)"PF_CState"] != null)
			{
				Room currentRoom = PhotonNetwork.CurrentRoom;
				Hashtable val = new Hashtable();
				((Dictionary<object, object>)val).Add((object)"PF_CState", (object)null);
				currentRoom.SetCustomProperties(val, (Hashtable)null, (WebFlags)null);
			}
		}
	}
	public sealed class MeshData
	{
		public string name;

		public float[] positions;

		public float[] normals;

		public float[] colors;

		public int[] triangles;
	}
	public static class ModelData
	{
		private static float[] Floats(BinaryReader reader, int count)
		{
			float[] array = new float[count];
			for (int i = 0; i < count; i++)
			{
				array[i] = reader.ReadSingle();
				if (float.IsNaN(array[i]) || float.IsInfinity(array[i]))
				{
					throw new InvalidDataException("Non-finite model coordinate");
				}
			}
			return array;
		}

		public static MeshData[] Read(byte[] bytes)
		{
			if (bytes == null || bytes.Length > 2000000)
			{
				throw new InvalidDataException("Model byte size");
			}
			using BinaryReader binaryReader = new BinaryReader(new MemoryStream(bytes), Encoding.UTF8);
			if (new string(binaryReader.ReadChars(4)) != "PFCM")
			{
				throw new InvalidDataException("Model signature");
			}
			int num = binaryReader.ReadInt32();
			if (num != 42)
			{
				throw new InvalidDataException("Expected 42 model parts, received " + num);
			}
			MeshData[] array = new MeshData[num];
			HashSet<string> hashSet = new HashSet<string>();
			int num2 = 0;
			int num3 = 0;
			for (int i = 0; i < num; i++)
			{
				int num4 = binaryReader.ReadInt32();
				if (num4 < 1 || num4 > 64)
				{
					throw new InvalidDataException("Part name length");
				}
				byte[] array2 = binaryReader.ReadBytes(num4);
				if (array2.Length != num4)
				{
					throw new EndOfStreamException();
				}
				string text = Encoding.UTF8.GetString(array2);
				if (!hashSet.Add(text))
				{
					throw new InvalidDataException("Duplicate model part");
				}
				int num5 = binaryReader.ReadInt32();
				int num6 = binaryReader.ReadInt32();
				if (num5 < 3 || num5 > 10000 || num6 < 3 || num6 > 60000 || num6 % 3 != 0)
				{
					throw new InvalidDataException("Model mesh size");
				}
				num2 += num5;
				num3 += num6;
				MeshData meshData = new MeshData();
				meshData.name = text;
				meshData.positions = Floats(binaryReader, num5 * 3);
				meshData.normals = Floats(binaryReader, num5 * 3);
				meshData.colors = Floats(binaryReader, num5 * 4);
				meshData.triangles = new int[num6];
				MeshData meshData2 = meshData;
				for (int j = 0; j < num6; j++)
				{
					meshData2.triangles[j] = binaryReader.ReadInt32();
					if (meshData2.triangles[j] < 0 || meshData2.triangles[j] >= num5)
					{
						throw new InvalidDataException("Model index out of range");
					}
				}
				for (int k = 0; k < num5; k++)
				{
					float num7 = meshData2.normals[k * 3];
					float num8 = meshData2.normals[k * 3 + 1];
					float num9 = meshData2.normals[k * 3 + 2];
					float num10 = num7 * num7 + num8 * num8 + num9 * num9;
					if (num10 < 0.8f || num10 > 1.2f)
					{
						throw new InvalidDataException("Model normal length");
					}
				}
				array[i] = meshData2;
			}
			if (num2 != 3444 || num3 != 19080 || !hashSet.Contains("Tail") || !hashSet.Contains("LowerJaw") || binaryReader.BaseStream.Position != binaryReader.BaseStream.Length)
			{
				throw new InvalidDataException("Model totals or trailing bytes");
			}
			return array;
		}
	}
	[Serializable]
	public sealed class Flock
	{
		public string epoch;

		public string protocol;

		public int owner;

		public double at;

		public Agent[] agents;
	}
	public static class CrocodileSnapshot
	{
		public const int MaximumBytes = 32768;

		public const string Prefix = "PFC2:";

		private static readonly UTF8Encoding Utf8 = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true);

		private static void Text(BinaryWriter w, string s, int max)
		{
			byte[] bytes = Utf8.GetBytes(s ?? "");
			if (bytes.Length > max)
			{
				throw new InvalidDataException("Crocodile text length");
			}
			w.Write(bytes.Length);
			w.Write(bytes);
		}

		private static string Text(BinaryReader r, int max)
		{
			int num = r.ReadInt32();
			if (num < 0 || num > max || num > r.BaseStream.Length - r.BaseStream.Position)
			{
				throw new InvalidDataException("Crocodile text length");
			}
			return Utf8.GetString(r.ReadBytes(num));
		}

		private static bool Finite(double n)
		{
			return !double.IsNaN(n) && !double.IsInfinity(n);
		}

		private static void Point(BinaryWriter w, P p)
		{
			w.Write(p.x);
			w.Write(p.y);
			w.Write(p.z);
		}

		private static P Point(BinaryReader r)
		{
			return new P(r.ReadSingle(), r.ReadSingle(), r.ReadSingle());
		}

		private static bool Finite(P p)
		{
			return Finite(p.x) && Finite(p.y) && Finite(p.z);
		}

		public static void Validate(Flock f)
		{
			if (f == null || string.IsNullOrEmpty(f.epoch) || string.IsNullOrEmpty(f.protocol) || f.owner < 1 || !Finite(f.at) || f.agents == null || f.agents.Length < 4 || f.agents.Length > 12)
			{
				throw new InvalidDataException("Crocodile snapshot header");
			}
			for (int i = 0; i < f.agents.Length; i++)
			{
				Agent agent = f.agents[i];
				if (agent == null || agent.id != i || !Enum.IsDefined(typeof(Mode), agent.mode) || agent.serial < 0 || agent.releaseSerial < 0 || !Finite(agent.pos) || !Finite(agent.nest) || !Finite(agent.lungeFrom) || !Finite(agent.lungeEnd) || !Finite(agent.lastProgressPos) || !Finite(agent.yaw) || !Finite(agent.speed) || agent.speed < 0f || agent.speed > 15f || !Finite(agent.hop) || agent.hop < 0f || agent.hop > 3f || !Finite(agent.releasedAt) || !Finite(agent.lungeAt) || !Finite(agent.attackReadyAt) || !Finite(agent.until) || !Finite(agent.captureAt) || !Finite(agent.lastProgress) || !Finite(agent.cooldownUntil))
				{
					throw new InvalidDataException("Crocodile snapshot agent");
				}
			}
		}

		public static byte[] Encode(Flock f)
		{
			Validate(f);
			using MemoryStream memoryStream = new MemoryStream();
			using (BinaryWriter binaryWriter = new BinaryWriter(memoryStream, Utf8, leaveOpen: true))
			{
				binaryWriter.Write(843269712u);
				Text(binaryWriter, f.epoch, 128);
				Text(binaryWriter, f.protocol, 256);
				binaryWriter.Write(f.owner);
				binaryWriter.Write(f.at);
				binaryWriter.Write(f.agents.Length);
				Agent[] agents = f.agents;
				foreach (Agent agent in agents)
				{
					binaryWriter.Write(agent.id);
					binaryWriter.Write(agent.target);
					binaryWriter.Write(agent.serial);
					binaryWriter.Write(agent.releasedView);
					binaryWriter.Write(agent.releaseSerial);
					binaryWriter.Write(agent.releasedAtNest);
					binaryWriter.Write(agent.releasedAt);
					binaryWriter.Write((int)agent.mode);
					Point(binaryWriter, agent.pos);
					Point(binaryWriter, agent.nest);
					binaryWriter.Write(agent.yaw);
					binaryWriter.Write(agent.speed);
					binaryWriter.Write(agent.hop);
					Point(binaryWriter, agent.lungeFrom);
					Point(binaryWriter, agent.lungeEnd);
					binaryWriter.Write(agent.lungeAt);
					binaryWriter.Write(agent.attackReadyAt);
					binaryWriter.Write(agent.until);
					binaryWriter.Write(agent.captureAt);
					binaryWriter.Write(agent.lastProgress);
					binaryWriter.Write(agent.cooldownUntil);
					Point(binaryWriter, agent.lastProgressPos);
					Text(binaryWriter, agent.reason, 512);
				}
			}
			if (memoryStream.Length > 32768)
			{
				throw new InvalidDataException("Crocodile packet length");
			}
			return memoryStream.ToArray();
		}

		public static Flock Decode(byte[] bytes)
		{
			if (bytes == null || bytes.Length < 32 || bytes.Length > 32768)
			{
				throw new InvalidDataException("Crocodile packet length");
			}
			using BinaryReader binaryReader = new BinaryReader(new MemoryStream(bytes), Utf8);
			if (binaryReader.ReadUInt32() != 843269712)
			{
				throw new InvalidDataException("Crocodile packet signature");
			}
			Flock flock = new Flock
			{
				epoch = Text(binaryReader, 128),
				protocol = Text(binaryReader, 256),
				owner = binaryReader.ReadInt32(),
				at = binaryReader.ReadDouble()
			};
			int num = binaryReader.ReadInt32();
			if (num < 4 || num > 12)
			{
				throw new InvalidDataException("Crocodile population");
			}
			flock.agents = new Agent[num];
			for (int i = 0; i < num; i++)
			{
				flock.agents[i] = new Agent
				{
					id = binaryReader.ReadInt32(),
					target = binaryReader.ReadInt32(),
					serial = binaryReader.ReadInt32(),
					releasedView = binaryReader.ReadInt32(),
					releaseSerial = binaryReader.ReadInt32(),
					releasedAtNest = binaryReader.ReadBoolean(),
					releasedAt = binaryReader.ReadDouble(),
					mode = (Mode)binaryReader.ReadInt32(),
					pos = Point(binaryReader),
					nest = Point(binaryReader),
					yaw = binaryReader.ReadSingle(),
					speed = binaryReader.ReadSingle(),
					hop = binaryReader.ReadSingle(),
					lungeFrom = Point(binaryReader),
					lungeEnd = Point(binaryReader),
					lungeAt = binaryReader.ReadDouble(),
					attackReadyAt = binaryReader.ReadDouble(),
					until = binaryReader.ReadDouble(),
					captureAt = binaryReader.ReadDouble(),
					lastProgress = binaryReader.ReadDouble(),
					cooldownUntil = binaryReader.ReadDouble(),
					lastProgressPos = Point(binaryReader),
					reason = Text(binaryReader, 512)
				};
			}
			if (binaryReader.BaseStream.Position != binaryReader.BaseStream.Length)
			{
				throw new InvalidDataException("Trailing crocodile data");
			}
			Validate(flock);
			return flock;
		}

		public static string Room(byte[] bytes)
		{
			return "PFC2:" + Convert.ToBase64String(bytes);
		}

		public static byte[] Packet(string value)
		{
			if (value == null || !value.StartsWith("PFC2:", StringComparison.Ordinal) || value.Length > "PFC2:".Length + 43692)
			{
				throw new InvalidDataException("Crocodile room format");
			}
			return Convert.FromBase64String(value.Substring("PFC2:".Length));
		}

		public static Flock Candidate(string raw, Flock current, string protocol, string epoch, int master, NavGrid nav, out string rejection)
		{
			rejection = null;
			if (string.IsNullOrEmpty(raw))
			{
				return null;
			}
			try
			{
				Flock flock = Decode(Packet(raw));
				rejection = Rejection(flock, protocol, epoch ?? flock.epoch, master, nav);
				if (rejection != null)
				{
					return null;
				}
				if (current != null && current.epoch == flock.epoch && flock.at <= current.at)
				{
					return null;
				}
				return flock;
			}
			catch (Exception ex)
			{
				rejection = ex.Message;
				return null;
			}
		}

		public static string Rejection(Flock f, string protocol, string epoch, int master, NavGrid nav)
		{
			if (f.protocol != protocol)
			{
				return "protocol mismatch";
			}
			if (string.IsNullOrEmpty(epoch) || f.epoch != epoch)
			{
				return "world epoch mismatch";
			}
			if (f.owner != master)
			{
				return "snapshot owner mismatch";
			}
			Agent[] agents = f.agents;
			foreach (Agent agent in agents)
			{
				if (nav.Index(agent.pos) < 0 || nav.Index(agent.nest) < 0)
				{
					return "position outside navigation";
				}
			}
			return null;
		}
	}
}

plugins/ThunderfenElectrical/PoisonForestElectrical.dll

Decompiled a week ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Security.Cryptography;
using System.Text;
using BepInEx;
using ExitGames.Client.Photon;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Photon.Pun;
using Photon.Realtime;
using PoisonForestSolo;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyVersion("0.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace PoisonForest
{
	public sealed class ElectricalModel
	{
		public float Charge { get; private set; }

		public double Phase { get; private set; }

		public double LockRemaining { get; private set; }

		public bool Locked => LockRemaining > 0.0;

		public int EventCount { get; private set; }

		public static double Interval(float fraction, double multiplier = 2.0)
		{
			return multiplier * (10.0 - 9.0 * Math.Max(0.0, Math.Min(1.0, ((double)fraction * 100.0 - 1.0) / 99.0)));
		}

		public void Set(float value)
		{
			Charge = Math.Max(0f, Math.Min(1f, value));
			if (Charge == 0f)
			{
				Phase = 0.0;
			}
		}

		public void Reset()
		{
			Charge = 0f;
			Phase = 0.0;
			LockRemaining = 0.0;
			EventCount = 0;
		}

		public void ClearStiffness()
		{
			Phase = 0.0;
			LockRemaining = 0.0;
		}

		public bool Tick(double dt, bool held, float gainPerSecond, float decayPerSecond, float cap, bool canAct, double intervalMultiplier = 2.0, double lockDuration = 1.0)
		{
			if (dt < 0.0 || double.IsNaN(dt) || double.IsInfinity(dt))
			{
				throw new ArgumentOutOfRangeException("dt");
			}
			LockRemaining = Math.Max(0.0, LockRemaining - dt);
			Charge = (float)Math.Max(0.0, Math.Min(cap, (double)Charge + (double)((held ? gainPerSecond : 0f) - decayPerSecond) * dt));
			if (Charge <= 0f)
			{
				Phase = 0.0;
				return false;
			}
			if (!canAct)
			{
				Phase = 0.0;
				LockRemaining = 0.0;
				return false;
			}
			Phase += dt / Interval(Charge, intervalMultiplier);
			if (Phase < 1.0 || Locked)
			{
				return false;
			}
			Phase %= 1.0;
			LockRemaining = lockDuration;
			EventCount++;
			return true;
		}
	}
	[BepInDependency("local.peak.poisonforest.solo", "0.5.0")]
	[DefaultExecutionOrder(-10000)]
	[BepInPlugin("local.peak.poisonforest.electrical", "Thunderfen Electrical Status", "1.0.0")]
	public sealed class ElectricalTrial : BaseUnityPlugin
	{
		[Serializable]
		public sealed class Settings
		{
			public float decayPerSecond = 0.001f;

			public float chargeCap = 1f;

			public float stiffnessIntervalMultiplier = 2f;

			public float stiffnessDuration = 1f;

			public float joltVelocityChange = 2.5f;

			public float joltUpwardVelocityChange = 5f;
		}

		[Serializable]
		private sealed class State
		{
			public int staticAckSent;

			public int staticAckReceived;

			public int staticAckRejected;

			public int staticAckPropertyReads;

			public string lastAckRejection;

			public bool charged;

			public int chargedAuras;

			public int staticBurstVisuals;

			public int staticBurstVisualStarts;

			public int staticBurstContacts;

			public int staticBurstCommits;

			public int staticBurstPending;

			public int staticBurstClaims;

			public int staticBurstLaunches;

			public int staticBurstCancellations;

			public int staticBurstPreviews;

			public float lastBurstConsumed;

			public float lastBurstInjury;

			public float lastBurstForce;

			public string lastBurstToken;

			public string utc;

			public string version;

			public string message;

			public string error;

			public bool ready;

			public bool failed;

			public bool roomCompatible;

			public bool inRun;

			public bool stiff;

			public float charge;

			public float lockRemaining;

			public float configuredLockSeconds;

			public float configuredDecayPerSecond;

			public float configuredIntervalMultiplier;

			public float joltVelocityChange;

			public float joltUpwardVelocityChange;

			public float lastLockGameSeconds;

			public float lastLockWallSeconds;

			public int events;

			public int nativeStatusCount;

			public int movementGateCalls;

			public int maskedMoveSamples;

			public int diagnosticBarFilters;

			public int areaDosesReceived;

			public int areaDosesApplied;

			public int areaDoseDuplicates;

			public int areaDosesPending;

			public int stiffSparkEffects;

			public int stiffSparkStarts;
		}

		public const string Id = "local.peak.poisonforest.electrical";

		public const string Version = "1.0.0";

		public const int BarStatusId = 62001;

		private const string PropertyProtocol = "PF_ETrial";

		private const string PropertyCharge = "PF_ECharge";

		private const string PropertyView = "PF_EView";

		private static string Folder;

		public static ElectricalTrial Instance;

		public readonly ElectricalModel Model = new ElectricalModel();

		private Settings settings;

		private Harmony harmony;

		private readonly HashSet<StaminaBar> bars = new HashSet<StaminaBar>();

		private Sprite immunityShield;

		private Sprite bolt;

		private string protocol;

		private string message = "Initializing";

		private string lastFailure;

		private Character active;

		private float nextInit;

		private float nextPublish;

		private float nextReport;

		private static float nextBarRefresh;

		private bool ready;

		private bool failed;

		private bool compatible;

		private int sourceArrayCount;

		private readonly StiffnessVisuals stiffnessVisuals = new StiffnessVisuals();

		private int sparkSerial;

		private double sparkUntil;

		private readonly StaticElectricVisuals staticVisuals = new StaticElectricVisuals();

		private bool observingLock;

		private float lockStartedGame;

		private float lockStartedWall;

		private float lastLockGameSeconds;

		private float lastLockWallSeconds;

		private int lockGateCount;

		private int lockInputCount;

		private const string BurstLedgerKey = "TF_StaticBursts2";

		private const string BurstOwnerKey = "TF_StaticOwner3";

		private const byte BurstAckEvent = 181;

		private readonly Dictionary<string, double> nextAck = new Dictionary<string, double>();

		private readonly StaticBurstAcknowledgements burstAcks = new StaticBurstAcknowledgements();

		private int ackSent;

		private int ackReceived;

		private int ackRejected;

		private int ackPropertyReads;

		private string lastAckRejection;

		private readonly AreaChargeQueue areaDoses = new AreaChargeQueue();

		private readonly StaticBurstReceipts staticReceipts = new StaticBurstReceipts();

		private readonly ReceiptWindow burstVisualReceipts = new ReceiptWindow(256);

		private readonly StaticBodyContacts bodyContacts = new StaticBodyContacts();

		private StaticBurstLedger burstLedger;

		private bool wasBurstMaster;

		private double burstGrace;

		private float nextBurst;

		private string electricalEpoch;

		private int electricalView;

		private int burstContacts;

		private int burstCommits;

		private int burstClaims;

		private int burstLaunches;

		private int burstCancellations;

		private int burstPreviews;

		private float lastBurstConsumed;

		private float lastBurstInjury;

		private float lastBurstForce;

		private string lastBurstToken;

		private double stiffnessImmuneUntil;

		public static float NaturalDecayRate => (Object.op_Implicit((Object)(object)Instance) && Instance.settings != null) ? Instance.settings.decayPerSecond : 0f;

		public static double StiffnessImmunityRemaining => Object.op_Implicit((Object)(object)Instance) ? Math.Max(0.0, Instance.stiffnessImmuneUntil - PhotonNetwork.Time) : 0.0;

		private void LateUpdate()
		{
			if (ready && !failed)
			{
				stiffnessVisuals.Tick(StiffVisible);
				staticVisuals.Tick((Character c) => CanReceive(c) ? ChargeFor(c) : 0f, InRun() && compatible);
			}
		}

		private bool StiffVisible(Character c)
		{
			if (!InRun() || !compatible || !Object.op_Implicit((Object)(object)c) || !Object.op_Implicit((Object)(object)c.data) || c.data.dead || c.refs == null || !Object.op_Implicit((Object)(object)c.refs.ragdoll) || !Object.op_Implicit((Object)(object)((MonoBehaviourPun)c).photonView) || ((MonoBehaviourPun)c).photonView.Owner == null || ((MonoBehaviourPun)c).photonView.Owner.IsInactive)
			{
				return false;
			}
			if ((Object)(object)c == (Object)(object)active)
			{
				return Model.Locked;
			}
			Player owner = ((MonoBehaviourPun)c).photonView.Owner;
			return owner.CustomProperties[(object)"PF_ETrial"] as string == protocol && StiffnessSignal.Active(owner.CustomProperties[(object)"TF_EStiff"], protocol, ((MonoBehaviourPun)c).photonView.ViewID, PhotonNetwork.Time);
		}

		private void Awake()
		{
			//IL_01d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01dd: Expected O, but got Unknown
			Instance = this;
			Folder = Path.Combine(Application.persistentDataPath, "PoisonForestElectricalTrial");
			Directory.CreateDirectory(Folder);
			try
			{
				string path = Path.Combine(Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location), "PoisonForestElectrical.settings.json");
				settings = JsonUtility.FromJson<Settings>(File.ReadAllText(path));
				NativeCompatibility.CheckPatches(typeof(ElectricalTrial).Assembly);
				if (settings == null || !Finite(settings.decayPerSecond, 0f, 1f) || !Finite(settings.chargeCap, 0.01f, 1f) || !Finite(settings.stiffnessIntervalMultiplier, 0.1f, 10f) || !Finite(settings.stiffnessDuration, 0.1f, 10f) || !Finite(settings.joltVelocityChange, 0f, 3f) || !Finite(settings.joltUpwardVelocityChange, 0f, 10f))
				{
					throw new InvalidOperationException("Invalid electrical trial rates/cap.");
				}
				sourceArrayCount = Enum.GetNames(typeof(STATUSTYPE)).Length;
				if (sourceArrayCount != 15)
				{
					throw new InvalidOperationException("Native status enum changed; re-audit before using this build.");
				}
				string text = Sha(Encoding.UTF8.GetBytes(JsonUtility.ToJson((object)settings)));
				protocol = "0.4.2:" + text.Substring(0, 12);
				NativeCompatibility.Require(typeof(CharacterItems), "CancelClimbingSpike", typeof(void), Array.Empty<Type>());
				NativeStaticBurst.Check();
				bolt = CreateBolt();
				harmony = new Harmony("local.peak.poisonforest.electrical");
				harmony.PatchAll(typeof(ElectricalTrial).Assembly);
				SharedWorld.Message += ReceiveShared;
				PhotonNetwork.NetworkingClient.EventReceived += ReceiveBurstAck;
				ready = true;
				Log("started", "version=1.0.0 decay=" + settings.decayPerSecond.ToString("F4", CultureInfo.InvariantCulture) + " intervalMultiplier=" + settings.stiffnessIntervalMultiplier + " lockSeconds=" + settings.stiffnessDuration + " joltHorizontalDeltaV=" + settings.joltVelocityChange + " joltUpwardDeltaV=" + settings.joltUpwardVelocityChange + " protocol=" + protocol + "; native status arrays unchanged.");
			}
			catch (Exception error)
			{
				RemoveHooks();
				SharedWorld.MarkStartupFailure("Thunderfen electrical effects");
				Fail(error);
			}
		}

		private static bool Finite(float n, float min, float max)
		{
			return !float.IsNaN(n) && !float.IsInfinity(n) && n >= min && n <= max;
		}

		private static string Sha(byte[] data)
		{
			using SHA256 sHA = SHA256.Create();
			return BitConverter.ToString(sHA.ComputeHash(data)).Replace("-", "");
		}

		public static Character Owner(Component value)
		{
			return Object.op_Implicit((Object)(object)value) ? value.GetComponentInParent<Character>() : null;
		}

		public static bool IsLocked(Character c)
		{
			return Object.op_Implicit((Object)(object)Instance) && Instance.ready && !Instance.failed && Object.op_Implicit((Object)(object)c) && (Object)(object)c == (Object)(object)Character.localCharacter && Instance.Model.Locked;
		}

		private static bool InRun()
		{
			//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)
			Scene sceneByName = SceneManager.GetSceneByName("WilIsland");
			return ((Scene)(ref sceneByName)).isLoaded;
		}

		public static bool CanReceive(Character c)
		{
			ElectricalTrial instance = Instance;
			if (!Object.op_Implicit((Object)(object)instance) || !instance.ready || instance.failed || !instance.compatible || !Object.op_Implicit((Object)(object)c) || !Object.op_Implicit((Object)(object)((MonoBehaviourPun)c).photonView) || ((MonoBehaviourPun)c).photonView.Owner == null || ((MonoBehaviourPun)c).photonView.Owner.IsInactive || (Object)(object)c.data == (Object)null || c.data.dead)
			{
				return false;
			}
			if ((Object)(object)c == (Object)(object)Character.localCharacter)
			{
				return (Object)(object)c == (Object)(object)instance.active;
			}
			Player owner = ((MonoBehaviourPun)c).photonView.Owner;
			return owner.CustomProperties[(object)"PF_ETrial"] is string text && text == instance.protocol && owner.CustomProperties[(object)"PF_EView"] is int num && num == ((MonoBehaviourPun)c).photonView.ViewID;
		}

		public static float ChargeFor(Character c)
		{
			ElectricalTrial instance = Instance;
			if (!Object.op_Implicit((Object)(object)instance) || !instance.ready || instance.failed || !Object.op_Implicit((Object)(object)c) || !InRun())
			{
				return 0f;
			}
			if ((Object)(object)c == (Object)(object)Character.localCharacter)
			{
				return (instance.compatible && (Object)(object)c == (Object)(object)instance.active) ? instance.Model.Charge : 0f;
			}
			PhotonView photonView = ((MonoBehaviourPun)c).photonView;
			Player val = (Object.op_Implicit((Object)(object)photonView) ? photonView.Owner : null);
			if (val == null || !(val.CustomProperties[(object)"PF_ETrial"] is string text) || text != instance.protocol)
			{
				return 0f;
			}
			if (!(val.CustomProperties[(object)"PF_EView"] is int num) || num != photonView.ViewID)
			{
				return 0f;
			}
			return (val.CustomProperties[(object)"PF_ECharge"] is float num2 && Finite(num2, 0f, 1f)) ? num2 : 0f;
		}

		private void Update()
		{
			//IL_02d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_02db: Unknown result type (might be due to invalid IL or missing references)
			//IL_0347: Unknown result type (might be due to invalid IL or missing references)
			if (!ready || failed)
			{
				return;
			}
			try
			{
				Advertise();
				compatible = RoomCompatible();
				if (Time.unscaledTime >= nextInit)
				{
					nextInit = Time.unscaledTime + 1f;
					EnsureBars();
				}
				Character localCharacter = Character.localCharacter;
				if ((Object)(object)localCharacter != (Object)(object)active)
				{
					stiffnessImmuneUntil = 0.0;
					FinishLock("character-changed");
					active = localCharacter;
					Model.Reset();
					nextPublish = 0f;
				}
				if (!Object.op_Implicit((Object)(object)localCharacter) || !InRun() || !compatible)
				{
					if (!InRun())
					{
						stiffnessImmuneUntil = 0.0;
					}
					if (Model.Charge > 0f || Model.Locked)
					{
						FinishLock((!InRun()) ? "run-ended" : "room-incompatible");
						Model.Reset();
						Publish(force: true);
						RefreshBar();
					}
					message = ((!InRun()) ? "Ready for a new solo run" : ((!compatible) ? "Waiting for matching trial on every player" : "Waiting for character"));
					Report();
				}
				else
				{
					if ((Object)(object)localCharacter.data == (Object)null || localCharacter.refs == null)
					{
						return;
					}
					TickShared(localCharacter);
					if (localCharacter.data.dead)
					{
						stiffnessImmuneUntil = 0.0;
						FinishLock("death");
						Model.Reset();
						Publish(force: false);
						RefreshBar();
						Report();
						return;
					}
					float charge = Model.Charge;
					bool flag = Model.Tick(Time.deltaTime, held: false, 0f, settings.decayPerSecond, settings.chargeCap, localCharacter.data.fullyConscious && PhotonNetwork.Time >= stiffnessImmuneUntil, settings.stiffnessIntervalMultiplier, settings.stiffnessDuration);
					if (observingLock && (flag || !Model.Locked))
					{
						FinishLock(localCharacter.data.fullyConscious ? "timer" : "not-conscious");
					}
					if (flag)
					{
						sparkSerial++;
						Vector3 direction = JoltDirection(localCharacter);
						CancelActions(localCharacter);
						observingLock = true;
						lockStartedGame = Time.time;
						lockStartedWall = Time.realtimeSinceStartup;
						lockGateCount = 0;
						lockInputCount = 0;
						Publish(force: true);
						if (settings.joltVelocityChange > 0f || settings.joltUpwardVelocityChange > 0f)
						{
							ApplyJolt(localCharacter, direction);
						}
						Log("stiffness", "version=1.0.0 charge=" + Model.Charge.ToString("F4", CultureInfo.InvariantCulture) + " duration=" + settings.stiffnessDuration.ToString("F2", CultureInfo.InvariantCulture) + " joltHorizontalDeltaV=" + settings.joltVelocityChange.ToString("F2", CultureInfo.InvariantCulture) + " joltUpwardDeltaV=" + settings.joltUpwardVelocityChange.ToString("F2", CultureInfo.InvariantCulture));
					}
					if (Model.Locked)
					{
						Mask(localCharacter.input);
						localCharacter.data.isSprinting = false;
					}
					if (Mathf.Abs(Model.Charge - charge) > 1E-06f)
					{
						localCharacter.ClampStamina();
					}
					RefreshBar();
					Publish(force: false);
					message = (Model.Locked ? ("STIFF - " + Model.LockRemaining.ToString("F2") + "s remaining") : "Electrical charge decays normally");
					Report();
				}
			}
			catch (Exception error)
			{
				RemoveHooks();
				SharedWorld.MarkStartupFailure("Thunderfen electrical effects");
				Fail(error);
			}
		}

		private void Advertise()
		{
			//IL_0044: 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: Expected O, but got Unknown
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Expected O, but got Unknown
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Expected O, but got Unknown
			//IL_008a: Expected O, but got Unknown
			if (PhotonNetwork.LocalPlayer != null && (!(PhotonNetwork.LocalPlayer.CustomProperties[(object)"PF_ETrial"] is string text) || text != protocol))
			{
				Player localPlayer = PhotonNetwork.LocalPlayer;
				Hashtable val = new Hashtable();
				((Dictionary<object, object>)val).Add((object)"PF_ETrial", (object)protocol);
				((Dictionary<object, object>)val).Add((object)"PF_ECharge", (object)0f);
				((Dictionary<object, object>)val).Add((object)"PF_EView", (object)0);
				localPlayer.SetCustomProperties(val, (Hashtable)null, (WebFlags)null);
			}
		}

		private bool RoomCompatible()
		{
			if (!PhotonNetwork.InRoom)
			{
				return false;
			}
			foreach (Player item in PhotonNetwork.PlayerList.Where((Player p) => !p.IsInactive))
			{
				if (!(item.CustomProperties[(object)"PF_ETrial"] is string text) || text != protocol)
				{
					return false;
				}
			}
			return true;
		}

		private void Publish(bool force)
		{
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Expected O, but got Unknown
			if (PhotonNetwork.LocalPlayer != null && PhotonNetwork.InRoom && (force || !(Time.unscaledTime < nextPublish)))
			{
				nextPublish = Time.unscaledTime + 0.25f;
				sparkUntil = ((observingLock && Model.Locked) ? (PhotonNetwork.Time + Math.Min(10.0, Model.LockRemaining / (double)Math.Max(0.1f, Time.timeScale))) : 0.0);
				Player localPlayer = PhotonNetwork.LocalPlayer;
				Hashtable val = new Hashtable();
				((Dictionary<object, object>)(object)val).Add((object)"PF_ECharge", (object)Model.Charge);
				((Dictionary<object, object>)(object)val).Add((object)"PF_EView", (object)((Object.op_Implicit((Object)(object)active) && Object.op_Implicit((Object)(object)((MonoBehaviourPun)active).photonView)) ? ((MonoBehaviourPun)active).photonView.ViewID : 0));
				((Dictionary<object, object>)(object)val).Add((object)"TF_StaticOwner3", (object)OwnerBurstState());
				((Dictionary<object, object>)(object)val).Add((object)"TF_EStiff", (object)new object[4]
				{
					protocol,
					(Object.op_Implicit((Object)(object)active) && Object.op_Implicit((Object)(object)((MonoBehaviourPun)active).photonView)) ? ((MonoBehaviourPun)active).photonView.ViewID : 0,
					sparkSerial,
					sparkUntil
				});
				localPlayer.SetCustomProperties(val, (Hashtable)null, (WebFlags)null);
			}
		}

		public static void Mask(CharacterInput input)
		{
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)input == (Object)null)
			{
				return;
			}
			FieldInfo[] fields = typeof(CharacterInput).GetFields(BindingFlags.Instance | BindingFlags.Public);
			foreach (FieldInfo fieldInfo in fields)
			{
				if (fieldInfo.FieldType == typeof(bool) && fieldInfo.Name != "pauseWasPressed" && fieldInfo.Name != "pushToTalkPressed" && fieldInfo.Name != "itemSwitchBlocked")
				{
					fieldInfo.SetValue(input, false);
				}
			}
			input.movementInput = Vector2.zero;
			input.scrollInput = 0f;
		}

		private void ApplyJolt(Character c, Vector3 direction)
		{
			//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_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			Vector3 val = direction * settings.joltVelocityChange + Vector3.up * settings.joltUpwardVelocityChange;
			foreach (Bodypart part in c.refs.ragdoll.partList)
			{
				if (Object.op_Implicit((Object)(object)part))
				{
					Rigidbody rig = part.Rig;
					if (Object.op_Implicit((Object)(object)rig) && !rig.isKinematic)
					{
						rig.AddForce(val, (ForceMode)2);
					}
				}
			}
		}

		private static Vector3 JoltDirection(Character c)
		{
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_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)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: 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_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: 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_0080: Unknown result type (might be due to invalid IL or missing references)
			if (c.data.isClimbing)
			{
				Vector3 val = Vector3.ProjectOnPlane(c.data.climbNormal, Vector3.up);
				if (((Vector3)(ref val)).sqrMagnitude > 0.001f)
				{
					return ((Vector3)(ref val)).normalized;
				}
			}
			Vector3 val2 = Vector3.ProjectOnPlane(-((Component)c).transform.forward, Vector3.up);
			return (((Vector3)(ref val2)).sqrMagnitude > 0.001f) ? ((Vector3)(ref val2)).normalized : Vector3.back;
		}

		private void FinishLock(string reason)
		{
			if (observingLock)
			{
				observingLock = false;
				sparkUntil = 0.0;
				Publish(force: true);
				lastLockGameSeconds = Time.time - lockStartedGame;
				lastLockWallSeconds = Time.realtimeSinceStartup - lockStartedWall;
				Log("lock-ended", "version=1.0.0 reason=" + reason + " elapsedGame=" + lastLockGameSeconds.ToString("F3", CultureInfo.InvariantCulture) + " elapsedReal=" + lastLockWallSeconds.ToString("F3", CultureInfo.InvariantCulture) + " movementGates=" + lockGateCount + " maskedMoveSamples=" + lockInputCount);
			}
		}

		public static void NoteMovementGate()
		{
			if (Object.op_Implicit((Object)(object)Instance) && Instance.observingLock)
			{
				Instance.lockGateCount++;
			}
		}

		public static void NoteInputSample(CharacterInput input)
		{
			if (Object.op_Implicit((Object)(object)Instance) && Instance.observingLock && (Object)(object)input != (Object)null && ((Vector2)(ref input.movementInput)).sqrMagnitude > 0.0001f)
			{
				Instance.lockInputCount++;
			}
		}

		private void CancelActions(Character c)
		{
			c.refs.climbing.StopAnyClimbing();
			Item currentItem = c.data.currentItem;
			if (Object.op_Implicit((Object)(object)currentItem))
			{
				if (currentItem.isUsingPrimary)
				{
					currentItem.CancelUsePrimary();
				}
				if (currentItem.isUsingSecondary)
				{
					currentItem.CancelUseSecondary();
				}
			}
			if (Object.op_Implicit((Object)(object)c.refs.items))
			{
				AccessTools.Method(typeof(CharacterItems), "CancelClimbingSpike", (Type[])null, (Type[])null).Invoke(c.refs.items, null);
			}
			c.data.isSprinting = false;
			Mask(c.input);
		}

		public void EnsureBar(StaminaBar bar)
		{
			if (!ready || failed || !Object.op_Implicit((Object)(object)bar) || bars.Contains(bar))
			{
				return;
			}
			try
			{
				EnsureBarCore(bar);
			}
			catch (Exception error)
			{
				Fail(error);
			}
		}

		private void EnsureBarCore(StaminaBar bar)
		{
			//IL_00da: Unknown result type (might be due to invalid IL or missing references)
			BarAffliction[] componentsInChildren = ((Component)((Component)bar).transform.parent).GetComponentsInChildren<BarAffliction>(true);
			BarAffliction val = ((IEnumerable<BarAffliction>)componentsInChildren).FirstOrDefault((Func<BarAffliction, bool>)((BarAffliction a) => !a.isPetrify && (int)a.afflictionType == 3)) ?? ((IEnumerable<BarAffliction>)componentsInChildren).FirstOrDefault((Func<BarAffliction, bool>)((BarAffliction a) => !a.isPetrify));
			if (Object.op_Implicit((Object)(object)val))
			{
				GameObject val2 = Object.Instantiate<GameObject>(((Component)val).gameObject, ((Component)val).transform.parent);
				((Object)val2).name = "PF_ElectricalStatus";
				BarAffliction entry = val2.GetComponent<BarAffliction>();
				entry.rtf = val2.GetComponent<RectTransform>();
				entry.isPetrify = false;
				entry.afflictionType = (STATUSTYPE)62001;
				entry.size = 0f;
				entry.width = 0f;
				if (!Object.op_Implicit((Object)(object)entry.icon))
				{
					throw new InvalidOperationException("Cloned native status bar has no icon reference.");
				}
				entry.icon.sprite = bolt;
				Image[] accents = (from img in val2.GetComponentsInChildren<Image>(true)
					where ((Object)img).name == "Fill" || ((Object)img).name == "Outline" || (Object)(object)img == (Object)(object)entry.icon
					select img).ToArray();
				if (!Object.op_Implicit((Object)(object)immunityShield))
				{
					immunityShield = StiffnessBadge.CreateSprite();
				}
				StiffnessBadge stiffnessBadge = val2.AddComponent<StiffnessBadge>();
				stiffnessBadge.icon = entry.icon;
				stiffnessBadge.accents = accents;
				stiffnessBadge.normalIcon = bolt;
				stiffnessBadge.shieldedIcon = immunityShield;
				stiffnessBadge.charge = () => ChargeFor(Character.localCharacter);
				stiffnessBadge.immune = delegate
				{
					Character localCharacter = Character.localCharacter;
					return Object.op_Implicit((Object)(object)this) && CanReceive(localCharacter) && ((MonoBehaviourPun)localCharacter).photonView.IsMine && StiffnessImmunityRemaining > 0.0;
				};
				stiffnessBadge.Refresh();
				val2.SetActive(false);
				List<BarAffliction> list = (bar.afflictions ?? componentsInChildren).Where((BarAffliction a) => Object.op_Implicit((Object)(object)a) && (Object)(object)a != (Object)(object)entry).ToList();
				list.Add(entry);
				bar.afflictions = list.ToArray();
				bars.Add(bar);
				Log("bar-created", "Electrical segment added to native stamina bar.");
			}
		}

		private void EnsureBars()
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			StaminaBar[] array = Resources.FindObjectsOfTypeAll<StaminaBar>();
			foreach (StaminaBar val in array)
			{
				if (Object.op_Implicit((Object)(object)val))
				{
					Scene scene = ((Component)val).gameObject.scene;
					if (((Scene)(ref scene)).IsValid())
					{
						EnsureBar(val);
					}
				}
			}
		}

		private static Sprite CreateBolt()
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Expected O, but got Unknown
			//IL_0118: Unknown result type (might be due to invalid IL or missing references)
			//IL_0127: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			Texture2D val = new Texture2D(32, 32, (TextureFormat)4, false);
			((Object)val).name = "PF_ElectricBolt";
			((Texture)val).filterMode = (FilterMode)0;
			Color[] array = (Color[])(object)new Color[1024];
			for (int i = 3; i < 29; i++)
			{
				for (int j = 0; j < 32; j++)
				{
					float num = (float)(i - 3) / 26f;
					bool flag = i >= 15 && (float)j >= 12f + (float)(i - 15) * 0.25f && (float)j <= 23f + (float)(i - 15) * 0.15f;
					bool flag2 = i <= 17 && (float)j >= 7f + (float)(i - 3) * 0.35f && (float)j <= 10f + (float)(i - 3) * 0.8f;
					if (flag || flag2)
					{
						array[i * 32 + j] = Color.white;
					}
				}
			}
			val.SetPixels(array);
			val.Apply();
			return Sprite.Create(val, new Rect(0f, 0f, 32f, 32f), new Vector2(0.5f, 0.5f));
		}

		public static void RefreshBar()
		{
			if (!(Time.unscaledTime < nextBarRefresh))
			{
				nextBarRefresh = Time.unscaledTime + 0.1f;
				if (Object.op_Implicit((Object)(object)GUIManager.instance) && Object.op_Implicit((Object)(object)GUIManager.instance.bar))
				{
					GUIManager.instance.bar.ChangeBar();
				}
			}
		}

		private void Report()
		{
			if (RuntimeDiagnostics.PeriodicSnapshots && !(Time.unscaledTime < nextReport))
			{
				nextReport = Time.unscaledTime + (Model.Locked ? 0.1f : 2f);
				State state = new State
				{
					utc = DateTime.UtcNow.ToString("O"),
					version = "1.0.0",
					ready = ready,
					failed = failed,
					roomCompatible = compatible,
					inRun = InRun(),
					charge = Model.Charge,
					stiff = Model.Locked,
					events = Model.EventCount,
					nativeStatusCount = sourceArrayCount,
					lockRemaining = (float)Model.LockRemaining,
					configuredLockSeconds = ((settings != null) ? settings.stiffnessDuration : 0f),
					configuredDecayPerSecond = ((settings != null) ? settings.decayPerSecond : 0f),
					configuredIntervalMultiplier = ((settings != null) ? settings.stiffnessIntervalMultiplier : 0f),
					joltVelocityChange = ((settings != null) ? settings.joltVelocityChange : 0f),
					joltUpwardVelocityChange = ((settings != null) ? settings.joltUpwardVelocityChange : 0f),
					lastLockGameSeconds = lastLockGameSeconds,
					lastLockWallSeconds = lastLockWallSeconds,
					movementGateCalls = lockGateCount,
					maskedMoveSamples = lockInputCount,
					diagnosticBarFilters = ElectricalBarCompatibility.FilteredReads,
					areaDosesReceived = areaDoses.Accepted,
					areaDosesApplied = areaDoses.Applied,
					areaDoseDuplicates = areaDoses.Duplicates,
					areaDosesPending = areaDoses.Pending,
					stiffSparkEffects = stiffnessVisuals.Active,
					stiffSparkStarts = stiffnessVisuals.Started,
					charged = StaticBurstRules.Charged(Model.Charge),
					chargedAuras = staticVisuals.Auras,
					staticBurstVisuals = staticVisuals.Bursts,
					staticBurstVisualStarts = staticVisuals.Started,
					staticAckSent = ackSent,
					staticAckReceived = ackReceived,
					staticAckRejected = ackRejected,
					staticAckPropertyReads = ackPropertyReads,
					lastAckRejection = lastAckRejection,
					staticBurstContacts = burstContacts,
					staticBurstCommits = burstCommits,
					staticBurstPending = ((burstLedger != null) ? burstLedger.records.Length : 0),
					staticBurstClaims = burstClaims,
					staticBurstLaunches = burstLaunches,
					staticBurstCancellations = burstCancellations,
					staticBurstPreviews = burstPreviews,
					lastBurstToken = lastBurstToken,
					lastBurstConsumed = lastBurstConsumed,
					lastBurstInjury = lastBurstInjury,
					lastBurstForce = lastBurstForce,
					message = message,
					error = lastFailure
				};
				string contents = JsonUtility.ToJson((object)state, true);
				File.WriteAllText(Path.Combine(Folder, "trial-state.json"), contents);
				if (InRun() && Object.op_Implicit((Object)(object)active))
				{
					File.WriteAllText(Path.Combine(Folder, "electrical-last-active.json"), contents);
				}
			}
		}

		private void Log(string kind, string detail)
		{
			((BaseUnityPlugin)this).Logger.LogInfo((object)(kind + ": " + detail));
			if (RuntimeDiagnostics.PeriodicSnapshots)
			{
				File.AppendAllText(Path.Combine(Folder, "events.tsv"), DateTime.UtcNow.ToString("O") + "\t" + kind + "\t" + detail.Replace('\t', ' ').Replace('\n', ' ') + "\n");
			}
		}

		private void Fail(Exception error)
		{
			FinishLock("trial-error");
			stiffnessVisuals.Dispose();
			staticVisuals.Dispose();
			bodyContacts.Clear();
			failed = true;
			ready = false;
			Model.Reset();
			lastFailure = error.ToString();
			message = "Electrical trial stopped; see trial-state.json";
			((BaseUnityPlugin)this).Logger.LogError((object)lastFailure);
			nextReport = 0f;
			try
			{
				Publish(force: true);
				Report();
				RefreshBar();
			}
			catch
			{
			}
		}

		private void RemoveHooks()
		{
			SharedWorld.Message -= ReceiveShared;
			if (PhotonNetwork.NetworkingClient != null)
			{
				PhotonNetwork.NetworkingClient.EventReceived -= ReceiveBurstAck;
			}
			Harmony obj = harmony;
			if (obj != null)
			{
				obj.UnpatchSelf();
			}
			harmony = null;
		}

		private void OnDestroy()
		{
			//IL_0112: Unknown result type (might be due to invalid IL or missing references)
			//IL_011c: Invalid comparison between Unknown and I4
			RemoveHooks();
			if (Object.op_Implicit((Object)(object)immunityShield))
			{
				Object.Destroy((Object)(object)immunityShield.texture);
				Object.Destroy((Object)(object)immunityShield);
			}
			stiffnessVisuals.Dispose();
			staticVisuals.Dispose();
			bodyContacts.Clear();
			FinishLock("plugin-unloaded");
			ready = false;
			Model.Reset();
			try
			{
				Publish(force: true);
			}
			catch
			{
			}
			foreach (StaminaBar bar in bars)
			{
				if (!Object.op_Implicit((Object)(object)bar))
				{
					continue;
				}
				BarAffliction[] array = (BarAffliction[])(((object)bar.afflictions) ?? ((object)new BarAffliction[0]));
				bar.afflictions = array.Where((BarAffliction a) => Object.op_Implicit((Object)(object)a) && (int)a.afflictionType != 62001).ToArray();
				BarAffliction[] array2 = array;
				foreach (BarAffliction val in array2)
				{
					if (Object.op_Implicit((Object)(object)val) && (int)val.afflictionType == 62001)
					{
						Object.Destroy((Object)(object)((Component)val).gameObject);
					}
				}
			}
			if ((Object)(object)Instance == (Object)(object)this)
			{
				Instance = null;
			}
		}

		private void ScopeShared(Character c)
		{
			string epoch = SharedWorld.Epoch;
			int num = ((Object.op_Implicit((Object)(object)c) && Object.op_Implicit((Object)(object)((MonoBehaviourPun)c).photonView)) ? ((MonoBehaviourPun)c).photonView.ViewID : 0);
			if (!(electricalEpoch == epoch) || electricalView != num)
			{
				electricalEpoch = epoch;
				electricalView = num;
				areaDoses.Scope(epoch);
				staticReceipts.Clear();
				burstAcks.Clear();
				nextAck.Clear();
				burstVisualReceipts.Clear();
				bodyContacts.Clear();
				burstLedger = null;
				wasBurstMaster = false;
				nextBurst = 0f;
			}
		}

		private void ReceiveShared(string kind, string id, object[] data)
		{
			if (!SharedWorld.Online)
			{
				return;
			}
			if (kind == "charge")
			{
				areaDoses.Receive(SharedWorld.Epoch, data, PhotonNetwork.Time);
			}
			if ((kind == "static-claim" || kind == "static-burst") && data != null && data.Length == 1 && data[0] is string { Length: <2048 } text)
			{
				Character localCharacter = Character.localCharacter;
				if (Object.op_Implicit((Object)(object)localCharacter) && InRun() && compatible && SharedWorld.Ready)
				{
					ScopeShared(localCharacter);
					StaticBurstEvent b = JsonUtility.FromJson<StaticBurstEvent>(text);
					HandleBurst(b, localCharacter);
				}
			}
		}

		private bool LocalBurstOwner(Character c)
		{
			return Object.op_Implicit((Object)(object)c) && (Object)(object)c == (Object)(object)Character.localCharacter && (Object)(object)c == (Object)(object)active && Object.op_Implicit((Object)(object)((MonoBehaviourPun)c).photonView) && ((MonoBehaviourPun)c).photonView.IsMine && Object.op_Implicit((Object)(object)c.data) && !c.data.dead && c.refs != null && Object.op_Implicit((Object)(object)c.refs.afflictions) && Object.op_Implicit((Object)(object)c.refs.ragdoll);
		}

		private void HandleBurst(StaticBurstEvent b, Character c)
		{
			//IL_00a3: 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_0255: 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_026d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0271: Unknown result type (might be due to invalid IL or missing references)
			if (b == null || !b.Valid(protocol, SharedWorld.Epoch))
			{
				return;
			}
			double time = PhotonNetwork.Time;
			if (!StaticBurstRules.Fresh(b.createdAt, time, 13.0))
			{
				return;
			}
			if (b.phase == 1 && StaticBurstRules.Fresh(b.committedAt, time, 5.0) && burstVisualReceipts.Take(b.token))
			{
				staticVisuals.Burst(new Vector3(b.x, b.y, b.z), new Vector3(b.dx, b.dy, b.dz), Math.Max(b.qa, b.qb), b.token.GetHashCode());
			}
			if (!LocalBurstOwner(c))
			{
				return;
			}
			int viewID = ((MonoBehaviourPun)c).photonView.ViewID;
			int actorNumber = PhotonNetwork.LocalPlayer.ActorNumber;
			if ((viewID != b.a || actorNumber != b.actorA) && (viewID != b.b || actorNumber != b.actorB))
			{
				return;
			}
			if (b.phase == 0)
			{
				if (StaticBurstRules.Fresh(b.createdAt, time, 8.0))
				{
					if (staticReceipts.Consume(b.token, Model.Charge, out var receipt))
					{
						ConsumeStaticCharge(c, receipt.consumed, b.token);
						burstClaims++;
						Publish(force: true);
					}
					if (receipt != null)
					{
						SendBurstAck(receipt);
					}
				}
				return;
			}
			if (!staticReceipts.Launch(b.token, out var receipt2))
			{
				if (receipt2 != null && receipt2.launched)
				{
					SendBurstAck(receipt2);
				}
				return;
			}
			if (StaticBurstRules.Fresh(b.committedAt, time, 5.0))
			{
				Vector3 away = new Vector3(b.dx, b.dy, b.dz) * (float)((viewID == b.a) ? 1 : (-1));
				LaunchStatic(c, away, Math.Max(b.qa, b.qb));
				burstLaunches++;
				Log("static-burst-launch", "token=" + b.token + " consumed=" + receipt2.consumed + " H=" + Math.Max(b.qa, b.qb) + " force=" + lastBurstForce);
			}
			Publish(force: true);
			SendBurstAck(receipt2);
		}

		private void ConsumeStaticCharge(Character c, float own, string token)
		{
			lastBurstToken = token;
			lastBurstConsumed = own;
			lastBurstInjury = StaticBurstRules.Injury(own);
			FinishLock("static-burst");
			Model.Reset();
			c.refs.afflictions.AddStatus((STATUSTYPE)0, lastBurstInjury, false, false, true, false, false);
			c.ClampStamina();
			RefreshBar();
			Log("static-burst-consume", "token=" + token + " own=" + own + " injury=" + lastBurstInjury);
		}

		private void LaunchStatic(Character c, Vector3 away, float highest)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_006f: 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_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			if (LocalBurstOwner(c))
			{
				CancelActions(c);
				Vector3 val = Vector3.ProjectOnPlane(away, Vector3.up);
				if (((Vector3)(ref val)).sqrMagnitude < 0.0001f)
				{
					val = Vector3.right;
				}
				Vector3 val2 = ((Vector3)(ref val)).normalized + Vector3.up * 0.45f;
				Vector3 normalized = ((Vector3)(ref val2)).normalized;
				lastBurstForce = StaticBurstRules.Force(highest);
				NativeStaticBurst.Apply(c, normalized * lastBurstForce);
			}
		}

		private object[] OwnerBurstState()
		{
			Character localCharacter = Character.localCharacter;
			StaticBurstReceipts staticBurstReceipts = staticReceipts;
			string text = protocol;
			string epoch = electricalEpoch;
			int view = ((Object.op_Implicit((Object)(object)localCharacter) && Object.op_Implicit((Object)(object)((MonoBehaviourPun)localCharacter).photonView)) ? ((MonoBehaviourPun)localCharacter).photonView.ViewID : 0);
			Player localPlayer = PhotonNetwork.LocalPlayer;
			return StaticBurstWire.Owner(staticBurstReceipts.Snapshot(text, epoch, view, (localPlayer != null) ? localPlayer.ActorNumber : 0));
		}

		private void SendBurstAck(StaticBurstReceipt receipt)
		{
			//IL_01ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e0: Expected O, but got Unknown
			Character localCharacter = Character.localCharacter;
			if (!SharedWorld.Online || !Object.op_Implicit((Object)(object)localCharacter) || !Object.op_Implicit((Object)(object)((MonoBehaviourPun)localCharacter).photonView) || !((MonoBehaviourPun)localCharacter).photonView.IsMine || PhotonNetwork.LocalPlayer == null)
			{
				return;
			}
			string key = receipt.token + ":" + receipt.launched;
			double time = PhotonNetwork.Time;
			if (!nextAck.TryGetValue(key, out var value) || !(time < value))
			{
				if (nextAck.Count >= 128)
				{
					nextAck.Remove(nextAck.Keys.First());
				}
				nextAck[key] = time + 0.5;
				object[] array = StaticBurstWire.Ack(protocol, electricalEpoch, ((MonoBehaviourPun)localCharacter).photonView.ViewID, PhotonNetwork.LocalPlayer.ActorNumber, receipt);
				ackSent++;
				Log("static-burst-ack-send", "token=" + receipt.token + " view=" + ((MonoBehaviourPun)localCharacter).photonView.ViewID + " actor=" + PhotonNetwork.LocalPlayer.ActorNumber + " consumed=" + receipt.consumed + " launched=" + receipt.launched);
				if (SharedWorld.Authority)
				{
					ReceiveAck(array, PhotonNetwork.LocalPlayer.ActorNumber);
					return;
				}
				PhotonNetwork.RaiseEvent((byte)181, (object)array, new RaiseEventOptions
				{
					Receivers = (ReceiverGroup)2
				}, SendOptions.SendReliable);
			}
		}

		private void ReceiveBurstAck(EventData ev)
		{
			if (ev.Code == 181)
			{
				ReceiveAck(ev.CustomData, ev.Sender);
			}
		}

		private void ReceiveAck(object payload, int sender)
		{
			if (!ready || failed || !compatible || !SharedWorld.Ready || !SharedWorld.Online || !SharedWorld.Authority)
			{
				return;
			}
			if (!StaticBurstWire.ReadAck(payload, protocol, electricalEpoch, sender, out var view, out var actor, out var receipt))
			{
				ackRejected++;
				lastAckRejection = "wire/epoch/protocol/sender";
				return;
			}
			StaticBurstEvent staticBurstEvent = burstLedger?.records.FirstOrDefault((StaticBurstEvent r) => r.token == receipt.token && ((r.a == view && r.actorA == actor) || (r.b == view && r.actorB == actor)));
			Character val = SharedWorld.CharacterFor(view);
			if (staticBurstEvent == null || !Object.op_Implicit((Object)(object)val) || ((MonoBehaviourPun)val).photonView.Owner == null || ((MonoBehaviourPun)val).photonView.Owner.ActorNumber != actor || !StaticBurstRules.Fresh(staticBurstEvent.createdAt, PhotonNetwork.Time, 13.0) || !burstAcks.Add(view, actor, receipt))
			{
				ackRejected++;
				lastAckRejection = "no pending participant/owner/amount";
				return;
			}
			ackReceived++;
			lastAckRejection = "";
			Log("static-burst-receipt", "token=" + receipt.token + " actor=" + actor + " view=" + view + " consumed=" + receipt.consumed + " launched=" + receipt.launched);
		}

		private StaticBurstReceipt ReceiptFor(int view, int actor, string token)
		{
			StaticBurstReceipt staticBurstReceipt = burstAcks.Find(view, actor, token);
			if (staticBurstReceipt != null)
			{
				return staticBurstReceipt;
			}
			Character val = SharedWorld.CharacterFor(view);
			if (!Object.op_Implicit((Object)(object)val) || ((MonoBehaviourPun)val).photonView.Owner == null || ((MonoBehaviourPun)val).photonView.Owner.ActorNumber != actor)
			{
				return null;
			}
			if (LocalBurstOwner(val))
			{
				return StaticBurstReceipts.Find(staticReceipts.Snapshot(protocol, electricalEpoch, view, actor), protocol, electricalEpoch, view, actor, token);
			}
			StaticBurstOwnerState staticBurstOwnerState = StaticBurstWire.ReadOwner(((MonoBehaviourPun)val).photonView.Owner.CustomProperties[(object)"TF_StaticOwner3"], protocol, electricalEpoch, view, actor);
			if (staticBurstOwnerState == null)
			{
				return null;
			}
			StaticBurstReceipt staticBurstReceipt2 = StaticBurstReceipts.Find(staticBurstOwnerState, protocol, electricalEpoch, view, actor, token);
			if (staticBurstReceipt2 != null)
			{
				ackPropertyReads++;
			}
			return staticBurstReceipt2;
		}

		private bool BurstParticipant(int view, int actor)
		{
			Character val = SharedWorld.CharacterFor(view);
			return Object.op_Implicit((Object)(object)val) && CanReceive(val) && ((MonoBehaviourPun)val).photonView.Owner != null && ((MonoBehaviourPun)val).photonView.Owner.ActorNumber == actor;
		}

		private StaticBurstLedger ReadBurstLedger()
		{
			string text = ((RoomInfo)PhotonNetwork.CurrentRoom).CustomProperties[(object)"TF_StaticBursts2"] as string;
			if (string.IsNullOrEmpty(text) || text.Length > 32768)
			{
				return null;
			}
			StaticBurstLedger staticBurstLedger = JsonUtility.FromJson<StaticBurstLedger>(text);
			if (staticBurstLedger == null || staticBurstLedger.protocol != protocol || staticBurstLedger.epoch != electricalEpoch || staticBurstLedger.records == null || staticBurstLedger.records.Length > 32 || staticBurstLedger.records.Any((StaticBurstEvent b) => b == null || !b.Valid(protocol, electricalEpoch)))
			{
				return null;
			}
			return staticBurstLedger;
		}

		private unsafe void TickShared(Character c)
		{
			//IL_0959: Unknown result type (might be due to invalid IL or missing references)
			//IL_095e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0974: Expected O, but got Unknown
			//IL_097c: Expected O, but got Unknown
			//IL_0722: Unknown result type (might be due to invalid IL or missing references)
			//IL_0729: Unknown result type (might be due to invalid IL or missing references)
			//IL_072e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0733: Unknown result type (might be due to invalid IL or missing references)
			//IL_0738: Unknown result type (might be due to invalid IL or missing references)
			//IL_073d: Unknown result type (might be due to invalid IL or missing references)
			//IL_07f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0804: Unknown result type (might be due to invalid IL or missing references)
			//IL_0811: Unknown result type (might be due to invalid IL or missing references)
			//IL_081e: Unknown result type (might be due to invalid IL or missing references)
			//IL_082b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0838: Unknown result type (might be due to invalid IL or missing references)
			//IL_0753: Unknown result type (might be due to invalid IL or missing references)
			//IL_0758: Unknown result type (might be due to invalid IL or missing references)
			if (!SharedWorld.Online)
			{
				return;
			}
			ScopeShared(c);
			AreaChargeQueue.AppliedDose[] array = areaDoses.Drain(SharedWorld.Epoch, ((MonoBehaviourPun)c).photonView.ViewID, PhotonNetwork.Time, SharedWorld.Ready, !c.data.dead, Model);
			AreaChargeQueue.AppliedDose[] array2 = array;
			foreach (AreaChargeQueue.AppliedDose appliedDose in array2)
			{
				Log("area-dose", "epoch=" + SharedWorld.Epoch + " source=" + appliedDose.source + " cycle=" + appliedDose.cycle + " view=" + appliedDose.view + " offered=" + appliedDose.offered.ToString("F4") + " used=" + appliedDose.used.ToString("F4") + " after=" + appliedDose.after.ToString("F4"));
			}
			if (array.Any((AreaChargeQueue.AppliedDose d) => d.used > 0f))
			{
				c.ClampStamina();
				RefreshBar();
				Publish(force: true);
			}
			if (!SharedWorld.Ready || !InRun() || Time.unscaledTime < nextBurst)
			{
				return;
			}
			nextBurst = Time.unscaledTime + 0.05f;
			bool authority = SharedWorld.Authority;
			if (authority && !wasBurstMaster)
			{
				burstLedger = ReadBurstLedger() ?? new StaticBurstLedger
				{
					protocol = protocol,
					epoch = electricalEpoch
				};
				burstGrace = PhotonNetwork.Time + 1.0;
			}
			wasBurstMaster = authority;
			StaticBurstLedger staticBurstLedger = (authority ? burstLedger : ReadBurstLedger());
			if (staticBurstLedger != null)
			{
				StaticBurstEvent[] records = staticBurstLedger.records;
				foreach (StaticBurstEvent b in records)
				{
					HandleBurst(b, c);
				}
			}
			if (!authority || PhotonNetwork.Time < burstGrace)
			{
				return;
			}
			bool flag = false;
			double time = PhotonNetwork.Time;
			List<StaticBurstEvent> list = burstLedger.records.ToList();
			List<StaticBurstEvent> list2 = new List<StaticBurstEvent>();
			StaticBurstEvent[] array3 = list.ToArray();
			foreach (StaticBurstEvent staticBurstEvent in array3)
			{
				if (!BurstParticipant(staticBurstEvent.a, staticBurstEvent.actorA) || !BurstParticipant(staticBurstEvent.b, staticBurstEvent.actorB))
				{
					list.Remove(staticBurstEvent);
					burstCancellations++;
					flag = true;
					continue;
				}
				StaticBurstReceipt staticBurstReceipt = ReceiptFor(staticBurstEvent.a, staticBurstEvent.actorA, staticBurstEvent.token);
				StaticBurstReceipt staticBurstReceipt2 = ReceiptFor(staticBurstEvent.b, staticBurstEvent.actorB, staticBurstEvent.token);
				if (staticBurstEvent.phase == 0 && staticBurstReceipt != null && staticBurstReceipt2 != null)
				{
					staticBurstEvent.qa = staticBurstReceipt.consumed;
					staticBurstEvent.qb = staticBurstReceipt2.consumed;
					staticBurstEvent.phase = 1;
					staticBurstEvent.committedAt = time;
					staticBurstEvent.lastSent = 0.0;
					burstCommits++;
					Log("static-burst-commit", "token=" + staticBurstEvent.token + " consumedA=" + staticBurstEvent.qa + " consumedB=" + staticBurstEvent.qb + " force=" + StaticBurstRules.Force(Math.Max(staticBurstEvent.qa, staticBurstEvent.qb)));
					flag = true;
				}
				if ((staticBurstEvent.phase == 0 && !StaticBurstRules.Fresh(staticBurstEvent.createdAt, time, 8.0)) || (staticBurstEvent.phase == 1 && ((staticBurstReceipt != null && staticBurstReceipt.launched && staticBurstReceipt2 != null && staticBurstReceipt2.launched) || !StaticBurstRules.Fresh(staticBurstEvent.committedAt, time, 5.0))))
				{
					if (staticBurstEvent.phase == 0)
					{
						burstCancellations++;
						Log("static-burst-expired", "token=" + staticBurstEvent.token + " missing owner consumption receipt; a=" + staticBurstEvent.actorA + ":" + staticBurstEvent.a + " received=" + (staticBurstReceipt != null) + " b=" + staticBurstEvent.actorB + ":" + staticBurstEvent.b + " received=" + (staticBurstReceipt2 != null));
					}
					list.Remove(staticBurstEvent);
					flag = true;
				}
				else if (time - staticBurstEvent.lastSent >= 0.75)
				{
					staticBurstEvent.lastSent = time;
					list2.Add(staticBurstEvent);
					flag = true;
				}
			}
			Character[] array4 = (from p in Character.AllCharacters
				where Object.op_Implicit((Object)(object)p) && CanReceive(p) && Object.op_Implicit((Object)(object)((MonoBehaviourPun)p).photonView) && ((MonoBehaviourPun)p).photonView.Owner != null
				orderby ((MonoBehaviourPun)p).photonView.ViewID
				select p).ToArray();
			HashSet<int> hashSet = new HashSet<int>(list.SelectMany((StaticBurstEvent staticBurstEvent3) => new int[2] { staticBurstEvent3.a, staticBurstEvent3.b }));
			for (int num3 = 0; num3 < array4.Length; num3++)
			{
				for (int num4 = num3 + 1; num4 < array4.Length; num4++)
				{
					Character val = array4[num3];
					Character val2 = array4[num4];
					int viewID = ((MonoBehaviourPun)val).photonView.ViewID;
					int viewID2 = ((MonoBehaviourPun)val2).photonView.ViewID;
					float num5 = ChargeFor(val);
					float num6 = ChargeFor(val2);
					if (!hashSet.Contains(viewID) && !hashSet.Contains(viewID2) && ((MonoBehaviourPun)val).photonView.Owner.ActorNumber != ((MonoBehaviourPun)val2).photonView.Owner.ActorNumber && StaticBurstRules.Eligible(num5, num6) && bodyContacts.Touching(val, val2, out var point))
					{
						Vector3 val3 = Vector3.ProjectOnPlane(val.Center - val2.Center, Vector3.up);
						if (((Vector3)(ref val3)).sqrMagnitude < 0.001f)
						{
							val3 = Vector3.right;
						}
						((Vector3)(ref val3)).Normalize();
						StaticBurstEvent staticBurstEvent2 = new StaticBurstEvent
						{
							token = Guid.NewGuid().ToString("N"),
							protocol = protocol,
							epoch = electricalEpoch,
							a = viewID,
							b = viewID2,
							actorA = ((MonoBehaviourPun)val).photonView.Owner.ActorNumber,
							actorB = ((MonoBehaviourPun)val2).photonView.Owner.ActorNumber,
							qa = num5,
							qb = num6,
							createdAt = time,
							lastSent = time,
							x = point.x,
							y = point.y,
							z = point.z,
							dx = val3.x,
							dy = val3.y,
							dz = val3.z
						};
						list.Add(staticBurstEvent2);
						hashSet.Add(viewID);
						hashSet.Add(viewID2);
						list2.Add(staticBurstEvent2);
						burstContacts++;
						Log("static-burst-contact", "token=" + staticBurstEvent2.token + " a=" + viewID + " b=" + viewID2 + " advertisedA=" + num5 + " advertisedB=" + num6 + " point=" + ((object)(*(Vector3*)(&point))/*cast due to .constrained prefix*/).ToString());
						flag = true;
					}
				}
			}
			if (flag)
			{
				burstLedger.records = list.ToArray();
				Room currentRoom = PhotonNetwork.CurrentRoom;
				Hashtable val4 = new Hashtable();
				((Dictionary<object, object>)val4).Add((object)"TF_StaticBursts2", (object)JsonUtility.ToJson((object)burstLedger));
				currentRoom.SetCustomProperties(val4, (Hashtable)null, (WebFlags)null);
			}
			foreach (StaticBurstEvent item in list2)
			{
				SharedWorld.Emit((item.phase == 0) ? "static-claim" : "static-burst", new object[1] { JsonUtility.ToJson((object)item) }, true);
			}
		}

		public static float TakeCharge(Character c, float maximum)
		{
			ElectricalTrial instance = Instance;
			if (!Object.op_Implicit((Object)(object)instance) || !Object.op_Implicit((Object)(object)c) || (Object)(object)c != (Object)(object)Character.localCharacter || !Object.op_Implicit((Object)(object)((MonoBehaviourPun)c).photonView) || !((MonoBehaviourPun)c).photonView.IsMine || !CanReceive(c) || !Finite(maximum, 0f, 1f))
			{
				return 0f;
			}
			float num = Math.Min(maximum, instance.Model.Charge);
			instance.Model.Set(instance.Model.Charge - num);
			c.ClampStamina();
			RefreshBar();
			instance.Publish(force: false);
			return num;
		}

		public static float AddCharge(Character c, float amount)
		{
			ElectricalTrial instance = Instance;
			if (!Object.op_Implicit((Object)(object)instance) || !Object.op_Implicit((Object)(object)c) || (Object)(object)c != (Object)(object)Character.localCharacter || !Object.op_Implicit((Object)(object)((MonoBehaviourPun)c).photonView) || !((MonoBehaviourPun)c).photonView.IsMine || !CanReceive(c) || !Finite(amount, 0f, 1f))
			{
				return 0f;
			}
			float charge = instance.Model.Charge;
			instance.Model.Set(Math.Min(instance.settings.chargeCap, charge + amount));
			c.ClampStamina();
			RefreshBar();
			instance.Publish(force: true);
			return instance.Model.Charge - charge;
		}

		public static void GrantStiffnessImmunity(Character c, float seconds)
		{
			ElectricalTrial instance = Instance;
			if (Object.op_Implicit((Object)(object)instance) && Object.op_Implicit((Object)(object)c) && !((Object)(object)c != (Object)(object)Character.localCharacter) && Object.op_Implicit((Object)(object)((MonoBehaviourPun)c).photonView) && ((MonoBehaviourPun)c).photonView.IsMine && CanReceive(c) && Finite(seconds, 0f, 180f))
			{
				instance.stiffnessImmuneUntil = PhotonNetwork.Time + (double)seconds;
				instance.FinishLock("stiffness-immunity");
				instance.Model.ClearStiffness();
				instance.Publish(force: true);
				instance.Log("stiffness-immunity", "until=" + instance.stiffnessImmuneUntil + " duration=" + seconds);
			}
		}
	}
	[HarmonyPatch(typeof(CharacterAfflictions), "get_statusSum", new Type[] { })]
	internal static class StatusSumPatch
	{
		private static void Postfix(CharacterAfflictions __instance, ref float __result)
		{
			float num = ElectricalTrial.ChargeFor(__instance.character);
			if (num > 0f)
			{
				__result = Mathf.Min(2f, __result + num);
			}
		}
	}
	[HarmonyPatch(typeof(CharacterAfflictions), "GetCurrentStatus", new Type[] { typeof(STATUSTYPE) })]
	internal static class ElectricalQueryPatch
	{
		private static bool Prefix(CharacterAfflictions __instance, STATUSTYPE __0, ref float __result)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Invalid comparison between Unknown and I4
			if ((int)__0 != 62001)
			{
				return true;
			}
			__result = ElectricalTrial.ChargeFor(__instance.character);
			return false;
		}
	}
	[HarmonyPatch(typeof(StaminaBar), "Start", new Type[] { })]
	internal static class BarStartPatch
	{
		private static void Postfix(StaminaBar __instance)
		{
			if (Object.op_Implicit((Object)(object)ElectricalTrial.Instance))
			{
				ElectricalTrial.Instance.EnsureBar(__instance);
			}
		}
	}
	[HarmonyPatch(typeof(CharacterInput), "Sample", new Type[] { typeof(bool) })]
	internal static class InputSamplePatch
	{
		private static void Postfix(CharacterInput __instance)
		{
			Character localCharacter = Character.localCharacter;
			if (Object.op_Implicit((Object)(object)localCharacter) && (Object)(object)localCharacter.input == (Object)(object)__instance && ElectricalTrial.IsLocked(localCharacter))
			{
				ElectricalTrial.NoteInputSample(__instance);
				ElectricalTrial.Mask(__instance);
			}
		}
	}
	[HarmonyPatch]
	internal static class HotbarPatch
	{
		private static IEnumerable<MethodBase> TargetMethods()
		{
			string[] array = new string[4] { "SelectSlotWasPressed", "SelectSlotIsPressed", "HotbarKeyWasPressed", "HotbarKeyIsPressed" };
			foreach (string name in array)
			{
				yield return NativeCompatibility.Require(typeof(CharacterInput), name, typeof(bool), new Type[1] { typeof(int) });
			}
		}

		private static bool Prefix(CharacterInput __instance, ref bool __result)
		{
			Character localCharacter = Character.localCharacter;
			if (Object.op_Implicit((Object)(object)localCharacter) && (Object)(object)localCharacter.input == (Object)(object)__instance && ElectricalTrial.IsLocked(localCharacter))
			{
				__result = false;
				return false;
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(CharacterClimbing), "CanClimb", new Type[] { })]
	internal static class ClimbGatePatch
	{
		private static bool Prefix(Character ___character, ref bool __result)
		{
			if (ElectricalTrial.IsLocked(___character))
			{
				__result = false;
				return false;
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(CharacterMovement), "GetMovementForce", new Type[] { })]
	internal static class MovementGatePatch
	{
		private static bool Prefix(Character ___character, ref float __result)
		{
			if (ElectricalTrial.IsLocked(___character))
			{
				ElectricalTrial.NoteMovementGate();
				__result = 0f;
				return false;
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(CharacterMovement), "TryToJump", new Type[] { })]
	internal static class JumpGatePatch
	{
		private static bool Prefix(Character ___character)
		{
			return !ElectricalTrial.IsLocked(___character);
		}
	}
	[HarmonyPatch]
	internal static class ItemUseGatePatch
	{
		private static IEnumerable<MethodBase> TargetMethods()
		{
			string[] array = new string[5] { "StartUsePrimary", "StartUseSecondary", "ContinueUsePrimary", "ContinueUseSecondary", "FinishCastPrimary" };
			foreach (string name in array)
			{
				yield return NativeCompatibility.Require(typeof(Item), name, typeof(void), Array.Empty<Type>());
			}
		}

		private static bool Prefix(Item __instance)
		{
			return !ElectricalTrial.IsLocked(__instance.holderCharacter);
		}
	}
	[HarmonyPatch(typeof(CharacterAfflictions), "PrettyPrintStaminaBar", new Type[]
	{
		typeof(float[]),
		typeof(int),
		typeof(bool)
	})]
	public static class ElectricalBarCompatibility
	{
		public static int FilteredReads { get; private set; }

		public static BarAffliction[] NativeEntries(BarAffliction[] entries)
		{
			if (entries == null || !entries.Any((BarAffliction a) => a != null && (int)a.afflictionType == 62001))
			{
				return entries;
			}
			FilteredReads++;
			return entries.Where((BarAffliction a) => a == null || (int)a.afflictionType != 62001).ToArray();
		}

		public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Expected O, but got Unknown
			List<CodeInstruction> list = new List<CodeInstruction>();
			int num = 0;
			FieldInfo objB = AccessTools.Field(typeof(StaminaBar), "afflictions");
			MethodInfo methodInfo = AccessTools.Method(typeof(ElectricalBarCompatibility), "NativeEntries", (Type[])null, (Type[])null);
			foreach (CodeInstruction instruction in instructions)
			{
				list.Add(instruction);
				if (instruction.opcode == OpCodes.Ldfld && object.Equals(instruction.operand, objB))
				{
					list.Add(new CodeInstruction(OpCodes.Call, (object)methodInfo));
					num++;
				}
			}
			if (num != 2)
			{
				throw new InvalidOperationException("Native stamina diagnostic shape changed; expected two affliction reads, found " + num);
			}
			return list;
		}
	}
	public sealed class AreaChargeQueue
	{
		private sealed class Dose
		{
			public string source;

			public int view;

			public float amount;

			public double due;

			public long cycle;
		}

		public sealed class AppliedDose
		{
			public string source;

			public int view;

			public long cycle;

			public float offered;

			public float used;

			public float after;
		}

		private readonly List<Dose> pending = new List<Dose>();

		private readonly CycleReceipts receipts = new CycleReceipts();

		private string epoch;

		public int Accepted { get; private set; }

		public int Applied { get; private set; }

		public int Duplicates { get; private set; }

		public int Dropped { get; private set; }

		public int Pending => pending.Count;

		public void Scope(string value)
		{
			if (!(epoch == value))
			{
				epoch = value;
				pending.Clear();
				receipts.Clear();
			}
		}

		private static bool Finite(double x)
		{
			return !double.IsNaN(x) && !double.IsInfinity(x);
		}

		public bool Receive(string current, object[] data, double now)
		{
			if (string.IsNullOrEmpty(current) || data == null || data.Length != 5 || !(data[0] is string text) || !(data[1] is int num) || !(data[2] is float num2) || !(data[3] is double num3) || !(data[4] is long num4) || (!text.StartsWith("grass:", StringComparison.Ordinal) && !text.StartsWith("swarm:", StringComparison.Ordinal)) || num <= 0 || num4 < 0 || !Finite(num2) || num2 <= 0f || num2 > 0.25f || !Finite(num3) || !Finite(now) || Math.Abs(num3 - now) > 15.0)
			{
				return false;
			}
			Scope(current);
			if (!receipts.Take(text + ":" + num, num4))
			{
				Duplicates++;
				return false;
			}
			pending.Add(new Dose
			{
				source = text,
				view = num,
				amount = num2,
				due = num3,
				cycle = num4
			});
			Accepted++;
			return true;
		}

		public AppliedDose[] Drain(string current, int view, double now, bool ready, bool alive, ElectricalModel model)
		{
			Scope(current);
			List<AppliedDose> list = new List<AppliedDose>();
			Dose[] array = pending.ToArray();
			foreach (Dose dose in array)
			{
				if (now - dose.due > 15.0)
				{
					pending.Remove(dose);
					Dropped++;
				}
				else if (view > 0 && dose.view != view)
				{
					pending.Remove(dose);
				}
				else if (!(now < dose.due) && ready && view > 0)
				{
					pending.Remove(dose);
					if (!alive)
					{
						Dropped++;
						continue;
					}
					float charge = model.Charge;
					model.Set(Math.Min(1f, charge + dose.amount));
					AppliedDose item = new AppliedDose
					{
						source = dose.source,
						view = view,
						cycle = dose.cycle,
						offered = dose.amount,
						used = Math.Max(0f, model.Charge - charge),
						after = model.Charge
					};
					list.Add(item);
					Applied++;
				}
			}
			return list.ToArray();
		}
	}
	public static class StiffnessSignal
	{
		public static bool Active(object raw, string protocol, int view, double now)
		{
			return raw is object[] array && array.Length == 4 && array[0] as string == protocol && array[1] is int num && num == view && array[2] is int num2 && num2 > 0 && array[3] is double num3 && !double.IsNaN(num3) && !double.IsInfinity(num3) && num3 > now && num3 <= now + 10.25;
		}
	}
	public sealed class StiffnessVisuals : IDisposable
	{
		private sealed class Effect
		{
			public Character character;

			public GameObject node;

			public StiffSparkRibbon[] arcs;

			public int frame = -1;
		}

		private readonly Dictionary<int, Effect> effects = new Dictionary<int, Effect>();

		private Material material;

		private float nextFind;

		public int Active => effects.Count;

		public int Started { get; private set; }

		private bool Ensure()
		{
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c3: Expected O, but got Unknown
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			if (Object.op_Implicit((Object)(object)material))
			{
				return true;
			}
			if (Time.unscaledTime < nextFind)
			{
				return false;
			}
			nextFind = Time.unscaledTime + 1f;
			Shader val = Shader.Find("FirstRidge/CampfireParticle") ?? ((IEnumerable<Shader>)Resources.FindObjectsOfTypeAll<Shader>()).FirstOrDefault((Func<Shader, bool>)((Shader s) => Object.op_Implicit((Object)(object)s) && ((Object)s).name == "FirstRidge/CampfireParticle"));
			if (!Object.op_Implicit((Object)(object)val) || !val.isSupported)
			{
				return false;
			}
			material = new Material(val)
			{
				name = "Thunderfen_StiffSparks_Private",
				hideFlags = (HideFlags)61,
				renderQueue = 3100
			};
			material.SetColor("_BaseColor", Color.white);
			return true;
		}

		public void Tick(Func<Character, bool> active)
		{
			//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fe: Expected O, but got Unknown
			//IL_0129: Unknown result type (might be due to invalid IL or missing references)
			//IL_0130: Expected O, but got Unknown
			//IL_0197: Unknown result type (might be due to invalid IL or missing references)
			//IL_019c: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0363: Unknown result type (might be due to invalid IL or missing references)
			//IL_0349: Unknown result type (might be due to invalid IL or missing references)
			//IL_0368: Unknown result type (might be due to invalid IL or missing references)
			//IL_0308: Unknown result type (might be due to invalid IL or missing references)
			//IL_030d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0312: Unknown result type (might be due to invalid IL or missing references)
			//IL_0330: Unknown result type (might be due to invalid IL or missing references)
			//IL_0335: Unknown result type (might be due to invalid IL or missing references)
			//IL_033a: Unknown result type (might be due to invalid IL or missing references)
			//IL_039e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0370: Unknown result type (might be due to invalid IL or missing references)
			//IL_0375: Unknown result type (might be due to invalid IL or missing references)
			//IL_037f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0384: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_03cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_03d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_041d: Unknown result type (might be due to invalid IL or missing references)
			//IL_043b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0440: Unknown result type (might be due to invalid IL or missing references)
			//IL_0446: Unknown result type (might be due to invalid IL or missing references)
			//IL_0448: Unknown result type (might be due to invalid IL or missing references)
			//IL_044c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0463: Unknown result type (might be due to invalid IL or missing references)
			//IL_0468: Unknown result type (might be due to invalid IL or missing references)
			//IL_046d: Unknown result type (might be due to invalid IL or missing references)
			//IL_045f: Unknown result type (might be due to invalid IL or missing references)
			HashSet<int> live = new HashSet<int>();
			if (Ensure())
			{
				foreach (Character allCharacter in Character.AllCharacters)
				{
					if (!Object.op_Implicit((Object)(object)allCharacter) || !Object.op_Implicit((Object)(object)((MonoBehaviourPun)allCharacter).photonView) || !active(allCharacter))
					{
						continue;
					}
					int viewID = ((MonoBehaviourPun)allCharacter).photonView.ViewID;
					live.Add(viewID);
					if (!effects.TryGetValue(viewID, out var value) || (Object)(object)value.character != (Object)(object)allCharacter)
					{
						if (value != null && Object.op_Implicit((Object)(object)value.node))
						{
							Object.Destroy((Object)(object)value.node);
						}
						Effect effect = new Effect();
						effect.character = allCharacter;
						effect.node = new GameObject("Thunderfen_StiffSparks_" + viewID);
						effect.arcs = new StiffSparkRibbon[6];
						value = effect;
						for (int i = 0; i < value.arcs.Length; i++)
						{
							GameObject val = new GameObject("Spark_" + i);
							val.transform.SetParent(value.node.transform, false);
							StiffSparkRibbon stiffSparkRibbon = val.AddComponent<StiffSparkRibbon>();
							stiffSparkRibbon.sharedMaterial = material;
							stiffSparkRibbon.widthMultiplier = (((Object)(object)allCharacter == (Object)(object)Character.localCharacter) ? 0.012f : 0.045f);
							stiffSparkRibbon.startColor = new Color(0.78f, 0.66f, 1f, 1f);
							stiffSparkRibbon.endColor = new Color(0.36f, 0.68f, 1f, 0.6f);
							value.arcs[i] = stiffSparkRibbon;
						}
						effects[viewID] = value;
						Started++;
					}
					int num = (int)(Time.unscaledTime * 14f);
					Random random = new Random((viewID * 397) ^ num);
					Bodypart[] array = allCharacter.refs.ragdoll.partList.Where((Bodypart p) => Object.op_Implicit((Object)(object)p)).ToArray();
					Camera val2 = Camera.main;
					if (!Object.op_Implicit((Object)(object)val2))
					{
						val2 = ((IEnumerable<Camera>)Camera.allCameras).FirstOrDefault((Func<Camera, bool>)((Camera view) => Object.op_Implicit((Object)(object)view) && ((Behaviour)view).enabled && !view.orthographic && !Object.op_Implicit((Object)(object)view.targetTexture)));
					}
					for (int num2 = 0; num2 < value.arcs.Length; num2++)
					{
						Vector3 val3;
						Vector3 val4;
						if ((Object)(object)allCharacter == (Object)(object)Character.localCharacter && Object.op_Implicit((Object)(object)val2))
						{
							float num3 = ((num2 % 2 != 0) ? 1 : (-1));
							float num4 = -0.18f + (float)(num2 / 2) * 0.11f;
							val3 = ((Component)val2).transform.TransformPoint(new Vector3(num3 * 0.24f, num4, 0.48f));
							val4 = ((Component)val2).transform.TransformPoint(new Vector3(num3 * 0.32f, num4 + 0.075f, 0.52f));
						}
						else
						{
							val3 = ((array.Length != 0) ? array[random.Next(array.Length)].transform.position : allCharacter.Center);
							val4 = ((array.Length != 0) ? array[random.Next(array.Length)].transform.position : (allCharacter.Center + Vector3.up * 0.4f));
							Vector3 val5 = val4 - val3;
							if (((Vector3)(ref val5)).sqrMagnitude > 2.25f)
							{
								val4 = Vector3.Lerp(val3, val4, 0.6f);
							}
						}
						Vector3[] array2 = (Vector3[])(object)new Vector3[6];
						for (int num5 = 0; num5 < array2.Length; num5++)
						{
							float num6 = (float)num5 / (float)(array2.Length - 1);
							Vector3 val6 = new Vector3((float)random.NextDouble() - 0.5f, (float)random.NextDouble() - 0.5f, (float)random.NextDouble() - 0.5f) * (((Object)(object)allCharacter == (Object)(object)Character.localCharacter) ? 0.035f : 0.18f);
							array2[num5] = Vector3.Lerp(val3, val4, num6) + ((num5 == 0 || num5 == array2.Length - 1) ? Vector3.zero : val6);
						}
						value.arcs[num2].SetPositions(array2);
					}
				}
			}
			int[] array3 = effects.Keys.Where((int id) => !live.Contains(id)).ToArray();
			foreach (int key in array3)
			{
				if (Object.op_Implicit((Object)(object)effects[key].node))
				{
					Object.Destroy((Object)(object)effects[key].node);
				}
				effects.Remove(key);
			}
		}

		public void Dispose()
		{
			foreach (Effect value in effects.Values)
			{
				if (Object.op_Implicit((Object)(object)value.node))
				{
					Object.Destroy((Object)(object)value.node);
				}
			}
			effects.Clear();
			if (Object.op_Implicit((Object)(object)material))
			{
				Object.Destroy((Object)(object)material);
			}
			material = null;
		}
	}
	public sealed class StiffSparkRibbon : MonoBehaviour
	{
		public float widthMultiplier = 0.03f;

		public Color startColor = Color.white;

		public Color endColor = Color.white;

		public int positionCount;

		private Mesh mesh;

		private MeshRenderer renderer;

		private Vector3[] points;

		private Vector3[] vertices;

		private Color[] colors;

		private Vector2[] uv;

		private int[] indices;

		private static int cameraFrame = -1;

		private static Camera view;

		public Material sharedMaterial
		{
			set
			{
				if (Object.op_Implicit((Object)(object)renderer))
				{
					((Renderer)renderer).sharedMaterial = value;
				}
			}
		}

		public int sortingOrder
		{
			set
			{
				if (Object.op_Implicit((Object)(object)renderer))
				{
					((Renderer)renderer).sortingOrder = value;
				}
			}
		}

		private void Awake()
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Expected O, but got Unknown
			mesh = new Mesh
			{
				name = "Thunderfen_StiffRibbon"
			};
			mesh.MarkDynamic();
			((Component)this).gameObject.AddComponent<MeshFilter>().sharedMesh = mesh;
			renderer = ((Component)this).gameObject.AddComponent<MeshRenderer>();
			((Renderer)renderer).shadowCastingMode = (ShadowCastingMode)0;
			((Renderer)renderer).receiveShadows = false;
		}

		public void SetPositions(Vector3[] value)
		{
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b8: 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_00bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e2: 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_00e8: 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_00ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
			points = (Vector3[])value.Clone();
			positionCount = points.Length;
			int num = (points.Length - 1) * 4;
			if (vertices == null || vertices.Length != num)
			{
				vertices = (Vector3[])(object)new Vector3[num];
				colors = (Color[])(object)new Color[num];
				uv = (Vector2[])(object)new Vector2[num];
				indices = new int[(points.Length - 1) * 6];
				for (int i = 0; i < points.Length - 1; i++)
				{
					int num2 = i * 4;
					int num3 = i * 6;
					uv[num2] = (uv[num2 + 2] = new Vector2(0.5f, 0f));
					uv[num2 + 1] = (uv[num2 + 3] = new Vector2(0.5f, 1f));
					indices[num3] = num2;
					indices[num3 + 1] = num2 + 2;
					indices[num3 + 2] = num2 + 1;
					indices[num3 + 3] = num2 + 1;
					indices[num3 + 4] = num2 + 2;
					indices[num3 + 5] = num2 + 3;
				}
				mesh.Clear();
				mesh.vertices = vertices;
				mesh.triangles = indices;
				mesh.uv = uv;
			}
		}

		private void LateUpdate()
		{
			//IL_00de: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fa: 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_010b: Unknown result type (might be due to invalid IL or missing references)
			//IL_010d: Unknown result type (might be due to invalid IL or missing references)
			//IL_010f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0111: Unknown result type (might be due to invalid IL or missing references)
			//IL_0120: Unknown result type (might be due to invalid IL or missing references)
			//IL_0125: Unknown result type (might be due to invalid IL or missing references)
			//IL_0127: Unknown result type (might be due to invalid IL or missing references)
			//IL_0129: Unknown result type (might be due to invalid IL or missing references)
			//IL_0133: Unknown result type (might be due to invalid IL or missing references)
			//IL_0138: Unknown result type (might be due to invalid IL or missing references)
			//IL_013d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0142: Unknown result type (might be due to invalid IL or missing references)
			//IL_0146: Unknown result type (might be due to invalid IL or missing references)
			//IL_014b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0172: Unknown result type (might be due to invalid IL or missing references)
			//IL_0180: Unknown result type (might be due to invalid IL or missing references)
			//IL_0185: Unknown result type (might be due to invalid IL or missing references)
			//IL_0197: Unknown result type (might be due to invalid IL or missing references)
			//IL_0199: Unknown result type (might be due to invalid IL or missing references)
			//IL_019b: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01de: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0202: Unknown result type (might be due to invalid IL or missing references)
			//IL_021a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0220: Unknown result type (might be due to invalid IL or missing references)
			//IL_0234: Unknown result type (might be due to invalid IL or missing references)
			//IL_0239: Unknown result type (might be due to invalid IL or missing references)
			//IL_023a: Unknown result type (might be due to invalid IL or missing references)
			//IL_023c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0241: Unknown result type (might be due to invalid IL or missing references)
			//IL_0243: Unknown result type (might be due to invalid IL or missing references)
			//IL_025d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0263: Unknown result type (might be due to invalid IL or missing references)
			//IL_0279: Unknown result type (might be due to invalid IL or missing references)
			//IL_027e: Unknown result type (might be due to invalid IL or missing references)
			//IL_027f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0281: Unknown result type (might be due to invalid IL or missing references)
			//IL_0286: Unknown result type (might be due to invalid IL or missing references)
			//IL_0288: Unknown result type (might be due to invalid IL or missing references)
			//IL_016b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0170: Unknown result type (might be due to invalid IL or missing references)
			if (points == null || points.Length < 2)
			{
				return;
			}
			if (cameraFrame != Time.frameCount)
			{
				cameraFrame = Time.frameCount;
				view = Camera.main;
				if (!Object.op_Implicit((Object)(object)view))
				{
					Camera[] allCameras = Camera.allCameras;
					Camera[] array = allCameras;
					foreach (Camera val in array)
					{
						if (Object.op_Implicit((Object)(object)val) && ((Behaviour)val).enabled)
						{
							view = val;
							break;
						}
					}
				}
			}
			if (!Object.op_Implicit((Object)(object)view))
			{
				((Renderer)renderer).enabled = false;
				return;
			}
			((Renderer)renderer).enabled = true;
			Matrix4x4 worldToLocalMatrix = ((Component)this).transform.worldToLocalMatrix;
			for (int j = 0; j < points.Length - 1; j++)
			{
				Vector3 val2 = points[j];
				Vector3 val3 = points[j + 1];
				Vector3 val4 = Vector3.Cross(val3 - val2, ((Component)view).transform.position - (val2 + val3) * 0.5f);
				Vector3 val5 = ((Vector3)(ref val4)).normalized;
				if (((Vector3)(ref val5)).sqrMagnitude < 0.0001f)
				{
					val5 = ((Component)view).transform.right;
				}
				val5 *= widthMultiplier * 0.5f;
				int num = j * 4;
				vertices[num] = ((Matrix4x4)(ref worldToLocalMatrix)).MultiplyPoint3x4(val2 - val5);
				vertices[num + 1] = ((Matrix4x4)(ref worldToLocalMatrix)).MultiplyPoint3x4(val2 + val5);
				vertices[num + 2] = ((Matrix4x4)(ref worldToLocalMatrix)).MultiplyPoint3x4(val3 - val5);
				vertices[num + 3] = ((Matrix4x4)(ref worldToLocalMatrix)).MultiplyPoint3x4(val3 + val5);
				colors[num] = (colors[num + 1] = Color.Lerp(startColor, endColor, (float)j / (float)(points.Length - 1)));
				colors[num + 2] = (colors[num + 3] = Color.Lerp(startColor, endColor, (float)(j + 1) / (float)(points.Length - 1)));
			}
			mesh.vertices = vertices;
			mesh.colors = colors;
			mesh.RecalculateBounds();
		}

		private void OnEnable()
		{
			if (Object.op_Implicit((Object)(object)renderer))
			{
				((Renderer)renderer).enabled = true;
			}
		}

		private void OnDisable()
		{
			if (Object.op_Implicit((Object)(object)renderer))
			{
				((Renderer)renderer).enabled = false;
			}
		}

		private void OnDestroy()
		{
			if (Object.op_Implicit((Object)(object)mesh))
			{
				Object.Destroy((Object)(object)mesh);
			}
		}
	}
	public static class StaticBurstRules
	{
		public const float ChargedThreshold = 0.3f;

		public const float BaseForce = 400f;

		public const float MaximumForce = 1200f;

		public const double OfferLifetime = 8.0;

		public const double LaunchLifetime = 5.0;

		public static bool Charge(float q)
		{
			return !float.IsNaN(q) && !float.IsInfinity(q) && q >= 0f && q <= 1f;
		}

		public static bool Charged(float q)
		{
			return Charge(q) && q > 0.3f;
		}

		public static bool Eligible(float a, float b)
		{
			return Charge(a) && Charge(b) && a > 0f && b > 0f && (Charged(a) || Charged(b));
		}

		public static float Injury(float own)
		{
			return Charge(own) ? (own / 3f) : 0f;
		}

		public static float Force(float highest)
		{
			return 400f + 800f * Math.Max(0f, Math.Min(1f, (highest - 0.3f) / 0.7f));
		}

		public static bool Fresh(double then, double now, double age)
		{
			return !double.IsNaN(then) && !double.IsInfinity(then) && then <= now + 0.5 && now - then <= age;
		}
	}
	[Serializable]
	public sealed class StaticBurstEvent
	{
		public string token;

		public string protocol;

		public string epoch;

		public int a;

		public int b;

		public int actorA;

		public int actorB;

		public int phase;

		public float qa;

		public float qb;

		public float x;

		public float y;

		public float z;

		public float dx;

		public float dy;

		public float dz;

		public double createdAt;

		public double committedAt;

		public double lastSent;

		public bool Valid(string expectedProtocol, string expectedEpoch)
		{
			Guid result;
			return protocol == expectedProtocol && epoch == expectedEpoch && !string.IsNullOrEmpty(epoch) && Guid.TryParseExact(token, "N", out result) && a > 0 && b > 0 && a != b && actorA > 0 && actorB > 0 && actorA != actorB && (phase == 0 || phase == 1) && StaticBurstRules.Charge(qa) && StaticBurstRules.Charge(qb) && new float[6] { x, y, z, dx, dy, dz }.All((float f) => !float.IsNaN(f) && !float.IsInfinity(f) && Math.Abs(f) < 1000000f);
		}
	}
	[Serializable]
	public sealed class StaticBurstLedger
	{
		public string protocol;

		public string epoch;

		public StaticBurstEvent[] records = new StaticBurstEvent[0];
	}
	[Serializable]
	public sealed class StaticBurstReceipt
	{
		public string token;

		public float consumed;

		public bool launched;
	}
	[Serializable]
	public sealed class StaticBurstOwnerState
	{
		public string protocol;

		public string epoch;

		public int view;

		public int actor;

		public StaticBurstReceipt[] receipts = new StaticBurstReceipt[0];
	}
	public sealed class StaticBurstReceipts
	{
		private readonly List<StaticBurstReceipt> records = new List<StaticBurstReceipt>();

		public int Count => records.Count;

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

		public bool Consume(string token, float own, out StaticBurstReceipt receipt)
		{
			receipt = records.FirstOrDefault((StaticBurstReceipt r) => r.token == token);
			if (receipt != null || !StaticBurstRules.Charge(own))
			{
				return false;
			}
			if (records.Count >= 64)
			{
				StaticBurstReceipt staticBurstReceipt = records.FirstOrDefault((StaticBurstReceipt r) => r.launched);
				if (staticBurstReceipt == null)
				{
					return false;
				}
				records.Remove(staticBurstReceipt);
			}
			receipt = new StaticBurstReceipt
			{
				token = token,
				consumed = own
			};
			records.Add(receipt);
			return true;
		}

		public bool Launch(string token, out StaticBurstReceipt receipt)
		{
			receipt = records.FirstOrDefault((StaticBurstReceipt r) => r.token == token);
			if (receipt == null || receipt.launched)
			{
				return false;
			}
			receipt.launched = true;
			return true;
		}

		public StaticBurstOwnerState Snapshot(string protocol, string epoch, int view, int actor)
		{
			return new StaticBurstOwnerState
			{
				protocol = protocol,
				epoch = epoch,
				view = view,
				actor = actor,
				receipts = records.Select((StaticBurstReceipt r) => new StaticBurstReceipt
				{
					token = r.token,
					consumed = r.consumed,
					launched = r.launched
				}).ToArray()
			};
		}

		public static StaticBurstReceipt Find(StaticBurstOwnerState state, string protocol, string epoch, int view, int actor, string token)
		{
			if (state == null || state.protocol != protocol || state.epoch != epoch || state.view != view || state.actor != actor || state.receipts == null || state.receipts.Length > 64)
			{
				return null;
			}
			return state.receipts.FirstOrDefault((StaticBurstReceipt r) => r != null && r.token == token && StaticBurstRules.Charge(r.consumed));
		}
	}
	public static class StaticBurstContact
	{
		public const float Skin = 0.04f;

		public static bool Touching(Collider[] a, Collider[] b, out Vector3 point)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: 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_0089: 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_00b6: 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_00d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_0133: Unknown result type (might be due to invalid IL or missing references)
			//IL_0138: Unknown result type (might be due to invalid IL or missing references)
			//IL_013c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0141: Unknown result type (might be due to invalid IL or missing references)
			//IL_0146: Unknown result type (might be due to invalid IL or missing references)
			//IL_014a: 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_0151: 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_00ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0101: Unknown result type (might be due to invalid IL or missing references)
			//IL_0106: 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)
			//IL_010f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0114: Unknown result type (might be due to invalid IL or missing references)
			//IL_011e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0123: Unknown result type (might be due to invalid IL or missing references)
			//IL_015b: Unknown result type (might be due to invalid IL or missing references)
			//IL_015d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0162: Unknown result type (might be due to invalid IL or missing references)
			//IL_0166: Unknown result type (might be due to invalid IL or missing references)
			//IL_0168: Unknown result type (might be due to invalid IL or missing references)
			//IL_016d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0181: Unknown result type (might be due to invalid IL or missing references)
			//IL_0183: Unknown result type (might be due to invalid IL or missing references)
			//IL_0185: Unknown result type (might be due to invalid IL or missing references)
			//IL_018a: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b8: Unknown result type (might be due to invalid IL or missing references)
			point = Vector3.zero;
			if (a == null || b == null)
			{
				return false;
			}
			Vector3 val3 = default(Vector3);
			float num = default(float);
			foreach (Collider val in a)
			{
				if (!Usable(val))
				{
					continue;
				}
				foreach (Collider val2 in b)
				{
					if (!Usable(val2))
					{
						continue;
					}
					Bounds bounds = val.bounds;
					((Bounds)(ref bounds)).Expand(0.08f);
					if (((Bounds)(ref bounds)).Intersects(val2.bounds))
					{
						Bounds bounds2;
						if (Physics.ComputePenetration(val, ((Component)val).transform.position, ((Component)val).transform.rotation, val2, ((Component)val2).transform.position, ((Component)val2).transform.rotation, ref val3, ref num))
						{
							bounds2 = val2.bounds;
							Vector3 val4 = val.ClosestPoint(((Bounds)(ref bounds2)).center);
							bounds2 = val.bounds;
							point = (val4 + val2.ClosestPoint(((Bounds)(ref bounds2)).center)) * 0.5f;
							return true;
						}
						bounds2 = val2.bounds;
						Vector3 val5 = val.ClosestPoint(((Bounds)(ref bounds2)).center);
						Vector3 val6 = val2.ClosestPoint(val5);
						for (int k = 0; k < 3; k++)
						{
							val5 = val.ClosestPoint(val6);
							val6 = val2.ClosestPoint(val5);
						}
						Vector3 val7 = val5 - val6;
						if (((Vector3)(ref val7)).sqrMagnitude <= 0.0016f)
						{
							point = (val5 + val6) * 0.5f;
							return true;
						}
					}
				}
			}
			return false;
		}

		private static bool Usable(Collider c)
		{
			int result;
			if (Object.op_Implicit((Object)(object)c) && c.enabled && ((Component)c).gameObject.activeInHierarchy && !c.isTrigger)
			{
				if (!(c is BoxCollider) && !(c is CapsuleCollider) && !(c is SphereCollider))
				{
					MeshCollider val = (MeshCollider)(object)((c is MeshCollider) ? c : null);
					result = ((val != null && val.convex) ? 1 : 0);
				}
				else
				{
					result = 1;
				}
			}
			else
			{
				result = 0;
			}
			return (byte)result != 0;
		}
	}
	public sealed class StaticBodyContacts
	{
		private sealed class Body
		{
			public Character character;

			public Collider[] colliders;

			public float refresh;
		}

		private readonly Dictionary<int, Body> bodies = new Dictionary<int, Body>();

		private Collider[] Parts(Character c)
		{
			int viewID = ((MonoBehaviourPun)c).photonView.ViewID;
			if (!bodies.TryGetValue(viewID, out var value) || (Object)(object)value.character != (Object)(object)c || Time.unscaledTime >= value.refresh)
			{
				HashSet<Rigidbody> rigs = new HashSet<Rigidbody>(from p in c.refs.ragdoll.partList
					where Object.op_Implicit((Object)(object)p) && Object.op_Implicit((Object)(object)p.Rig)
					select p.Rig);
				value = new Body
				{
					character = c,
					refresh = Time.unscaledTime + 0.5f,
					colliders = (from col in ((Component)c).GetComponentsInChildren<Collider>(true)
						where Object.op_Implicit((Object)(object)col) && Object.op_Implicit((Object)(object)col.attachedRigidbody) && rigs.Contains(col.attachedRigidbody)
						select col).ToArray()
				};
				bodies[viewID] = value;
			}
			return value.colliders;
		}

		public bool Touching(Character a, Character b, out Vector3 point)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_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)
			point = Vector3.zero;
			if (Object.op_Implicit((Object)(object)a) && Object.op_Implicit((Object)(object)b) && a.refs != null && b.refs != null && Object.op_Implicit((Object)(object)a.refs.ragdoll) && Object.op_Implicit((Object)(object)b.refs.ragdoll))
			{
				Vector3 val = a.Center - b.Center;
				if (!(((Vector3)(ref val)).sqrMagnitude > 25f))
				{
					return StaticBurstContact.Touching(Parts(a), Parts(b), out point);
				}
			}
			return false;
		}

		public void Clear()
		{
			bodies.Clear();
		}
	}
	public sealed class StaticElectricVisuals : IDisposable
	{
		private sealed class Aura
		{
			public Character character;

			public GameObject node;

			public StiffSparkRibbon[] arcs;

			public Spark[] sparks;
		}

		private sealed class Spark
		{
			public int cycle = -1;

			public Vector3 origin;

			public Vector3 direction;

			public float reach;

			public readonly Vector3[] offsets = (Vector3[])(object)new Vector3[5];
		}

		private sealed class Pop
		{
			public GameObject node;

			public StiffSparkRibbon[] arcs;

			public Vector3 point;

			public Vector3 axis;

			public float begin;

			public float highest;

			public int seed;
		}

		private readonly Dictionary<int, Aura> auras = new Dictionary<int, Aura>();

		private readonly List<Pop> pops = new List<Pop>();

		private Material material;

		private float nextFind;

		public int Auras => auras.Count;

		public int Bursts => pops.Count;

		public int Started { get; private set; }

		private bool Ensure()
		{
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL o

plugins/ThunderfenGroundcover/PoisonForestGroundcover.dll

Decompiled a week ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security.Cryptography;
using System.Text;
using BepInEx;
using Microsoft.CodeAnalysis;
using PoisonForestGeneration;
using PoisonForestSolo;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.SceneManagement;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyVersion("0.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace PoisonForestGroundcover
{
	public sealed class PlantMesh
	{
		public string name;

		public float[] positions;

		public float[] normals;

		public float[] uv;

		public float[] colors;

		public int[] triangles;
	}
	public sealed class Plant
	{
		public int kind;

		public int zone;

		public float x;

		public float y;

		public float z;

		public float sx;

		public float sy;

		public float sz;

		public float yaw;

		public bool Fern => kind == 1 || kind == 2;
	}
	public sealed class CoverCatalog
	{
		public int seed;

		public PlantMesh[] meshes;

		public Plant[] plants;

		private static float[] Floats(BinaryReader r, int n)
		{
			float[] array = new float[n];
			for (int i = 0; i < n; i++)
			{
				array[i] = r.ReadSingle();
				if (float.IsNaN(array[i]) || float.IsInfinity(array[i]))
				{
					throw new InvalidDataException("Nonfinite plant data");
				}
			}
			return array;
		}

		public static CoverCatalog Read(byte[] bytes)
		{
			if (bytes == null || bytes.Length > 5000000)
			{
				throw new InvalidDataException("Groundcover catalog size");
			}
			using BinaryReader binaryReader = new BinaryReader(new MemoryStream(bytes), Encoding.UTF8);
			if (new string(binaryReader.ReadChars(4)) != "PFG1" || binaryReader.ReadInt32() != 1)
			{
				throw new InvalidDataException("Groundcover signature");
			}
			CoverCatalog coverCatalog = new CoverCatalog
			{
				seed = binaryReader.ReadInt32()
			};
			int num = binaryReader.ReadInt32();
			if (num != 2)
			{
				throw new InvalidDataException("Expected grass and fern meshes");
			}
			coverCatalog.meshes = new PlantMesh[num];
			for (int i = 0; i < num; i++)
			{
				int num2 = binaryReader.ReadInt32();
				if (num2 < 1 || num2 > 80)
				{
					throw new InvalidDataException("Plant mesh name size");
				}
				byte[] array = binaryReader.ReadBytes(num2);
				if (array.Length != num2)
				{
					throw new EndOfStreamException();
				}
				int num3 = binaryReader.ReadInt32();
				int num4 = binaryReader.ReadInt32();
				if (num3 < 4 || num3 > 1000 || num4 < 3 || num4 > 12000 || num4 % 3 != 0)
				{
					throw new InvalidDataException("Plant mesh dimensions");
				}
				PlantMesh plantMesh = new PlantMesh();
				plantMesh.name = Encoding.UTF8.GetString(array);
				plantMesh.positions = Floats(binaryReader, num3 * 3);
				plantMesh.normals = Floats(binaryReader, num3 * 3);
				plantMesh.uv = Floats(binaryReader, num3 * 2);
				plantMesh.colors = Floats(binaryReader, num3 * 4);
				plantMesh.triangles = new int[num4];
				PlantMesh plantMesh2 = plantMesh;
				for (int j = 0; j < num4; j++)
				{
					plantMesh2.triangles[j] = binaryReader.ReadInt32();
					if (plantMesh2.triangles[j] < 0 || plantMesh2.triangles[j] >= num3)
					{
						throw new InvalidDataException("Plant mesh index");
					}
				}
				coverCatalog.meshes[i] = plantMesh2;
			}
			int num5 = binaryReader.ReadInt32();
			if (num5 < 1 || num5 > 16000)
			{
				throw new InvalidDataException("Plant population size");
			}
			coverCatalog.plants = new Plant[num5];
			for (int k = 0; k < num5; k++)
			{
				int num6 = binaryReader.ReadInt32();
				int num7 = binaryReader.ReadInt32();
				float[] array2 = Floats(binaryReader, 7);
				Plant plant = new Plant
				{
					kind = num6,
					zone = num7,
					x = array2[0],
					y = array2[1],
					z = array2[2],
					sx = array2[3],
					sy = array2[4],
					sz = array2[5],
					yaw = array2[6]
				};
				if (num6 < 0 || num6 > 3 || num7 < 0 || num7 > 1 || plant.sx <= 0f || plant.sx > 2f || plant.sy <= 0f || plant.sy > 2f || plant.sz <= 0f || plant.sz > 2f || Math.Abs(plant.x) > 160f || plant.z < 120f || plant.z > 820f || plant.y < -100f || plant.y > 500f)
				{
					throw new InvalidDataException("Plant placement outside approved bounds");
				}
				coverCatalog.plants[k] = plant;
			}
			if (binaryReader.BaseStream.Position != binaryReader.BaseStream.Length)
			{
				throw new InvalidDataException("Trailing groundcover data");
			}
			return coverCatalog;
		}
	}
	[BepInPlugin("local.peak.poisonforest.groundcover", "Thunderfen Groundcover", "1.0.0")]
	[BepInDependency("local.peak.poisonforest.solo", "0.6.0")]
	public sealed class GroundcoverPlugin : BaseUnityPlugin
	{
		[Serializable]
		private sealed class State
		{
			public string version = "1.0.0";

			public string utc;

			public string error;

			public string message;

			public string root;

			public bool ready;

			public bool active;

			public bool complete;

			public bool terrainChanged = false;

			public int planned;

			public int processed;

			public int placed;

			public int grass;

			public int ferns;

			public int batches;

			public int activeBatches;

			public int colliders;

			public int rejectedSupport;

			public int rejectedSlope;

			public int rejectedHeight;

			public double buildSeconds;

			public string[] missingMaterials;

			public string[] nativeMaterials;
		}

		private sealed class Batch
		{
			public int kind;

			public Vector3 origin;

			public readonly List<Vector3> vertices = new List<Vector3>();

			public readonly List<Vector3> normals = new List<Vector3>();

			public readonly List<Vector2> uv = new List<Vector2>();

			public readonly List<Color> colors = new List<Color>();

			public readonly List<int> triangles = new List<int>();
		}

		public const string Version = "1.0.0";

		private int dataRevision = -1;

		private CoverCatalog data;

		private Transform terrain;

		private Transform group;

		private Coroutine worker;

		private bool ready;

		private bool complete;

		private string folder;

		private string error;

		private string message = "Waiting for Poison Forest";

		private float nextScan;

		private float nextReport;

		private float nextCull;

		private int processed;

		private int placed;

		private int grass;

		private int ferns;

		private int rejectedSupport;

		private int rejectedSlope;

		private int rejectedHeight;

		private int activeBatches;

		private double buildSeconds;

		private readonly List<Mesh> ownedMeshes = new List<Mesh>();

		private readonly List<Material> materials = new List<Material>();

		private readonly List<MeshRenderer> renderers = new List<MeshRenderer>();

		private readonly HashSet<Collider> supports = new HashSet<Collider>();

		private readonly RaycastHit[] hits = (RaycastHit[])(object)new RaycastHit[256];

		private string[] missingMaterials = new string[0];

		private float rayTop;

		private float rayBottom;

		private int groundMask;

		private readonly Stopwatch timer = new Stopwatch();

		private bool Active => Object.op_Implicit((Object)(object)terrain) && ((Component)terrain).gameObject.activeInHierarchy;

		private void Awake()
		{
			folder = Path.Combine(Application.persistentDataPath, "PoisonForestGroundcover");
			Directory.CreateDirectory(folder);
			try
			{
				data = CoverCatalog.Read(GeneratedData.Read("groundcover-catalog.bin"));
				ready = true;
				((BaseUnityPlugin)this).Logger.LogInfo((object)("Groundcover ready: " + data.plants.Length + " seeded cosmetic grass/fern candidates; time-sliced batches; no colliders or new hotkeys."));
			}
			catch (Exception e)
			{
				Fail(e);
			}
		}

		private static string Sha(byte[] bytes)
		{
			using SHA256 sHA = SHA256.Create();
			return BitConverter.ToString(sHA.ComputeHash(bytes)).Replace("-", "");
		}

		private Transform FindTerrain()
		{
			//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)
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Expected O, but got Unknown
			Scene sceneByName = SceneManager.GetSceneByName("WilIsland");
			if (!((Scene)(ref sceneByName)).IsValid() || !((Scene)(ref sceneByName)).isLoaded)
			{
				return null;
			}
			GameObject val = ((IEnumerable<GameObject>)((Scene)(ref sceneByName)).GetRootGameObjects()).FirstOrDefault((Func<GameObject, bool>)((GameObject g) => ((Object)g).name == "Map"));
			if (!Object.op_Implicit((Object)(object)val))
			{
				return null;
			}
			Transform val2 = val.transform.Find("Global");
			if (!Object.op_Implicit((Object)(object)val2))
			{
				return null;
			}
			foreach (Transform item in val2)
			{
				Transform val3 = item;
				if (((Object)val3).name.Contains("first-ridge"))
				{
					Transform val4 = ((IEnumerable<Transform>)((Component)val3).GetComponentsInChildren<Transform>(true)).FirstOrDefault((Func<Transform, bool>)((Transform n) => ((Object)n).name == "PF_HybridTerrain" && Object.op_Implicit((Object)(object)n.parent) && ((Object)n.parent).name == "RootsTerrain"));
					if (Object.op_Implicit((Object)(object)val4))
					{
						return val4;
					}
				}
			}
			return null;
		}

		private void Update()
		{
			//IL_01bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e9: Unknown result type (might be due to invalid IL or missing references)
			if (!ready)
			{
				return;
			}
			try
			{
				if (RunData.Pending)
				{
					if (Object.op_Implicit((Object)(object)group) || worker != null)
					{
						Clear();
					}
					return;
				}
				if (dataRevision != RunData.Revision)
				{
					Clear();
					data = CoverCatalog.Read(GeneratedData.Read("groundcover-catalog.bin"));
					dataRevision = RunData.Revision;
					nextScan = 0f;
				}
				if (Time.unscaledTime >= nextScan)
				{
					nextScan = Time.unscaledTime + 1f;
					Transform val = FindTerrain();
					if ((Object)(object)val != (Object)(object)terrain)
					{
						Clear();
						terrain = val;
					}
					if (!Active)
					{
						if (Object.op_Implicit((Object)(object)group) || worker != null)
						{
							Clear();
						}
						message = "Waiting for Poison Forest";
					}
					else if (!Object.op_Implicit((Object)(object)group) && worker == null)
					{
						if (PrepareMaterials())
						{
							worker = ((MonoBehaviour)this).StartCoroutine(SafeBuild());
						}
						else
						{
							message = "Waiting for native foliage materials: " + string.Join(", ", missingMaterials);
						}
					}
				}
				if (Object.op_Implicit((Object)(object)group) && Object.op_Implicit((Object)(object)terrain))
				{
					group.localPosition = terrain.localPosition;
					group.localRotation = terrain.localRotation;
					group.localScale = terrain.localScale;
				}
				if (renderers.Count > 0 && Time.unscaledTime >= nextCull)
				{
					nextCull = Time.unscaledTime + 0.35f;
					Cull();
				}
				Report();
			}
			catch (Exception e)
			{
				Fail(e);
			}
		}

		private bool PrepareMaterials()
		{
			//IL_0124: Unknown result type (might be due to invalid IL or missing references)
			//IL_0129: Unknown result type (might be due to invalid IL or missing references)
			//IL_0151: Expected O, but got Unknown
			//IL_0296: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0246: Unknown result type (might be due to invalid IL or missing references)
			//IL_024b: Unknown result type (might be due to invalid IL or missing references)
			//IL_025d: Unknown result type (might be due to invalid IL or missing references)
			if (materials.Count == 4)
			{
				return true;
			}
			Material[] source = Resources.FindObjectsOfTypeAll<Material>();
			string[] names = new string[4] { "M_Grass_GD 1", "Fern", "Fern Dark purple", "M_Grass_GD 1" };
			List<string> list = new List<string>();
			Material[] array = (Material[])(object)new Material[4];
			int i;
			for (i = 0; i < 4; i++)
			{
				array[i] = ((IEnumerable<Material>)source).FirstOrDefault((Func<Material, bool>)((Material m) => Object.op_Implicit((Object)(object)m) && ((Object)m).name == names[i] && Object.op_Implicit((Object)(object)m.shader) && m.shader.isSupported));
				if (!Object.op_Implicit((Object)(object)array[i]))
				{
					list.Add(names[i]);
				}
			}
			missingMaterials = list.Distinct().ToArray();
			if (list.Count > 0)
			{
				return false;
			}
			for (int num = 0; num < 4; num++)
			{
				Material val = new Material(array[num])
				{
					name = "PF_Groundcover_" + num + "_" + ((Object)array[num]).name
				};
				val.DisableKeyword("_USECLOSEDITHER_ON");
				val.DisableKeyword("_USEPLAYERSQUISH_ON");
				if (val.HasProperty("_UseCloseDither"))
				{
					val.SetFloat("_UseCloseDither", 0f);
				}
				if (val.HasProperty("_UsePlayerSquish"))
				{
					val.SetFloat("_UsePlayerSquish", 0f);
				}
				if (val.HasProperty("_PlayerPushAmount"))
				{
					val.SetFloat("_PlayerPushAmount", 0f);
				}
				if (val.HasProperty("_Cull"))
				{
					val.SetFloat("_Cull", 0f);
				}
				if (num == 0 || num == 3)
				{
					string[] array2 = new string[2] { "_VertexWindAmount", "_WindAmount" };
					foreach (string text in array2)
					{
						if (val.HasProperty(text))
						{
							Vector4 vector = val.GetVector(text);
							vector.y = 0f;
							val.SetVector(text, vector);
						}
					}
				}
				if (num == 3)
				{
					SetColor(val, "_TopColor", new Color(0.38f, 0.29f, 0.45f));
					SetColor(val, "_TopColorSecondary", new Color(0.48f, 0.35f, 0.55f));
				}
				materials.Add(val);
				((BaseUnityPlugin)this).Logger.LogInfo((object)("Groundcover native material: " + ((Object)array[num]).name + " / " + ((Object)val.shader).name));
			}
			return true;
		}

		private static void SetColor(Material m, string key, Color value)
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			if (m.HasProperty(key))
			{
				value.a = m.GetColor(key).a;
				m.SetColor(key, value);
			}
		}

		private IEnumerator SafeBuild()
		{
			IEnumerator build = Build();
			while (true)
			{
				bool more;
				try
				{
					more = build.MoveNext();
				}
				catch (Exception ex)
				{
					Exception e = ex;
					Fail(e);
					yield break;
				}
				if (!more)
				{
					break;
				}
				yield return build.Current;
			}
			worker = null;
		}

		private IEnumerator Build()
		{
			yield return (object)new WaitForSeconds(0.6f);
			if (!Active)
			{
				yield break;
			}
			GameObject o = new GameObject("PF_Groundcover");
			o.layer = 2;
			group = o.transform;
			group.SetParent(terrain.parent, false);
			group.localPosition = terrain.localPosition;
			group.localRotation = terrain.localRotation;
			group.localScale = terrain.localScale;
			supports.Clear();
			Bounds bounds = new Bounds(terrain.position, Vector3.zero);
			bool first = true;
			groundMask = 0;
			Collider[] componentsInChildren = ((Component)terrain).GetComponentsInChildren<Collider>(false);
			foreach (Collider collider in componentsInChildren)
			{
				if (!collider.isTrigger)
				{
					supports.Add(collider);
					groundMask |= 1 << ((Component)collider).gameObject.layer;
					if (first)
					{
						bounds = collider.bounds;
						first = false;
					}
					else
					{
						((Bounds)(ref bounds)).Encapsulate(collider.bounds);
					}
				}
			}
			if (first)
			{
				throw new Exception("No accepted terrain collision for groundcover support");
			}
			rayTop = ((Bounds)(ref bounds)).max.y + 2f;
			rayBottom = ((Bounds)(ref bounds)).min.y - 2f;
			Batch pending = null;
			string pendingKey = null;
			timer.Restart();
			WorkBudget slice = new WorkBudget(() => timer.Elapsed.TotalMilliseconds, 4.0);
			message = "Placing ground vegetation";
			for (int i2 = 0; i2 < data.plants.Length; i2++)
			{
				if (!Active || !Object.op_Implicit((Object)(object)group))
				{
					yield break;
				}
				Plant p = data.plants[i2];
				processed++;
				if (Support(p, out var point, out var normal))
				{
					string key = (int)Math.Floor(p.x / 28f) + ":" + (int)Math.Floor(p.z / 28f) + ":" + p.kind;
					if (pendingKey != key)
					{
						if (pending != null)
						{
							CreateBatch(pending);
						}
						pending = new Batch
						{
							kind = p.kind,
							origin = new Vector3(((float)Math.Floor(p.x / 28f) + 0.5f) * 28f, point.y, ((float)Math.Floor(p.z / 28f) + 0.5f) * 28f)
						};
						pendingKey = key;
					}
					if (Append(pending, p, point, normal))
					{
						placed++;
						if (p.Fern)
						{
							ferns++;
						}
						else
						{
							grass++;
						}
					}
				}
				if (slice.Expired)
				{
					yield return null;
					slice.Resume();
				}
			}
			if (pending != null && Object.op_Implicit((Object)(object)group))
			{
				CreateBatch(pending);
			}
			timer.Stop();
			buildSeconds = timer.Elapsed.TotalSeconds;
			complete = true;
			message = "Clustered grass and Roots ferns ready";
			((BaseUnityPlugin)this).Logger.LogInfo((object)("Groundcover built: " + grass + " grass clumps, " + ferns + " ferns / " + renderers.Count + " batches in " + buildSeconds.ToString("F2") + "s (spread over frames). No new collision or shelter."));
			Cull();
			Report(force: true);
		}

		private bool Support(Plant p, out Vector3 position, out Vector3 normal)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0143: Unknown result type (might be due to invalid IL or missing references)
			//IL_0148: Unknown result type (might be due to invalid IL or missing references)
			//IL_0153: 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_015d: Unknown result type (might be due to invalid IL or missing references)
			//IL_016b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0170: Unknown result type (might be due to invalid IL or missing references)
			//IL_0175: Unknown result type (might be due to invalid IL or missing references)
			//IL_0179: Unknown result type (might be due to invalid IL or missing references)
			//IL_017e: Unknown result type (might be due to invalid IL or missing references)
			position = Vector3.zero;
			normal = Vector3.up;
			Vector3 val = terrain.TransformPoint(new Vector3(p.x, p.y, p.z));
			Vector3 val2 = default(Vector3);
			((Vector3)(ref val2))..ctor(val.x, rayTop, val.z);
			int num = Physics.RaycastNonAlloc(val2, Vector3.down, hits, rayTop - rayBottom, groundMask, (QueryTriggerInteraction)1);
			if (num >= hits.Length)
			{
				rejectedSupport++;
				return false;
			}
			float num2 = float.PositiveInfinity;
			int num3 = -1;
			for (int i = 0; i < num; i++)
			{
				if (supports.Contains(((RaycastHit)(ref hits[i])).collider) && ((RaycastHit)(ref hits[i])).distance < num2)
				{
					num2 = ((RaycastHit)(ref hits[i])).distance;
					num3 = i;
				}
			}
			if (num3 < 0)
			{
				rejectedSupport++;
				return false;
			}
			RaycastHit val3 = hits[num3];
			position = terrain.InverseTransformPoint(((RaycastHit)(ref val3)).point);
			Vector3 val4 = terrain.InverseTransformDirection(((RaycastHit)(ref val3)).normal);
			normal = ((Vector3)(ref val4)).normalized;
			if (normal.y < 0.82f)
			{
				rejectedSlope++;
				return false;
			}
			if (Mathf.Abs(position.y - p.y) > (float)((p.zone == 0) ? 3 : 7))
			{
				rejectedHeight++;
				return false;
			}
			position.y += (p.Fern ? 0.04f : 0.025f);
			return true;
		}

		private bool Append(Batch b, Plant p, Vector3 position, Vector3 normal)
		{
			//IL_000e: 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_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: 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_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_0145: Unknown result type (might be due to invalid IL or missing references)
			//IL_014a: Unknown result type (might be due to invalid IL or missing references)
			//IL_014b: Unknown result type (might be due to invalid IL or missing references)
			//IL_014d: Unknown result type (might be due to invalid IL or missing references)
			//IL_014f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0154: Unknown result type (might be due to invalid IL or missing references)
			//IL_0159: Unknown result type (might be due to invalid IL or missing references)
			//IL_015e: Unknown result type (might be due to invalid IL or missing references)
			//IL_017f: 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)
			//IL_018c: 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_0204: Unknown result type (might be due to invalid IL or missing references)
			//IL_0205: Unknown result type (might be due to invalid IL or missing references)
			//IL_0213: Unknown result type (might be due to invalid IL or missing references)
			//IL_0221: Unknown result type (might be due to invalid IL or missing references)
			//IL_022f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0234: Unknown result type (might be due to invalid IL or missing references)
			//IL_0239: 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_0266: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a9: Unknown result type (might be due to invalid IL or missing references)
			PlantMesh plantMesh = data.meshes[p.Fern ? 1 : 0];
			Quaternion val = (p.Fern ? Quaternion.Slerp(Quaternion.identity, Quaternion.FromToRotation(Vector3.up, normal), 0.5f) : Quaternion.identity);
			Quaternion val2 = val * Quaternion.Euler(0f, p.yaw, 0f);
			Vector3 val3 = default(Vector3);
			((Vector3)(ref val3))..ctor(p.sx, p.sy, p.sz);
			int num = plantMesh.positions.Length / 3;
			Vector3[] array = (Vector3[])(object)new Vector3[num];
			float[] array2 = null;
			if (!p.Fern)
			{
				array2 = GroundFit.Grass(plantMesh, p, position.x, position.y, position.z, (float x, float z) => ColumnSupport(new Vector3(x, position.y, z), out var point) ? new float?(point.y) : ((float?)null));
				if (array2 == null)
				{
					rejectedSupport++;
					return false;
				}
			}
			Vector3 val4 = default(Vector3);
			for (int num2 = 0; num2 < num; num2++)
			{
				((Vector3)(ref val4))..ctor(plantMesh.positions[num2 * 3], plantMesh.positions[num2 * 3 + 1], plantMesh.positions[num2 * 3 + 2]);
				Vector3 val5 = position + val2 * Vector3.Scale(val4, val3);
				if (!p.Fern)
				{
					val5.y = array2[num2];
				}
				array[num2] = val5 - b.origin;
			}
			int count = b.vertices.Count;
			Vector3 val6 = default(Vector3);
			for (int num3 = 0; num3 < num; num3++)
			{
				((Vector3)(ref val6))..ctor(plantMesh.normals[num3 * 3], plantMesh.normals[num3 * 3 + 1], plantMesh.normals[num3 * 3 + 2]);
				b.vertices.Add(array[num3]);
				List<Vector3> normals = b.normals;
				Vector3 val7 = val2 * new Vector3(val6.x / p.sx, val6.y / p.sy, val6.z / p.sz);
				normals.Add(((Vector3)(ref val7)).normalized);
				b.uv.Add(new Vector2(plantMesh.uv[num3 * 2], plantMesh.uv[num3 * 2 + 1]));
				b.colors.Add(new Color(plantMesh.colors[num3 * 4], plantMesh.colors[num3 * 4 + 1], plantMesh.colors[num3 * 4 + 2], plantMesh.colors[num3 * 4 + 3]));
			}
			int[] triangles = plantMesh.triangles;
			foreach (int num5 in triangles)
			{
				b.triangles.Add(count + num5);
			}
			return true;
		}

		private bool ColumnSupport(Vector3 local, out Vector3 point)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: 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_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0106: Unknown result type (might be due to invalid IL or missing references)
			//IL_010b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0110: Unknown result type (might be due to invalid IL or missing references)
			point = Vector3.zero;
			Vector3 val = terrain.TransformPoint(local);
			int num = Physics.RaycastNonAlloc(new Vector3(val.x, rayTop, val.z), Vector3.down, hits, rayTop - rayBottom, groundMask, (QueryTriggerInteraction)1);
			if (num >= hits.Length)
			{
				return false;
			}
			float num2 = float.PositiveInfinity;
			int num3 = -1;
			for (int i = 0; i < num; i++)
			{
				if (supports.Contains(((RaycastHit)(ref hits[i])).collider) && ((RaycastHit)(ref hits[i])).distance < num2)
				{
					num2 = ((RaycastHit)(ref hits[i])).distance;
					num3 = i;
				}
			}
			if (num3 < 0)
			{
				return false;
			}
			point = terrain.InverseTransformPoint(((RaycastHit)(ref hits[num3])).point);
			return true;
		}

		private void CreateBatch(Batch b)
		{
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Expected O, but got Unknown
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Expected O, but got Unknown
			if (b.vertices.Count != 0)
			{
				GameObject val = new GameObject("PF_GroundcoverChunk_" + renderers.Count.ToString("D3") + "_" + b.kind);
				val.layer = 2;
				val.transform.SetParent(group, false);
				val.transform.localPosition = b.origin;
				Mesh val2 = new Mesh
				{
					name = ((Object)val).name,
					indexFormat = (IndexFormat)(b.vertices.Count > 65535)
				};
				ownedMeshes.Add(val2);
				val2.SetVertices(b.vertices);
				val2.SetNormals(b.normals);
				val2.SetColors(b.colors);
				val2.SetUVs(0, b.uv);
				val2.SetUVs(1, b.uv);
				val2.SetTriangles(b.triangles, 0);
				val2.RecalculateBounds();
				val.AddComponent<MeshFilter>().sharedMesh = val2;
				MeshRenderer val3 = val.AddComponent<MeshRenderer>();
				((Renderer)val3).sharedMaterial = materials[b.kind];
				((Renderer)val3).shadowCastingMode = (ShadowCastingMode)0;
				((Renderer)val3).receiveShadows = true;
				renderers.Add(val3);
			}
		}

		private void Cull()
		{
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: 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_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			Camera main = Camera.main;
			if (!Object.op_Implicit((Object)(object)main))
			{
				return;
			}
			activeBatches = 0;
			foreach (MeshRenderer renderer in renderers)
			{
				if (Object.op_Implicit((Object)(object)renderer))
				{
					float num = (((Object)(object)((Renderer)renderer).sharedMaterial == (Object)(object)materials[1] || (Object)(object)((Renderer)renderer).sharedMaterial == (Object)(object)materials[2]) ? 120 : 80);
					Bounds bounds = ((Renderer)renderer).bounds;
					Vector3 val = ((Bounds)(ref bounds)).ClosestPoint(((Component)main).transform.position) - ((Component)main).transform.position;
					((Renderer)renderer).enabled = ((Vector3)(ref val)).sqrMagnitude < num * num;
					if (((Renderer)renderer).enabled)
					{
						activeBatches++;
					}
				}
			}
		}

		private void Clear()
		{
			if (worker != null)
			{
				((MonoBehaviour)this).StopCoroutine(worker);
				worker = null;
			}
			if (Object.op_Implicit((Object)(object)group))
			{
				Object.Destroy((Object)(object)((Component)group).gameObject);
			}
			group = null;
			foreach (Mesh ownedMesh in ownedMeshes)
			{
				if (Object.op_Implicit((Object)(object)ownedMesh))
				{
					Object.Destroy((Object)(object)ownedMesh);
				}
			}
			ownedMeshes.Clear();
			renderers.Clear();
			foreach (Material material in materials)
			{
				if (Object.op_Implicit((Object)(object)material))
				{
					Object.Destroy((Object)(object)material);
				}
			}
			materials.Clear();
			supports.Clear();
			processed = (placed = (grass = (ferns = (rejectedSupport = (rejectedSlope = (rejectedHeight = (activeBatches = 0)))))));
			complete = false;
			buildSeconds = 0.0;
		}

		private void Fail(Exception e)
		{
			error = e.ToString();
			ready = false;
			((BaseUnityPlugin)this).Logger.LogError((object)error);
			Clear();
			Report(force: true);
		}

		private void Report(bool force = false)
		{
			if (!RuntimeDiagnostics.PeriodicSnapshots || (!force && Time.unscaledTime < nextReport))
			{
				return;
			}
			nextReport = Time.unscaledTime + 2f;
			try
			{
				string path = Path.Combine(folder, "groundcover-runtime-state.json");
				State obj = new State
				{
					utc = DateTime.UtcNow.ToString("O"),
					error = error,
					message = message,
					root = (Object.op_Implicit((Object)(object)terrain) ? ((Object)terrain).name : null),
					ready = ready,
					active = Active,
					complete = complete
				};
				CoverCatalog coverCatalog = data;
				obj.planned = ((coverCatalog != null) ? coverCatalog.plants.Length : 0);
				obj.processed = processed;
				obj.placed = placed;
				obj.grass = grass;
				obj.ferns = ferns;
				obj.batches = renderers.Count;
				obj.activeBatches = activeBatches;
				obj.colliders = (Object.op_Implicit((Object)(object)group) ? ((Component)group).GetComponentsInChildren<Collider>().Length : 0);
				obj.rejectedSupport = rejectedSupport;
				obj.rejectedSlope = rejectedSlope;
				obj.rejectedHeight = rejectedHeight;
				obj.buildSeconds = buildSeconds;
				obj.missingMaterials = missingMaterials;
				obj.nativeMaterials = (from m in materials
					where Object.op_Implicit((Object)(object)m)
					select ((Object)m).name + " / " + ((Object)m.shader).name).ToArray();
				File.WriteAllText(path, JsonUtility.ToJson((object)obj, true));
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)ex.Message);
			}
		}

		private void OnDestroy()
		{
			ready = false;
			Clear();
		}
	}
	public sealed class WorkBudget
	{
		private readonly Func<double> clock;

		private readonly double milliseconds;

		private double start;

		public bool Expired => clock() - start >= milliseconds;

		public WorkBudget(Func<double> clock, double milliseconds)
		{
			this.clock = clock;
			this.milliseconds = milliseconds;
			Resume();
		}

		public void Resume()
		{
			start = clock();
		}
	}
	public static class GroundFit
	{
		public const float Clearance = 0.025f;

		public static float[] Grass(PlantMesh mesh, Plant p, float rootX, float rootY, float rootZ, Func<float, float, float?> sample)
		{
			int num = mesh.positions.Length / 3;
			float[] array = new float[num];
			double num2 = (double)p.yaw * Math.PI / 180.0;
			float num3 = (float)Math.Cos(num2);
			float num4 = (float)Math.Sin(num2);
			Dictionary<(float, float), float> dictionary = new Dictionary<(float, float), float>();
			dictionary[(0f, 0f)] = rootY;
			for (int i = 0; i < num; i++)
			{
				float num5 = mesh.positions[i * 3];
				float num6 = mesh.positions[i * 3 + 1];
				float num7 = mesh.positions[i * 3 + 2];
				(float, float) key = (num5, num7);
				if (!dictionary.TryGetValue(key, out var value))
				{
					float arg = rootX + num5 * p.sx * num3 + num7 * p.sz * num4;
					float arg2 = rootZ - num5 * p.sx * num4 + num7 * p.sz * num3;
					float? num8 = sample(arg, arg2);
					if (!num8.HasValue || float.IsNaN(num8.Value) || float.IsInfinity(num8.Value) || Math.Abs(num8.Value - rootY) > Math.Max(0.22f, p.sy * 0.65f))
					{
						return null;
					}
					value = (dictionary[key] = num8.Value + 0.025f);
				}
				array[i] = value + num6 * p.sy;
			}
			return array;
		}
	}
}

plugins/ThunderfenItems/PoisonForestItems.dll

Decompiled a week ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security.Cryptography;
using System.Text;
using BepInEx;
using ExitGames.Client.Photon;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Peak;
using Photon.Pun;
using Photon.Realtime;
using PoisonForest;
using PoisonForestCaveBugs;
using PoisonForestGeneration;
using PoisonForestLightning;
using PoisonForestNativeProps;
using PoisonForestSolo;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using Zorro.Core;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyVersion("0.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace ThunderfenItems
{
	public sealed class ChargeSlotView : MonoBehaviour
	{
		private InventoryItemUI ui;

		private ItemSlot slot;

		private Image background;

		private Image fill;

		private RectTransform bar;

		private Sprite fallbackSprite;

		public void Bind(InventoryItemUI owner, ItemSlot value)
		{
			ui = owner;
			slot = value;
			Refresh();
		}

		private void LateUpdate()
		{
			Refresh();
		}

		private void Build()
		{
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Expected O, but got Unknown
			//IL_00be: Unknown result type (might be due to invalid IL or missing references)
			//IL_0108: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Expected O, but got Unknown
			//IL_0124: Unknown result type (might be due to invalid IL or missing references)
			//IL_0130: Unknown result type (might be due to invalid IL or missing references)
			//IL_013c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0148: Unknown result type (might be due to invalid IL or missing references)
			//IL_0179: Unknown result type (might be due to invalid IL or missing references)
			//IL_0214: Unknown result type (might be due to invalid IL or missing references)
			//IL_0223: Unknown result type (might be due to invalid IL or missing references)
			RectTransform val = (RectTransform)(Object.op_Implicit((Object)(object)ui.fuelBar) ? /*isinst with value type is only supported in some contexts*/: null);
			GameObject val2 = new GameObject("Thunderfen_ChargeBar", new Type[3]
			{
				typeof(RectTransform),
				typeof(CanvasRenderer),
				typeof(Image)
			});
			bar = val2.GetComponent<RectTransform>();
			((Transform)bar).SetParent(Object.op_Implicit((Object)(object)val) ? ((Transform)val).parent : ((Component)ui).transform, false);
			background = val2.GetComponent<Image>();
			((Graphic)background).color = new Color(0.12f, 0.06f, 0.18f, 0.95f);
			((Graphic)background).raycastTarget = false;
			GameObject val3 = new GameObject("Charge", new Type[3]
			{
				typeof(RectTransform),
				typeof(CanvasRenderer),
				typeof(Image)
			});
			RectTransform component = val3.GetComponent<RectTransform>();
			((Transform)component).SetParent((Transform)(object)bar, false);
			component.anchorMin = Vector2.zero;
			component.anchorMax = Vector2.one;
			component.offsetMin = Vector2.zero;
			component.offsetMax = Vector2.zero;
			fill = val3.GetComponent<Image>();
			((Graphic)fill).color = new Color(0.68f, 0.3f, 1f, 1f);
			((Graphic)fill).raycastTarget = false;
			fill.type = (Type)3;
			fill.fillMethod = (FillMethod)0;
			fill.fillOrigin = 0;
			Sprite val4 = (Object.op_Implicit((Object)(object)ui.fuelBarFill) ? ui.fuelBarFill.sprite : null);
			if (!Object.op_Implicit((Object)(object)val4))
			{
				Texture2D whiteTexture = Texture2D.whiteTexture;
				fallbackSprite = Sprite.Create(whiteTexture, new Rect(0f, 0f, (float)((Texture)whiteTexture).width, (float)((Texture)whiteTexture).height), new Vector2(0.5f, 0.5f));
				val4 = fallbackSprite;
			}
			background.sprite = val4;
			fill.sprite = val4;
		}

		public void Refresh()
		{
			//IL_0244: Unknown result type (might be due to invalid IL or missing references)
			//IL_025f: Unknown result type (might be due to invalid IL or missing references)
			//IL_027a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0295: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a6: 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_016b: Unknown result type (might be due to invalid IL or missing references)
			//IL_017e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0191: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_01dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_020e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0213: Unknown result type (might be due to invalid IL or missing references)
			//IL_0220: Unknown result type (might be due to invalid IL or missing references)
			//IL_0225: Unknown result type (might be due to invalid IL or missing references)
			ItemSlot obj = slot;
			Item item = ((obj != null) ? obj.prefab : null);
			bool flag = Object.op_Implicit((Object)(object)ui) && ItemData.IsCustom(item);
			IconLibrary iconLibrary = ItemsTrial.Instance?.Icons;
			if (flag && iconLibrary != null && Object.op_Implicit((Object)(object)ui.icon))
			{
				Texture2D val = iconLibrary.Get(ItemData.KindOf(item), ItemRules.Full(ItemData.Charge(slot.data)));
				if (Object.op_Implicit((Object)(object)val))
				{
					ui.icon.texture = (Texture)(object)val;
				}
			}
			if (!flag || !ItemRules.ManualCharge(ItemData.KindOf(item)))
			{
				if (Object.op_Implicit((Object)(object)bar))
				{
					((Component)bar).gameObject.SetActive(false);
				}
				return;
			}
			if (!Object.op_Implicit((Object)(object)bar))
			{
				Build();
			}
			((Component)bar).gameObject.SetActive(true);
			RectTransform val2 = (RectTransform)(Object.op_Implicit((Object)(object)ui.fuelBar) ? /*isinst with value type is only supported in some contexts*/: null);
			if (Object.op_Implicit((Object)(object)val2))
			{
				bar.anchorMin = val2.anchorMin;
				bar.anchorMax = val2.anchorMax;
				bar.pivot = val2.pivot;
				bar.sizeDelta = val2.sizeDelta;
				((Transform)bar).localRotation = ((Transform)val2).localRotation;
				((Transform)bar).localScale = ((Transform)val2).localScale;
				bar.anchoredPosition = val2.anchoredPosition;
				Rect rect = val2.rect;
				float num = Mathf.Max(3f, ((Rect)(ref rect)).height);
				if (ui.fuelBar.activeSelf)
				{
					RectTransform obj2 = bar;
					obj2.anchoredPosition += Vector2.up * (num + 3f);
				}
			}
			else
			{
				bar.anchorMin = new Vector2(0.12f, 0.05f);
				bar.anchorMax = new Vector2(0.88f, 0.05f);
				bar.pivot = new Vector2(0.5f, 0f);
				bar.sizeDelta = new Vector2(0f, 4f);
				bar.anchoredPosition = Vector2.zero;
			}
			fill.fillAmount = Mathf.Clamp01(ItemData.Charge(slot.data) / 0.3f);
		}

		public void Clear()
		{
			slot = null;
			if (Object.op_Implicit((Object)(object)bar))
			{
				((Component)bar).gameObject.SetActive(false);
			}
		}

		private void OnDestroy()
		{
			if (Object.op_Implicit((Object)(object)bar))
			{
				Object.Destroy((Object)(object)((Component)bar).gameObject);
			}
			if (Object.op_Implicit((Object)(object)fallbackSprite))
			{
				Object.Destroy((Object)(object)fallbackSprite);
			}
		}
	}
	[HarmonyPatch(typeof(InventoryItemUI), "SetItem", new Type[] { typeof(ItemSlot) })]
	internal static class ItemSlotPresentationPatch
	{
		private static void Postfix(InventoryItemUI __instance, ItemSlot __0)
		{
			ChargeSlotView chargeSlotView = ((Component)__instance).GetComponent<ChargeSlotView>();
			if (Object.op_Implicit((Object)(object)chargeSlotView) || (__0 != null && ItemData.IsCustom(__0.prefab)))
			{
				if (!Object.op_Implicit((Object)(object)chargeSlotView))
				{
					chargeSlotView = ((Component)__instance).gameObject.AddComponent<ChargeSlotView>();
				}
				chargeSlotView.Bind(__instance, __0);
			}
		}
	}
	[HarmonyPatch(typeof(InventoryItemUI), "Clear", new Type[] { })]
	internal static class ItemSlotClearPatch
	{
		private static void Postfix(InventoryItemUI __instance)
		{
			((Component)__instance).GetComponent<ChargeSlotView>()?.Clear();
		}
	}
	public static class ChestItemRotation
	{
		internal static Spawner Current;

		public static Quaternion Upward(Quaternion chest)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			return chest;
		}
	}
	[HarmonyPatch(typeof(Spawner), "SpawnItems", new Type[] { typeof(List<Transform>) })]
	internal static class ChestSpawnScope
	{
		private static void Prefix(Spawner __instance, out Spawner __state)
		{
			__state = ChestItemRotation.Current;
			OwnedNativeProp component = ((Component)__instance).GetComponent<OwnedNativeProp>();
			ChestItemRotation.Current = ((__instance is Luggage && Object.op_Implicit((Object)(object)component)) ? __instance : null);
		}

		private static Exception Finalizer(Exception __exception, Spawner __state)
		{
			ChestItemRotation.Current = __state;
			return __exception;
		}
	}
	[HarmonyPatch(typeof(PhotonNetwork), "InstantiateItemRoom", new Type[]
	{
		typeof(string),
		typeof(Vector3),
		typeof(Quaternion),
		typeof(bool)
	})]
	internal static class ChestTakoyakiRotation
	{
		private static void Prefix(string __0, ref Quaternion __2)
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			Spawner current = ChestItemRotation.Current;
			if (Object.op_Implicit((Object)(object)current) && __0 == ItemData.Prefab(Kind.Takoyaki))
			{
				__2 = ChestItemRotation.Upward(((Component)current).transform.rotation);
			}
		}
	}
	[HarmonyPatch(typeof(Spawner), "OffsetSpawn", new Type[] { typeof(Item) })]
	internal static class ChestTakoyakiPose
	{
		private static void Postfix(Spawner __instance, Item __0)
		{
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: 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_0066: Unknown result type (might be due to invalid IL or missing references)
			if (Object.op_Implicit((Object)(object)__instance) && !((Object)(object)ChestItemRotation.Current != (Object)(object)__instance) && ItemData.IsCustom(__0) && ItemData.KindOf(__0) == Kind.Takoyaki)
			{
				Quaternion rotation = ChestItemRotation.Upward(((Component)__instance).transform.rotation);
				__0.transform.rotation = rotation;
				if (Object.op_Implicit((Object)(object)__0.rig))
				{
					__0.rig.rotation = rotation;
				}
			}
		}
	}
	public sealed class ChestLoot : IDisposable
	{
		public const SpawnPool Ordinary = (SpawnPool)(-62101);

		public const SpawnPool Epic = (SpawnPool)(-62102);

		private readonly PrefabFactory factory;

		private Dictionary<SpawnPool, Dictionary<ushort, int>> cache;

		private Dictionary<ushort, int> normal;

		private Dictionary<ushort, int> epic;

		private Dictionary<ushort, int> normalSource;

		private Dictionary<ushort, int> epicSource;

		public int Draws { get; private set; }

		public int Fallbacks { get; private set; }

		public ChestLoot(PrefabFactory factory)
		{
			this.factory = factory;
		}

		public bool TryDraw(Spawner spawner, int count, bool repeat, out List<GameObject> result)
		{
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Invalid comparison between Unknown and I4
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a8: Invalid comparison between Unknown and I4
			//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f0: Invalid comparison between Unknown and I4
			//IL_00fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_0102: Unknown result type (might be due to invalid IL or missing references)
			//IL_014b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0152: Invalid comparison between Unknown and I4
			result = null;
			if (!(spawner is Luggage) || !SharedWorld.Ready || !SharedWorld.Authority)
			{
				return false;
			}
			OwnedNativeProp component = ((Component)spawner).GetComponent<OwnedNativeProp>();
			if (!Object.op_Implicit((Object)(object)component) || component.epoch != SharedWorld.Epoch || string.IsNullOrEmpty(component.site) || (!component.site.StartsWith("world:", StringComparison.Ordinal) && !component.site.StartsWith("camp:", StringComparison.Ordinal)))
			{
				return false;
			}
			if ((int)spawner.spawnPool != 2048 && (int)spawner.spawnPool != 16384)
			{
				return false;
			}
			try
			{
				if (!factory.Prepare())
				{
					throw new InvalidOperationException("Item prefabs not ready");
				}
				Ensure();
				SpawnPool val = (SpawnPool)(((int)spawner.spawnPool == 16384) ? (-62102) : (-62101));
				result = LootData.GetRandomItems(val, count, repeat, spawner.fallbackSpawn);
				Draws++;
				ItemsTrial.Event("chest-loot", "site=" + component.site + " epic=" + ((int)val == -62102) + " count=" + result.Count + " ids=" + string.Join(",", result.Select((GameObject o) => o.GetComponent<Item>().itemID.ToString()).ToArray()));
				return true;
			}
			catch (Exception ex)
			{
				Fallbacks++;
				ItemsTrial.Event("chest-loot-fallback", "site=" + component.site + " " + ex.Message);
				return false;
			}
		}

		private void Ensure()
		{
			if (LootData.AllSpawnWeightData == null)
			{
				LootData.PopulateLootData();
			}
			Dictionary<SpawnPool, Dictionary<ushort, int>> allSpawnWeightData = LootData.AllSpawnWeightData;
			Dictionary<ushort, int> dictionary = allSpawnWeightData[(SpawnPool)2048];
			Dictionary<ushort, int> dictionary2 = allSpawnWeightData[(SpawnPool)16384];
			if (cache != allSpawnWeightData || dictionary != normalSource || dictionary2 != epicSource || !allSpawnWeightData.TryGetValue((SpawnPool)(-62101), out var value) || value != normal || !allSpawnWeightData.TryGetValue((SpawnPool)(-62102), out var value2) || value2 != epic)
			{
				if ((allSpawnWeightData.TryGetValue((SpawnPool)(-62101), out var value3) && value3 != normal) || (allSpawnWeightData.TryGetValue((SpawnPool)(-62102), out var value4) && value4 != epic))
				{
					throw new InvalidOperationException("Private Thunderfen loot key collision");
				}
				Dictionary<ushort, Item>.ValueCollection values = SingletonAsset<ItemDatabase>.Instance.itemLookup.Values;
				Item val = values.Single((Item i) => Object.op_Implicit((Object)(object)i) && ((Object)i).name == "Lantern");
				Item val2 = values.Single((Item i) => Object.op_Implicit((Object)(object)i) && ((Object)i).name == "ScoutCookies");
				Dictionary<ushort, int> dictionary3 = new Dictionary<ushort, int>(dictionary);
				Dictionary<ushort, int> dictionary4 = new Dictionary<ushort, int>(dictionary2);
				for (int num = 62101; num <= 62106; num++)
				{
					dictionary3.Remove((ushort)num);
					dictionary4.Remove((ushort)num);
				}
				dictionary3.Remove(val.itemID);
				dictionary3.Remove(val2.itemID);
				dictionary3[ItemData.Id(Kind.Takoyaki)] = 15;
				dictionary3[ItemData.Id(Kind.ColdlightLantern)] = 20;
				dictionary3[ItemData.Id(Kind.StormOrb)] = 20;
				dictionary3[ItemData.Id(Kind.Milk)] = 15;
				dictionary4[ItemData.Id(Kind.StormOrb)] = 20;
				Dispose();
				cache = allSpawnWeightData;
				normalSource = dictionary;
				epicSource = dictionary2;
				normal = dictionary3;
				epic = dictionary4;
				allSpawnWeightData[(SpawnPool)(-62101)] = normal;
				allSpawnWeightData[(SpawnPool)(-62102)] = epic;
			}
		}

		public void Dispose()
		{
			if (cache != null)
			{
				if (cache.TryGetValue((SpawnPool)(-62101), out var value) && value == normal)
				{
					cache.Remove((SpawnPool)(-62101));
				}
				if (cache.TryGetValue((SpawnPool)(-62102), out var value2) && value2 == epic)
				{
					cache.Remove((SpawnPool)(-62102));
				}
			}
			cache = null;
		}
	}
	[HarmonyPatch(typeof(Spawner), "GetObjectsToSpawn", new Type[]
	{
		typeof(int),
		typeof(bool)
	})]
	internal static class ChestLootPatch
	{
		private static bool Prefix(Spawner __instance, int __0, bool __1, ref List<GameObject> __result)
		{
			ItemsTrial instance = ItemsTrial.Instance;
			if (!Object.op_Implicit((Object)(object)instance) || !instance.ChestLootEnabled || instance.Chests == null || !instance.Chests.TryDraw(__instance, __0, __1, out var result))
			{
				return true;
			}
			__result = result;
			return false;
		}

		private unsafe static void Postfix(Spawner __instance, List<GameObject> __result, bool __runOriginal)
		{
			if (!(__instance is Luggage))
			{
				return;
			}
			try
			{
				Dictionary<SpawnPool, Dictionary<ushort, int>> allSpawnWeightData = LootData.AllSpawnWeightData;
				ItemsTrial.Event("chest-selection", "chest=" + ((Object)__instance).name + " nativeRan=" + __runOriginal + " owned=" + Object.op_Implicit((Object)(object)((Component)__instance).GetComponent<OwnedNativeProp>()) + " mode=" + ((object)Unsafe.As<SpawnMode, SpawnMode>(ref __instance.spawnMode)/*cast due to .constrained prefix*/).ToString() + " pool=" + ((object)Unsafe.As<SpawnPool, SpawnPool>(ref __instance.spawnPool)/*cast due to .constrained prefix*/).ToString() + " selected=" + ((__result == null) ? "null" : __result.Count.ToString()) + " prefabs=" + ((__result == null) ? "none" : string.Join(",", from o in __result.Take(8)
					select Object.op_Implicit((Object)(object)o) ? ((Object)o).name : "null")) + " nativeTables=" + ((allSpawnWeightData == null) ? "null" : string.Join(",", allSpawnWeightData.Keys.Select((SpawnPool k) => ((object)(*(SpawnPool*)(&k))/*cast due to .constrained prefix*/).ToString()))));
			}
			catch
			{
			}
		}
	}
	public static class EyeBeamResources
	{
		public const string ShaderName = "FirstRidge/CampfireParticle";

		public static Shader FindShader(Func<string, Shader> find, Func<Shader[]> loaded)
		{
			return find("FirstRidge/CampfireParticle") ?? ((IEnumerable<Shader>)loaded()).FirstOrDefault((Func<Shader, bool>)((Shader s) => Object.op_Implicit((Object)(object)s) && ((Object)s).name == "FirstRidge/CampfireParticle"));
		}

		public static bool GameCamera(Camera c)
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Invalid comparison between Unknown and I4
			return Object.op_Implicit((Object)(object)c) && ((Behaviour)c).enabled && ((Component)c).gameObject.activeInHierarchy && (int)c.cameraType == 1 && !c.orthographic;
		}

		public static Camera FindCamera()
		{
			Camera main = Camera.main;
			if (GameCamera(main))
			{
				return main;
			}
			Camera result = null;
			float num = -1f;
			Camera[] allCameras = Camera.allCameras;
			foreach (Camera val in allCameras)
			{
				if (GameCamera(val))
				{
					float num2 = (float)val.pixelWidth * (float)val.pixelHeight * (Object.op_Implicit((Object)(object)val.targetTexture) ? 0.1f : 1f);
					if (num2 > num)
					{
						num = num2;
						result = val;
					}
				}
			}
			return result;
		}
	}
	public sealed class EyeBeams : IDisposable
	{
		private static readonly MethodInfo getHead = AccessTools.Method(typeof(Character), "GetBodypart", new Type[1] { typeof(BodypartType) }, (Type[])null);

		private const string Key = "TF_ItemEyes1";

		private readonly Dictionary<int, GameObject> lights = new Dictionary<int, GameObject>();

		private Character local;

		private double expires;

		private string epoch;

		private Material shaftMaterial;

		public int ObservedPlayers => lights.Count;

		public int VisibleShafts
		{
			get
			{
				int num = 0;
				foreach (GameObject value in lights.Values)
				{
					if (!Object.op_Implicit((Object)(object)value))
					{
						continue;
					}
					EyeBeamShaft[] componentsInChildren = value.GetComponentsInChildren<EyeBeamShaft>();
					foreach (EyeBeamShaft eyeBeamShaft in componentsInChildren)
					{
						if (((Component)eyeBeamShaft).GetComponent<Renderer>().enabled)
						{
							num++;
						}
					}
				}
				return num;
			}
		}

		public double Remaining => Math.Max(0.0, expires - PhotonNetwork.Time);

		public string RenderStatus => (!Object.op_Implicit((Object)(object)shaftMaterial)) ? "waiting-loaded-shader" : ((!Object.op_Implicit((Object)(object)EyeBeamResources.FindCamera())) ? "waiting-game-camera" : "ready");

		public EyeBeams()
		{
			RenderPipelineManager.beginCameraRendering += BeforeCamera;
		}

		private void BeforeCamera(ScriptableRenderContext context, Camera camera)
		{
			if (EyeBeamResources.GameCamera(camera))
			{
				TickForCamera(camera);
			}
		}

		public void Grant(Character c, float seconds)
		{
			if (Object.op_Implicit((Object)(object)c) && !((Object)(object)c != (Object)(object)Character.localCharacter) && ((MonoBehaviourPun)c).photonView.IsMine)
			{
				local = c;
				expires = ItemRules.RefreshExpiry(PhotonNetwork.Time, Math.Min(300f, seconds));
				epoch = SharedWorld.Epoch;
				Publish();
			}
		}

		private void Publish()
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Expected O, but got Unknown
			if (PhotonNetwork.LocalPlayer != null)
			{
				Player localPlayer = PhotonNetwork.LocalPlayer;
				Hashtable val = new Hashtable();
				((Dictionary<object, object>)(object)val).Add((object)"TF_ItemEyes1", (object)((!Object.op_Implicit((Object)(object)local) || !(expires > PhotonNetwork.Time)) ? null : new object[3]
				{
					((MonoBehaviourPun)local).photonView.ViewID,
					expires,
					epoch ?? ""
				}));
				localPlayer.SetCustomProperties(val, (Hashtable)null, (WebFlags)null);
			}
		}

		private void EnsureMaterial()
		{
			//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_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Expected O, but got Unknown
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			if (!Object.op_Implicit((Object)(object)shaftMaterial))
			{
				Shader val = EyeBeamResources.FindShader((Func<string, Shader>)Shader.Find, (Func<Shader[]>)Resources.FindObjectsOfTypeAll<Shader>);
				if (Object.op_Implicit((Object)(object)val) && val.isSupported)
				{
					shaftMaterial = new Material(val)
					{
						name = "Thunderfen_Owlberry_Beams_Private",
						hideFlags = (HideFlags)61,
						renderQueue = 3100
					};
					shaftMaterial.SetColor("_BaseColor", Color.white);
				}
			}
		}

		public void Tick()
		{
			TickForCamera(EyeBeamResources.FindCamera());
		}

		private void TickForCamera(Camera viewer)
		{
			//IL_0273: Unknown result type (might be due to invalid IL or missing references)
			//IL_027a: Expected O, but got Unknown
			//IL_03bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_0293: Unknown result type (might be due to invalid IL or missing references)
			//IL_029a: Expected O, but got Unknown
			//IL_02b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0320: Unknown result type (might be due to invalid IL or missing references)
			//IL_03e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_041c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0421: Unknown result type (might be due to invalid IL or missing references)
			//IL_0423: Unknown result type (might be due to invalid IL or missing references)
			//IL_0428: Unknown result type (might be due to invalid IL or missing references)
			//IL_0407: Unknown result type (might be due to invalid IL or missing references)
			//IL_040c: Unknown result type (might be due to invalid IL or missing references)
			//IL_04bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_04c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_04c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_04ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_04d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_04d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_04e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_04e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_04ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_0512: Unknown result type (might be due to invalid IL or missing references)
			//IL_0517: Unknown result type (might be due to invalid IL or missing references)
			//IL_051b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0520: Unknown result type (might be due to invalid IL or missing references)
			//IL_04ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_04b3: Unknown result type (might be due to invalid IL or missing references)
			if (Object.op_Implicit((Object)(object)local) && ((Object)(object)local != (Object)(object)Character.localCharacter || (Object)(object)local.data == (Object)null || local.data.dead || expires <= PhotonNetwork.Time || epoch != SharedWorld.Epoch))
			{
				local = null;
				expires = 0.0;
				Publish();
			}
			EnsureMaterial();
			HashSet<int> hashSet = new HashSet<int>();
			if (!PhotonNetwork.InRoom)
			{
				Clear();
				return;
			}
			foreach (Character allCharacter in Character.AllCharacters)
			{
				if (!Object.op_Implicit((Object)(object)allCharacter) || !Object.op_Implicit((Object)(object)((MonoBehaviourPun)allCharacter).photonView) || (Object)(object)allCharacter.data == (Object)null || allCharacter.data.dead || ((MonoBehaviourPun)allCharacter).photonView.Owner == null || ((MonoBehaviourPun)allCharacter).photonView.Owner.IsInactive)
				{
					continue;
				}
				int viewID = ((MonoBehaviourPun)allCharacter).photonView.ViewID;
				bool flag = (Object)(object)allCharacter == (Object)(object)local && expires > PhotonNetwork.Time;
				if ((Object)(object)allCharacter != (Object)(object)Character.localCharacter)
				{
					flag = ((MonoBehaviourPun)allCharacter).photonView.Owner.CustomProperties[(object)"TF_ItemEyes1"] is object[] array && array.Length == 3 && array[0] is int num && num == viewID && array[1] is double num2 && num2 > PhotonNetwork.Time && num2 <= PhotonNetwork.Time + 300.0 + 1.0 && array[2] as string == (SharedWorld.Epoch ?? "");
				}
				if (!flag)
				{
					continue;
				}
				hashSet.Add(viewID);
				if (!lights.TryGetValue(viewID, out var value) || !Object.op_Implicit((Object)(object)value))
				{
					value = new GameObject("TF_Owlberry_EyeBeams_" + viewID);
					for (int i = 0; i < 2; i++)
					{
						GameObject val = new GameObject((i == 0) ? "LeftEye" : "RightEye");
						val.transform.SetParent(value.transform, false);
						val.transform.localPosition = Vector3.zero;
						val.AddComponent<EyeBeamShaft>();
						Light val2 = val.AddComponent<Light>();
						val2.type = (LightType)0;
						val2.spotAngle = 65f;
						val2.innerSpotAngle = 35f;
						val2.range = 36f;
						val2.intensity = 1.6f;
						val2.color = new Color(0.82f, 0.94f, 0.72f);
						val2.shadows = (LightShadows)0;
						val2.renderMode = (LightRenderMode)1;
					}
					lights[viewID] = value;
				}
				object? obj = getHead?.Invoke(allCharacter, new object[1] { (object)(BodypartType)4 });
				Bodypart val3 = (Bodypart)((obj is Bodypart) ? obj : null);
				if (!Object.op_Implicit((Object)(object)val3))
				{
					value.SetActive(false);
					continue;
				}
				value.SetActive(true);
				Vector3 val4 = allCharacter.data.lookDirection;
				if ((Object)(object)allCharacter == (Object)(object)Character.localCharacter && Object.op_Implicit((Object)(object)viewer))
				{
					val4 = ((Component)viewer).transform.forward;
				}
				if (((Vector3)(ref val4)).sqrMagnitude < 0.001f)
				{
					val4 = ((Component)allCharacter).transform.forward;
				}
				value.transform.SetPositionAndRotation(val3.transform.position, Quaternion.LookRotation(val4, Vector3.up));
				Renderer[] componentsInChildren = ((Component)allCharacter).GetComponentsInChildren<Renderer>(true);
				int j;
				for (j = 0; j < 2; j++)
				{
					Transform child = value.transform.GetChild(j);
					Renderer val5 = Array.Find(componentsInChildren, (Renderer r) => Object.op_Implicit((Object)(object)r) && r.enabled && ((Component)r).gameObject.activeInHierarchy && ((Object)r).name == ((j == 0) ? "Eye Card L" : "Eye Card R"));
					Vector3 position;
					Bounds bounds;
					if (!Object.op_Implicit((Object)(object)val5))
					{
						position = val3.transform.TransformPoint(new Vector3((j == 0) ? (-0.18f) : 0.18f, 1f, 0.35f));
					}
					else
					{
						bounds = val5.bounds;
						position = ((Bounds)(ref bounds)).center + val4 * 0.008f;
					}
					child.position = position;
					child.rotation = Quaternion.LookRotation(val4, Vector3.up);
					EyeBeamShaft component = ((Component)child).GetComponent<EyeBeamShaft>();
					float startRadius;
					if (!Object.op_Implicit((Object)(object)val5))
					{
						startRadius = 0.055f;
					}
					else
					{
						bounds = val5.bounds;
						Vector3 size = ((Bounds)(ref bounds)).size;
						startRadius = Mathf.Clamp(((Vector3)(ref size)).magnitude * 0.22f, 0.025f, 0.1f);
					}
					component.StartRadius = startRadius;
					component.Draw(shaftMaterial, viewer, (Object)(object)allCharacter != (Object)(object)Character.localCharacter);
				}
			}
			List<int> list = new List<int>();
			foreach (KeyValuePair<int, GameObject> light in lights)
			{
				if (!hashSet.Contains(light.Key))
				{
					if (Object.op_Implicit((Object)(object)light.Value))
					{
						Object.Destroy((Object)(object)light.Value);
					}
					list.Add(light.Key);
				}
			}
			foreach (int item in list)
			{
				lights.Remove(item);
			}
		}

		private void Clear()
		{
			foreach (GameObject value in lights.Values)
			{
				if (Object.op_Implicit((Object)(object)value))
				{
					Object.Destroy((Object)(object)value);
				}
			}
			lights.Clear();
		}

		public void Dispose()
		{
			RenderPipelineManager.beginCameraRendering -= BeforeCamera;
			local = null;
			expires = 0.0;
			Publish();
			Clear();
			if (Object.op_Implicit((Object)(object)shaftMaterial))
			{
				Object.Destroy((Object)(object)shaftMaterial);
			}
		}
	}
	public sealed class EyeBeamShaft : MonoBehaviour
	{
		private const int Segments = 18;

		private const int Bands = 16;

		private readonly RaycastHit[] hits = (RaycastHit[])(object)new RaycastHit[64];

		private readonly Vector3[] vertices = (Vector3[])(object)new Vector3[323];

		private readonly Color[] colors = (Color[])(object)new Color[323];

		private readonly Vector2[] uv = (Vector2[])(object)new Vector2[323];

		private readonly int[] indices = new int[1728];

		private Mesh mesh;

		private MeshRenderer renderer;

		public float StartRadius = 0.055f;

		public float Length { get; private set; }

		private void Awake()
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Expected O, but got Unknown
			//IL_010b: 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)
			mesh = new Mesh
			{
				name = "Thunderfen_Owlberry_SoftCone"
			};
			mesh.MarkDynamic();
			((Component)this).gameObject.AddComponent<MeshFilter>().sharedMesh = mesh;
			renderer = ((Component)this).gameObject.AddComponent<MeshRenderer>();
			((Renderer)renderer).shadowCastingMode = (ShadowCastingMode)0;
			((Renderer)renderer).receiveShadows = false;
			for (int i = 0; i < 18; i++)
			{
				for (int j = 0; j < 16; j++)
				{
					int num = i * 17 + j;
					int num2 = (i * 16 + j) * 6;
					indices[num2] = num;
					indices[num2 + 1] = num + 16 + 1;
					indices[num2 + 2] = num + 1;
					indices[num2 + 3] = num + 1;
					indices[num2 + 4] = num + 16 + 1;
					indices[num2 + 5] = num + 16 + 2;
				}
			}
			for (int k = 0; k < uv.Length; k++)
			{
				uv[k] = new Vector2(0.5f, 0.5f);
			}
			mesh.vertices = vertices;
			mesh.triangles = indices;
			mesh.uv = uv;
		}

		public void Draw(Material material, Camera camera, bool visible)
		{
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: 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_014a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0151: Unknown result type (might be due to invalid IL or missing references)
			//IL_0156: Unknown result type (might be due to invalid IL or missing references)
			//IL_0157: Unknown result type (might be due to invalid IL or missing references)
			//IL_015e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0168: Unknown result type (might be due to invalid IL or missing references)
			//IL_016d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0172: Unknown result type (might be due to invalid IL or missing references)
			//IL_0177: Unknown result type (might be due to invalid IL or missing references)
			//IL_017c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0180: Unknown result type (might be due to invalid IL or missing references)
			//IL_0185: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0227: Unknown result type (might be due to invalid IL or missing references)
			//IL_0229: Unknown result type (might be due to invalid IL or missing references)
			//IL_022f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0234: Unknown result type (might be due to invalid IL or missing references)
			//IL_0239: Unknown result type (might be due to invalid IL or missing references)
			//IL_023e: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b3: Unknown result type (might be due to invalid IL or missing references)
			((Renderer)renderer).sharedMaterial = material;
			((Renderer)renderer).enabled = visible && Object.op_Implicit((Object)(object)material) && Object.op_Implicit((Object)(object)camera);
			if (!((Renderer)renderer).enabled)
			{
				return;
			}
			Vector3 position = ((Component)this).transform.position;
			Vector3 forward = ((Component)this).transform.forward;
			Length = 18f;
			int num = Physics.RaycastNonAlloc(position, forward, hits, Length, -5, (QueryTriggerInteraction)1);
			if (num == hits.Length)
			{
				Length = 0.1f;
			}
			else
			{
				for (int i = 0; i < num; i++)
				{
					RaycastHit val = hits[i];
					if (Object.op_Implicit((Object)(object)((RaycastHit)(ref val)).collider) && !Object.op_Implicit((Object)(object)((Component)((RaycastHit)(ref val)).collider).GetComponentInParent<Character>()) && !Object.op_Implicit((Object)(object)((Component)((RaycastHit)(ref val)).collider).GetComponentInParent<Bodypart>()) && !Object.op_Implicit((Object)(object)((Component)((RaycastHit)(ref val)).collider).GetComponentInParent<Item>()))
					{
						Length = Mathf.Min(Length, Mathf.Max(0.05f, ((RaycastHit)(ref val)).distance - 0.025f));
					}
				}
			}
			Vector3 val2 = Vector3.Cross(forward, ((Component)camera).transform.position - (position + forward * Length * 0.5f));
			Vector3 val3 = ((Vector3)(ref val2)).normalized;
			if (((Vector3)(ref val3)).sqrMagnitude < 0.001f)
			{
				val3 = ((Component)camera).transform.right;
			}
			Matrix4x4 worldToLocalMatrix = ((Component)this).transform.worldToLocalMatrix;
			for (int j = 0; j <= 18; j++)
			{
				float num2 = (float)j / 18f;
				float num3 = Length * num2;
				float num4 = StartRadius + num3 * 0.22f;
				Vector3 val4 = position + forward * num3;
				for (int k = 0; k <= 16; k++)
				{
					float num5 = (float)k / 16f * 2f - 1f;
					int num6 = j * 17 + k;
					vertices[num6] = ((Matrix4x4)(ref worldToLocalMatrix)).MultiplyPoint3x4(val4 + val3 * (num4 * num5));
					float num7 = 1f - Mathf.SmoothStep(0f, 1f, Mathf.Abs(num5));
					float num8 = (1f - Mathf.SmoothStep(0.6f, 1f, num2)) / (1f + num3 * 0.18f);
					colors[num6] = new Color(0.75f, 0.91f, 1f, 0.16f * num7 * num7 * num8);
				}
			}
			mesh.vertices = vertices;
			mesh.colors = colors;
			mesh.RecalculateBounds();
		}

		private void OnDestroy()
		{
			if (Object.op_Implicit((Object)(object)mesh))
			{
				Object.Destroy((Object)(object)mesh);
			}
		}
	}
	public sealed class IconLibrary : IDisposable
	{
		private readonly Dictionary<string, Texture2D> textures = new Dictionary<string, Texture2D>();

		public IconLibrary(Func<string, byte[]> reader = null)
		{
			//IL_0127: Unknown result type (might be due to invalid IL or missing references)
			//IL_012c: Unknown result type (might be due to invalid IL or missing references)
			//IL_013e: 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_014f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0159: Expected O, but got Unknown
			string[] array = new string[9] { "charged-milk-icon.png", "charged-milk-charged-icon.png", "charged-ball-icon.png", "charged-ball-charged-icon.png", "cold-lantern-icon.png", "owlberry-icon.png", "storm-fruit-icon.png", "storm-fruit-charged-icon.png", "takoyaki-icon.png" };
			foreach (string text in array)
			{
				byte[] array2;
				if (reader != null)
				{
					array2 = reader(text);
				}
				else
				{
					using Stream stream = typeof(IconLibrary).Assembly.GetManifestResourceStream("ThunderfenItems.Icon." + text);
					if (stream == null)
					{
						throw new InvalidDataException("Item icon missing: " + text);
					}
					using MemoryStream memoryStream = new MemoryStream();
					stream.CopyTo(memoryStream);
					array2 = memoryStream.ToArray();
				}
				if (array2 == null || array2.Length > 2000000)
				{
					throw new InvalidDataException("Item icon size: " + text);
				}
				Texture2D val = new Texture2D(2, 2, (TextureFormat)4, false)
				{
					name = "TFItem_" + text,
					hideFlags = (HideFlags)61,
					filterMode = (FilterMode)1,
					wrapMode = (TextureWrapMode)1
				};
				if (!ImageConversion.LoadImage(val, array2, true) || ((Texture)val).width != 512 || ((Texture)val).height != 512)
				{
					Object.Destroy((Object)(object)val);
					throw new InvalidDataException("Invalid item icon: " + text);
				}
				textures.Add(text, val);
			}
		}

		public Texture2D Get(Kind kind, bool full)
		{
			string text = kind switch
			{
				Kind.Takoyaki => "takoyaki", 
				Kind.StormFruit => "storm-fruit" + (full ? "-charged" : ""), 
				Kind.Owlberry => "owlberry", 
				Kind.ColdlightLantern => "cold-lantern", 
				Kind.StormOrb => "charged-ball" + (full ? "-charged" : ""), 
				Kind.Milk => "charged-milk" + (full ? "-charged" : ""), 
				_ => null, 
			};
			return (text != null) ? textures[text + "-icon.png"] : null;
		}

		public void Dispose()
		{
			foreach (Texture2D value in textures.Values)
			{
				if (Object.op_Implicit((Object)(object)value))
				{
					Object.Destroy((Object)(object)value);
				}
			}
			textures.Clear();
		}
	}
	public sealed class FoodAction : ItemAction
	{
		private float lastUse = -1f;

		public override void RunAction()
		{
			Item component = ((Component)this).GetComponent<Item>();
			if (!ItemData.IsCustom(component))
			{
				return;
			}
			Character holderCharacter = component.holderCharacter;
			if (Object.op_Implicit((Object)(object)holderCharacter) && !((Object)(object)holderCharacter != (Object)(object)Character.localCharacter) && Object.op_Implicit((Object)(object)((MonoBehaviourPun)holderCharacter).photonView) && ((MonoBehaviourPun)holderCharacter).photonView.IsMine && !(Time.unscaledTime - lastUse < 0.1f))
			{
				lastUse = Time.unscaledTime;
				FoodEffect e = ItemRules.Food(ItemData.KindOf(component), ItemData.Cooked(component) > 0, ItemRules.Full(ItemData.Charge(component)));
				NativeEffects.Food(holderCharacter, e);
				if (e.eyeSeconds > 0f)
				{
					ItemsTrial.Instance?.GrantEyes(holderCharacter, e.eyeSeconds);
				}
				ItemsTrial.Event("food", ItemData.KindOf(component).ToString() + " cooked=" + ItemData.Cooked(component) + " full=" + ItemRules.Full(ItemData.Charge(component)) + " uses=" + ItemData.Uses(component));
			}
		}
	}
	public sealed class ElectricalBlast : MonoBehaviour
	{
		private bool applied;

		public void Apply()
		{
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: 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_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0103: Unknown result type (might be due to invalid IL or missing references)
			//IL_0109: Unknown result type (might be due to invalid IL or missing references)
			//IL_0115: Unknown result type (might be due to invalid IL or missing references)
			//IL_011a: Unknown result type (might be due to invalid IL or missing references)
			if (applied)
			{
				return;
			}
			applied = true;
			AOE componentInChildren = ((Component)this).GetComponentInChildren<AOE>(true);
			Character localCharacter = Character.localCharacter;
			if (!Object.op_Implicit((Object)(object)componentInChildren) || !Object.op_Implicit((Object)(object)localCharacter) || !Object.op_Implicit((Object)(object)((MonoBehaviourPun)localCharacter).photonView) || !((MonoBehaviourPun)localCharacter).photonView.IsMine || !ElectricalTrial.CanReceive(localCharacter) || Vector3.Distance(((Component)componentInChildren).transform.position, localCharacter.Center) > componentInChildren.range)
			{
				return;
			}
			bool flag = false;
			Collider[] array = Physics.OverlapSphere(((Component)componentInChildren).transform.position, componentInChildren.range, LayerMask.op_Implicit(HelperFunctions.GetMask(componentInChildren.mask)));
			Character val2 = default(Character);
			foreach (Collider val in array)
			{
				if (CharacterRagdoll.TryGetCharacterFromCollider(val, ref val2) && (Object)(object)val2 == (Object)(object)localCharacter)
				{
					flag = true;
					break;
				}
			}
			if (!flag)
			{
				return;
			}
			if (componentInChildren.requireLineOfSigh)
			{
				RaycastHit val3 = HelperFunctions.LineCheck(((Component)componentInChildren).transform.position, localCharacter.Center, (LayerType)1, 0f, (QueryTriggerInteraction)1);
				if (Object.op_Implicit((Object)(object)((RaycastHit)(ref val3)).transform))
				{
					return;
				}
			}
			ElectricalTrial.AddCharge(localCharacter, 0.35f);
			ItemsTrial.Event("orb-cooked-dose", "electrical=.35 radius=" + componentInChildren.range);
		}
	}
	public sealed class NativeOrbField : MonoBehaviour
	{
	}
	[HarmonyPatch(typeof(AntiSphere), "Delete", new Type[] { })]
	internal static class OrbFieldCleanupPatch
	{
		private static void Postfix(AntiSphere __instance)
		{
			if (Object.op_Implicit((Object)(object)__instance) && Object.op_Implicit((Object)(object)((Component)__instance).GetComponent<NativeOrbField>()))
			{
				PhotonView component = ((Component)__instance).GetComponent<PhotonView>();
				if (PhotonNetwork.InRoom && Object.op_Implicit((Object)(object)component) && component.IsMine && component.ViewID > 0)
				{
					PhotonNetwork.Destroy(((Component)__instance).gameObject);
				}
			}
		}
	}
	[HarmonyPatch(typeof(AOE), "Explode", new Type[] { })]
	internal static class OrbCookBlastPatch
	{
		private static void Postfix(AOE __instance)
		{
			((Component)__instance).GetComponentInParent<ElectricalBlast>()?.Apply();
		}
	}
	[HarmonyPatch(typeof(Item), "RPC_SetThrownData", new Type[]
	{
		typeof(int),
		typeof(float)
	})]
	internal static class OrbThrowPatch
	{
		private static void Postfix(Item __instance, float __1)
		{
			if (ItemData.IsCustom(__instance) && ItemData.KindOf(__instance) == Kind.StormOrb)
			{
				((Component)__instance).GetComponent<ItemStateBehaviour>()?.Arm(__1);
			}
		}
	}
	[HarmonyPatch(typeof(Item), "SetState", new Type[]
	{
		typeof(ItemState),
		typeof(Character)
	})]
	internal static class ItemHandoffPatch
	{
		private static void Prefix(Item __instance)
		{
			if (ItemData.IsCustom(__instance))
			{
				ItemData.Sync(__instance);
			}
		}

		private static void Postfix(Item __instance, ItemState __0, Character __1)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Invalid comparison between Unknown and I4
			if (!ItemData.IsCustom(__instance))
			{
				return;
			}
			if ((int)__0 == 1)
			{
				((Component)__instance).GetComponent<ItemStateBehaviour>()?.PickedUp();
			}
			if (Object.op_Implicit((Object)(object)__1) && ((MonoBehaviourPun)__instance).photonView.IsMine)
			{
				switch (ItemData.KindOf(__instance))
				{
				case Kind.StormFruit:
					ItemData.SetInteger(__instance, (DataEntryKey)241, -1);
					break;
				case Kind.Owlberry:
					ItemData.SetInteger(__instance, (DataEntryKey)242, -1);
					break;
				default:
					return;
				}
				ItemData.Sync(__instance);
				((Component)__instance).GetComponent<ItemModelView>()?.Apply(ItemData.Charge(__instance), ItemData.Uses(__instance), force: true);
			}
		}
	}
	[HarmonyPatch(typeof(PhotonView), "TransferOwnership", new Type[] { typeof(int) })]
	internal static class ItemOwnershipFlushPatch
	{
		private static void Prefix(PhotonView __instance)
		{
			Item component = ((Component)__instance).GetComponent<Item>();
			if (ItemData.IsCustom(component))
			{
				ItemData.Sync(component);
			}
		}
	}
	[HarmonyPatch(typeof(Item), "GetItemName", new Type[] { typeof(ItemInstanceData) })]
	internal static class ItemSlotNamePatch
	{
		private static bool Prefix(Item __instance, ItemInstanceData __0, ref string __result)
		{
			if (!ItemData.IsCustom(__instance))
			{
				return true;
			}
			__0 = __0 ?? __instance.data;
			bool chinese = Naming.Chinese;
			string text = ItemRules.Name(ItemData.KindOf(__instance), ItemRules.Full(ItemData.Charge(__0)), chinese);
			int num = ItemData.Cooked(__0);
			__result = ((num > 0) ? ((chinese ? "烹饪的" : "Cooked ") + text) : text);
			return false;
		}
	}
	[HarmonyPatch(typeof(Item), "GetName", new Type[] { })]
	internal static class ItemNamePatch
	{
		private static bool Prefix(Item __instance, ref string __result)
		{
			if (!ItemData.IsCustom(__instance))
			{
				return true;
			}
			__result = ItemRules.Name(ItemData.KindOf(__instance), ItemRules.Full(ItemData.Charge(__instance)), Naming.Chinese);
			return false;
		}
	}
	[HarmonyPatch(typeof(ItemCooking), "get_canBeCooked", new Type[] { })]
	internal static class SingleCookPatch
	{
		private static void Postfix(ItemCooking __instance, ref bool __result)
		{
			Item component = ((Component)__instance).GetComponent<Item>();
			if (ItemData.IsCustom(component) && ItemData.KindOf(component) != Kind.ColdlightLantern && ItemData.Cooked(component) > 0)
			{
				__result = false;
			}
		}
	}
	internal static class Naming
	{
		public static bool Chinese => ((object)Unsafe.As<Language, Language>(ref LocalizedText.CURRENT_LANGUAGE)/*cast due to .constrained prefix*/).ToString().IndexOf("Chinese", StringComparison.OrdinalIgnoreCase) >= 0;
	}
	[HarmonyPatch(typeof(Item), "SetItemInstanceDataRPC", new Type[] { typeof(ItemInstanceData) })]
	internal static class ItemModelDataPatch
	{
		private static void Postfix(Item __instance)
		{
			if (ItemData.IsCustom(__instance))
			{
				((Component)__instance).GetComponent<ItemModelView>()?.Apply(ItemData.Charge(__instance), ItemData.Uses(__instance), force: true);
			}
		}
	}
	[HarmonyPatch(typeof(Item), "HoverEnter", new Type[] { })]
	internal static class ItemModelHoverEnterPatch
	{
		private static void Postfix(Item __instance)
		{
			if (ItemData.IsCustom(__instance))
			{
				((Component)__instance).GetComponent<ItemModelView>()?.Apply(ItemData.Charge(__instance), ItemData.Uses(__instance), force: true);
			}
		}
	}
	[HarmonyPatch(typeof(Item), "HoverExit", new Type[] { })]
	internal static class ItemModelHoverExitPatch
	{
		private static void Postfix(Item __instance)
		{
			if (ItemData.IsCustom(__instance))
			{
				((Component)__instance).GetComponent<ItemModelView>()?.Apply(ItemData.Charge(__instance), ItemData.Uses(__instance), force: true);
			}
		}
	}
	public static class ItemData
	{
		public const ushort FirstId = 62101;

		public const ushort LastId = 62106;

		public const DataEntryKey ChargeKey = (DataEntryKey)240;

		public const DataEntryKey TreeKey = (DataEntryKey)241;

		public const DataEntryKey SiteKey = (DataEntryKey)242;

		public const DataEntryKey ThrownKey = (DataEntryKey)243;

		public static bool IsCustom(Item item)
		{
			return Object.op_Implicit((Object)(object)item) && item.itemID >= 62101 && item.itemID <= 62106;
		}

		public static Kind KindOf(Item item)
		{
			if (!IsCustom(item))
			{
				throw new ArgumentException("Not a Thunderfen item");
			}
			return (Kind)(item.itemID - 62100);
		}

		public static ushort Id(Kind kind)
		{
			return (ushort)(62100 + kind);
		}

		public static string Prefab(Kind kind)
		{
			return "TFItems/" + kind;
		}

		public static float Charge(Item item)
		{
			return Object.op_Implicit((Object)(object)item) ? Charge(item.data) : 0f;
		}

		public static float Charge(ItemInstanceData data)
		{
			FloatItemData val = default(FloatItemData);
			if (data == null || !data.TryGetDataEntry<FloatItemData>((DataEntryKey)240, ref val) || !ItemRules.Finite(val.Value))
			{
				return 0f;
			}
			return Mathf.Clamp(val.Value, 0f, 0.3f);
		}

		public static void SetCharge(Item item, float charge)
		{
			if (!Object.op_Implicit((Object)(object)item) || !Object.op_Implicit((Object)(object)((MonoBehaviourPun)item).photonView) || !((MonoBehaviourPun)item).photonView.IsMine)
			{
				throw new InvalidOperationException("Only the item owner may change charge");
			}
			item.GetData<FloatItemData>((DataEntryKey)240).Value = Mathf.Clamp(charge, 0f, 0.3f);
		}

		public static int Integer(Item item, DataEntryKey key, int fallback = 0)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			IntItemData val = default(IntItemData);
			return (Object.op_Implicit((Object)(object)item) && item.data != null && item.data.TryGetDataEntry<IntItemData>(key, ref val)) ? val.Value : fallback;
		}

		public static void SetInteger(Item item, DataEntryKey key, int value)
		{
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			if (!Object.op_Implicit((Object)(object)item) || !Object.op_Implicit((Object)(object)((MonoBehaviourPun)item).photonView) || !((MonoBehaviourPun)item).photonView.IsMine)
			{
				throw new InvalidOperationException("Only the item owner may change item state");
			}
			item.GetData<IntItemData>(key).Value = value;
		}

		public static int Cooked(Item item)
		{
			return Object.op_Implicit((Object)(object)item) ? Cooked(item.data) : 0;
		}

		public static int Cooked(ItemInstanceData data)
		{
			IntItemData val = default(IntItemData);
			return (data != null && data.TryGetDataEntry<IntItemData>((DataEntryKey)1, ref val)) ? val.Value : 0;
		}

		public static int Uses(Item item)
		{
			OptionableIntItemData val = default(OptionableIntItemData);
			return (Object.op_Implicit((Object)(object)item) && item.data != null && item.data.TryGetDataEntry<OptionableIntItemData>((DataEntryKey)2, ref val) && val.HasData) ? val.Value : (Object.op_Implicit((Object)(object)item) ? item.totalUses : 0);
		}

		public static void Sync(Item item)
		{
			if (PhotonNetwork.InRoom && Object.op_Implicit((Object)(object)item) && Object.op_Implicit((Object)(object)((MonoBehaviourPun)item).photonView) && ((MonoBehaviourPun)item).photonView.ViewID > 0 && ((MonoBehaviourPun)item).photonView.IsMine && item.data != null && !((Object)(object)PhotonNetwork.GetPhotonView(((MonoBehaviourPun)item).photonView.ViewID) != (Object)(object)((MonoBehaviourPun)item).photonView))
			{
				((MonoBehaviourPun)item).photonView.RPC("SetItemInstanceDataRPC", (RpcTarget)1, new object[1] { item.data });
			}
		}
	}
	public enum Kind
	{
		Milk = 1,
		StormOrb,
		StormFruit,
		ColdlightLantern,
		Owlberry,
		Takoyaki
	}
	public struct FoodEffect
	{
		public float hunger;

		public float extraStamina;

		public float poison;

		public float electrical;

		public float clearHeat;

		public float eyeSeconds;

		public float immunitySeconds;
	}
	public static class ItemRules
	{
		public const float ChargeCost = 0.3f;

		public const float TransferMultiplier = 5f;

		public const float OwlberryEffectSeconds = 300f;

		public const float TakoyakiImmunitySeconds = 180f;

		public static bool ManualCharge(Kind kind)
		{
			return kind == Kind.Milk || kind == Kind.StormOrb;
		}

		public static string Name(Kind kind, bool charged, bool chinese)
		{
			string text;
			switch (kind)
			{
			case Kind.Milk:
				if (charged)
				{
					return chinese ? "带电的羊奶" : "Electric Milk";
				}
				text = (chinese ? "羊奶" : "Milk");
				break;
			case Kind.StormOrb:
				text = (chinese ? "雷暴球" : "Storm Orb");
				break;
			case Kind.StormFruit:
				text = (chinese ? "风暴果" : "Storm Fruit");
				break;
			case Kind.ColdlightLantern:
				return chinese ? "冷光灯" : "Coldlight Lantern";
			case Kind.Owlberry:
				return chinese ? "夜猫莓" : "Owlberry";
			case Kind.Takoyaki:
				return chinese ? "章鱼小丸子" : "Takoyaki";
			default:
				throw new ArgumentOutOfRangeException("kind");
			}
			return ((!chinese) ? (charged ? "Charged " : "Uncharged ") : (charged ? "充电的" : "未充电的")) + text;
		}

		public static bool Full(float stored)
		{
			return stored >= 0.299999f;
		}

		public static float Transfer(float stored, float player, float decay, float dt)
		{
			if (!Finite(stored) || !Finite(player) || !Finite(decay) || !Finite(dt) || dt <= 0f || decay < 0f || stored < 0f || player < 0f)
			{
				return 0f;
			}
			return Math.Max(0f, Math.Min(0.3f - stored, Math.Min(player, decay * 5f * Math.Min(dt, 0.25f))));
		}

		public static bool Finite(float n)
		{
			return !float.IsNaN(n) && !float.IsInfinity(n);
		}

		public static FoodEffect Food(Kind kind, bool cooked, bool charged)
		{
			FoodEffect result = default(FoodEffect);
			switch (kind)
			{
			case Kind.Milk:
				result.extraStamina = ((!charged) ? (cooked ? 0.4f : 0.3f) : (cooked ? 1f : 0.85f));
				result.clearHeat = 1f;
				result.electrical = (charged ? 0.05f : 0f);
				break;
			case Kind.StormFruit:
				result.hunger = ((!charged) ? (cooked ? 0.3f : 0.15f) : (cooked ? 0.45f : 0.3f));
				result.extraStamina = ((!charged) ? (cooked ? 0.1f : 0f) : (cooked ? 0.3f : 0.2f));
				result.electrical = (charged ? 0.1f : 0f);
				break;
			case Kind.Owlberry:
				result.hunger = (cooked ? 0.2f : 0.1f);
				result.extraStamina = (cooked ? 0.1f : 0f);
				result.poison = (cooked ? 0f : 0.1f);
				result.eyeSeconds = 300f;
				break;
			case Kind.Takoyaki:
				result.hunger = (cooked ? 0.2f : 0.1f);
				result.extraStamina = (cooked ? 0.05f : 0f);
				result.immunitySeconds = 180f;
				break;
			default:
				throw new ArgumentOutOfRangeException("kind");
			}
			return result;
		}

		public static double RefreshExpiry(double now, float seconds)
		{
			return now + (double)Math.Max(0f, seconds);
		}
	}
	public sealed class ItemSite
	{
		public int id;

		public int tree;

		public int branch;

		public int room;

		public Kind kind;

		public Vector3 position;

		public float scale;
	}
	public sealed class ItemSites
	{
		public int seed;

		public ItemSite[] sites;

		public static ItemSites Read(byte[] bytes)
		{
			//IL_0131: Unknown result type (might be due to invalid IL or missing references)
			//IL_0136: Unknown result type (might be due to invalid IL or missing references)
			if (bytes == null || bytes.Length < 16 || bytes.Length > 4000000)
			{
				throw new InvalidDataException("Invalid item sites");
			}
			using MemoryStream memoryStream = new MemoryStream(bytes);
			using BinaryReader binaryReader = new BinaryReader(memoryStream);
			if (new string(binaryReader.ReadChars(4)) != "TFIS" || binaryReader.ReadInt32() != 1)
			{
				throw new InvalidDataException("Item site version");
			}
			int num = binaryReader.ReadInt32();
			int num2 = binaryReader.ReadInt32();
			if (num2 < 4 || num2 > 2000 || memoryStream.Length != 16 + num2 * 40)
			{
				throw new InvalidDataException("Item site size");
			}
			ItemSites itemSites = new ItemSites();
			itemSites.seed = num;
			itemSites.sites = new ItemSite[num2];
			ItemSites itemSites2 = itemSites;
			for (int i = 0; i < num2; i++)
			{
				ItemSite itemSite = new ItemSite
				{
					id = binaryReader.ReadInt32(),
					kind = (Kind)binaryReader.ReadInt32(),
					tree = binaryReader.ReadInt32(),
					branch = binaryReader.ReadInt32(),
					room = binaryReader.ReadInt32(),
					position = new Vector3(binaryReader.ReadSingle(), binaryReader.ReadSingle(), binaryReader.ReadSingle()),
					scale = binaryReader.ReadSingle()
				};
				float num3 = binaryReader.ReadSingle();
				if (itemSite.id != i || itemSite.kind < Kind.Milk || itemSite.kind > Kind.Takoyaki || itemSite.tree < -1 || itemSite.branch < -1 || itemSite.room < -1 || !ItemRules.Finite(itemSite.position.x) || !ItemRules.Finite(itemSite.position.y) || !ItemRules.Finite(itemSite.position.z) || itemSite.scale <= 0f || itemSite.scale > 2f || num3 != 0f)
				{
					throw new InvalidDataException("Invalid item site record");
				}
				itemSites2.sites[i] = itemSite;
			}
			return itemSites2;
		}
	}
	public sealed class ItemStateBehaviour : MonoBehaviourPun
	{
		public const float ColdlightMultiplier = 1.5f;

		public const float OwlberryGlowRange = 3f;

		public const float OwlberryGlowIntensity = 2f;

		public static readonly HashSet<ItemStateBehaviour> Active = new HashSet<ItemStateBehaviour>();

		private Item source;

		private ItemModelView visual;

		private Lantern lantern;

		private Light glow;

		private float nextSync;

		private float nextFruit;

		private float nextVisual;

		private float sentCharge;

		private bool impactUsed;

		private int armed;

		private float armAt;

		private int shownImpact;

		private void Awake()
		{
			sentCharge = float.NaN;
			source = ((Component)this).GetComponent<Item>();
			visual = ((Component)this).GetComponent<ItemModelView>();
			lantern = ((Component)this).GetComponent<Lantern>();
		}

		private void OnEnable()
		{
			Active.Add(this);
			if (Object.op_Implicit((Object)(object)glow))
			{
				ItemLampAPI.RegisterFill(glow);
			}
			nextSync = Time.unscaledTime + 2f;
		}

		private void OnDisable()
		{
			Active.Remove(this);
			if (Object.op_Implicit((Object)(object)glow))
			{
				ItemLampAPI.RemoveFill(glow);
			}
			if (Object.op_Implicit((Object)(object)lantern))
			{
				ItemLampAPI.Remove(lantern.lanternLight);
			}
		}

		private void Start()
		{
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_015f: Unknown result type (might be due to invalid IL or missing references)
			if (ItemData.KindOf(source) == Kind.ColdlightLantern && Object.op_Implicit((Object)(object)lantern))
			{
				ItemLampAPI.Register(lantern.lanternLight, 1.5f);
				Lantern obj = lantern;
				obj.lightIntensity *= 1.5f;
				Light lanternLight = lantern.lanternLight;
				lanternLight.range *= 1.5f;
			}
			if (ItemData.KindOf(source) == Kind.Owlberry)
			{
				Transform val = ((Component)this).transform.Find("Owlberry_SelfLight");
				GameObject val2 = (GameObject)(Object.op_Implicit((Object)(object)val) ? ((object)((Component)val).gameObject) : ((object)new GameObject("Owlberry_SelfLight")));
				val2.transform.SetParent(((Component)this).transform, false);
				val2.transform.localPosition = new Vector3(0f, 0.12f, 0f);
				glow = val2.GetComponent<Light>();
				if (!Object.op_Implicit((Object)(object)glow))
				{
					glow = val2.AddComponent<Light>();
				}
				((Behaviour)glow).enabled = false;
				glow.type = (LightType)2;
				glow.range = 3f;
				glow.intensity = 2f;
				glow.color = new Color(0.58f, 0.66f, 1f);
				glow.shadows = (LightShadows)0;
				glow.renderMode = (LightRenderMode)1;
				ItemLampAPI.RegisterFill(glow);
				visual?.Apply(ItemData.Charge(source), ItemData.Uses(source), force: true);
			}
		}

		private void Update()
		{
			if (!Object.op_Implicit((Object)(object)source) || !Object.op_Implicit((Object)(object)((MonoBehaviourPun)this).photonView) || !Object.op_Implicit((Object)(object)ItemsTrial.Instance) || !ItemsTrial.Instance.Ready)
			{
				return;
			}
			Kind kind = ItemData.KindOf(source);
			if (((MonoBehaviourPun)this).photonView.IsMine)
			{
				Character holderCharacter = source.holderCharacter;
				if (kind == Kind.Owlberry && Object.op_Implicit((Object)(object)holderCharacter) && ItemData.Integer(source, (DataEntryKey)242, -1) >= 0)
				{
					ItemData.SetInteger(source, (DataEntryKey)242, -1);
					ItemData.Sync(source);
				}
				if (kind == Kind.StormFruit && Object.op_Implicit((Object)(object)holderCharacter) && ItemData.Integer(source, (DataEntryKey)241, -1) >= 0)
				{
					ItemData.SetInteger(source, (DataEntryKey)241, -1);
					ItemData.Sync(source);
				}
				if (ItemRules.ManualCharge(kind) && Object.op_Implicit((Object)(object)holderCharacter) && (Object)(object)holderCharacter == (Object)(object)Character.localCharacter && ((MonoBehaviourPun)holderCharacter).photonView.IsMine && !holderCharacter.data.dead)
				{
					float num = ItemData.Charge(source);
					float num2 = ItemRules.Transfer(num, ElectricalTrial.ChargeFor(holderCharacter), ElectricalTrial.NaturalDecayRate, Time.deltaTime);
					if (num2 > 0f)
					{
						float num3 = ElectricalTrial.TakeCharge(holderCharacter, num2);
						if (num3 > 0f)
						{
							ItemData.SetCharge(source, num + num3);
							if (ItemRules.Full(ItemData.Charge(source)))
							{
								ItemData.Sync(source);
								ItemsTrial.Event("fully-charged", kind.ToString() + " capacity=.30");
							}
						}
					}
				}
				if (kind == Kind.StormFruit && Time.unscaledTime >= nextFruit)
				{
					nextFruit = Time.unscaledTime + 0.25f;
					TryTreeCharge(-1);
				}
				if (Time.unscaledTime >= nextSync)
				{
					nextSync = Time.unscaledTime + 1f;
					if (!Mathf.Approximately(sentCharge, ItemData.Charge(source)))
					{
						Sync();
					}
				}
			}
			if (Time.unscaledTime >= nextVisual)
			{
				nextVisual = Time.unscaledTime + 0.1f;
				visual?.Apply(ItemData.Charge(source), ItemData.Uses(source));
			}
		}

		public void Sync()
		{
			ItemData.Sync(source);
			sentCharge = ItemData.Charge(source);
		}

		public void TryTreeCharge(int struck)
		{
			if (Object.op_Implicit((Object)(object)source) && Object.op_Implicit((Object)(object)((MonoBehaviourPun)this).photonView) && ((MonoBehaviourPun)this).photonView.IsMine && ItemData.KindOf(source) == Kind.StormFruit && !ItemRules.Full(ItemData.Charge(source)) && !Object.op_Implicit((Object)(object)source.holderCharacter) && Object.op_Implicit((Object)(object)source.rig) && source.rig.isKinematic)
			{
				int num = ItemData.Integer(source, (DataEntryKey)241, -1);
				if (num >= 0 && ItemData.Integer(source, (DataEntryKey)242, -1) >= 0 && (struck < 0 || num == struck) && (struck >= 0 || !(ItemTreeAPI.Charge(num) <= 1E-06f)))
				{
					ItemData.SetCharge(source, 0.3f);
					ItemData.Sync(source);
					ItemsTrial.Event("tree-fruit-charged", "tree=" + num + " strike=" + struck);
				}
			}
		}

		public void PickedUp()
		{
			armed = 0;
			impactUsed = false;
		}

		public void Arm(float power)
		{
			if (Object.op_Implicit((Object)(object)source) && ItemData.KindOf(source) == Kind.StormOrb && ItemRules.Finite(power) && !(power <= 0f))
			{
				armed++;
				armAt = Time.time;
				impactUsed = false;
				if (Object.op_Implicit((Object)(object)((MonoBehaviourPun)this).photonView) && ((MonoBehaviourPun)this).photonView.IsMine)
				{
					ItemsTrial.Event("orb-armed", "power=" + power + " dataPending=" + (source.data == null));
				}
			}
		}

		private void OnCollisionEnter(Collision collision)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			Collider collider = collision.collider;
			Vector3 point;
			if (collision.contactCount <= 0)
			{
				point = ((Component)this).transform.position;
			}
			else
			{
				ContactPoint contact = collision.GetContact(0);
				point = ((ContactPoint)(ref contact)).point;
			}
			Impact(collider, point);
		}

		internal void Impact(Collider collider, Vector3 point)
		{
			//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
			if (Object.op_Implicit((Object)(object)source) && ((MonoBehaviourPun)this).photonView.IsMine && !Object.op_Implicit((Object)(object)source.holderCharacter) && ItemData.KindOf(source) == Kind.StormOrb && ItemRules.Full(ItemData.Charge(source)) && armed > 0 && !impactUsed && !(Time.time - armAt > 30f) && (!((Object)(object)((Component)collider).GetComponentInParent<Character>() == (Object)(object)Character.localCharacter) || !(Time.time - armAt < 0.3f)))
			{
				impactUsed = true;
				ItemData.SetInteger(source, (DataEntryKey)243, armed);
				ItemData.Sync(source);
				((MonoBehaviourPun)this).photonView.RPC("OrbImpactRPC", (RpcTarget)0, new object[2] { armed, point });
				PhotonNetwork.Destroy(((Component)this).gameObject);
			}
		}

		[PunRPC]
		public unsafe void OrbImpactRPC(int serial, Vector3 point, PhotonMessageInfo info)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: 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_006a: 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)
			if (info.Sender != null && (info.Sender == ((MonoBehaviourPun)this).photonView.Owner || (((MonoBehaviourPun)this).photonView.IsRoomView && info.Sender == PhotonNetwork.MasterClient)) && serial > shownImpact && serial >= 1 && ItemRules.Finite(point.x) && ItemRules.Finite(point.y) && ItemRules.Finite(point.z) && !(Vector3.Distance(point, ((Component)this).transform.position) > 12f))
			{
				shownImpact = serial;
				ItemsTrial.Instance?.Factory.Gravity(point);
				ItemsTrial.Event("orb-field", "serial=" + serial + " position=" + ((object)(*(Vector3*)(&point))/*cast due to .constrained prefix*/).ToString());
			}
		}
	}
	[BepInPlugin("local.peak.poisonforest.items", "Thunderfen Items", "1.0.1")]
	[BepInDependency("local.peak.poisonforest.solo", "0.5.5")]
	[BepInDependency("local.peak.poisonforest.electrical", "0.4.0")]
	[BepInDependency("local.peak.poisonforest.lightning", "0.3.2")]
	[BepInDependency("local.peak.poisonforest.nativeprops", "0.2.6")]
	[BepInDependency("local.peak.poisonforest.cavebugs", "0.2.4")]
	[DefaultExecutionOrder(1250)]
	public sealed class ItemsTrial : BaseUnityPlugin
	{
		[Serializable]
		private sealed class Settings
		{
			public string modelSha256;

			public bool chestLootEnabled;
		}

		[Serializable]
		private sealed class Report
		{
			public string utc;

			public string version = "1.0.1";

			public string error;

			public string heldVisual;

			public string eyeRenderStatus;

			public bool ready;

			public bool failed;

			public bool chestLootEnabled;

			public int seed;

			public int sites;

			public int spawned;

			public int liveItems;

			public int naturalOwlberrySites;

			public int resyncPasses;

			public int resyncItems;

			public int eyeObservedPlayers;

			public int eyeVisibleShafts;

			public int chestLootDraws;

			public int chestLootFallbacks;

			public int hangingOwlberries;

			public int waitingOwlberryStalks;

			public double eyeSeconds;

			public double stiffnessImmuneSeconds;

			public string[] items;
		}

		public const string Id = "local.peak.poisonforest.items";

		public const string Version = "1.0.1";

		public static ItemsTrial Instance;

		private bool chestLootEnabled;

		private bool ready;

		private bool failed;

		private bool worldWasReady;

		private bool released;

		private bool prepared;

		private bool startupFailed;

		private int seedWarning;

		private RoomDataSync roomSync;

		private string error;

		private string folder;

		private ModelLibrary models;

		private Harmony harmony;

		private EyeBeams eyes;

		private Transform frame;

		private ItemSites sites;

		private int revision = -1;

		private int players = -1;

		private float nextPoll;

		private float nextReport;

		private float nextPrepare;

		private float resyncAt;

		private float resyncAgainAt;

		private int spawned;

		private int resyncPasses;

		private int resyncItems;

		public PrefabFactory Factory { get; private set; }

		public IconLibrary Icons { get; private set; }

		public bool Ready => ready && !failed;

		public ChestLoot Chests { get; private set; }

		public bool ChestLootEnabled => chestLootEnabled && !failed;

		private static string Hash(byte[] b)
		{
			using SHA256 sHA = SHA256.Create();
			return BitConverter.ToString(sHA.ComputeHash(b)).Replace("-", "");
		}

		private void Awake()
		{
			//IL_0118: Unknown result type (might be due to invalid IL or missing references)
			//IL_0122: Expected O, but got Unknown
			Instance = this;
			folder = Path.Combine(Application.persistentDataPath, "Thunderfen", "Items");
			Directory.CreateDirectory(folder);
			try
			{
				NativeCompatibility.CheckPatches(typeof(ItemsTrial).Assembly);
				string directoryName = Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location);
				Settings settings = JsonUtility.FromJson<Settings>(File.ReadAllText(Path.Combine(directoryName, "PoisonForestItems.settings.json")));
				byte[] array = File.ReadAllBytes(Path.Combine(directoryName, "thunderfen-item-models.bin"));
				if (settings == null || Hash(array) != settings.modelSha256)
				{
					throw new InvalidDataException("Item model/settings mismatch");
				}
				chestLootEnabled = settings.chestLootEnabled;
				NativeEffects.Check();
				models = new ModelLibrary(array);
				Icons = new IconLibrary();
				Factory = new PrefabFactory(models, Icons);
				Chests = new ChestLoot(Factory);
				eyes = new EyeBeams();
				PrefabDispatch.RegisterExtension("0_Items/TFItems/", (IPunPrefabPool)(object)Factory);
				harmony = new Harmony("local.peak.poisonforest.items");
				harmony.PatchAll(typeof(ItemsTrial).Assembly);
				ItemTreeAPI.Struck += TreeStruck;
				roomSync = ((Component)this).gameObject.AddComponent<RoomDataSync>();
				SceneManager.sceneLoaded += SceneLoaded;
				Event("startup", "six items; native item data; Thunderfen chest loot enabled=" + chestLootEnabled);
			}
			catch (Exception e)
			{
				startupFailed = true;
				Release();
				SharedWorld.MarkStartupFailure("Thunderfen items");
				Fail(e);
			}
		}

		private void SceneLoaded(Scene scene, LoadSceneMode mode)
		{
			if (failed && !startupFailed && !released && (!(((Scene)(ref scene)).name != "Title") || !(((Scene)(ref scene)).name != "Airport")))
			{
				failed = false;
				error = null;
				ready = prepared;
				frame = null;
				sites = null;
				revision = -1;
				Event("recovered", "after a runtime failure, on loading " + ((Scene)(ref scene)).name);
			}
		}

		private void Update()
		{
			if (failed)
			{
				return;
			}
			try
			{
				if (!ready && Time.unscaledTime >= nextPrepare)
				{
					nextPrepare = Time.unscaledTime + 1f;
					ready = Factory.Prepare();
					if (ready)
					{
						prepared = true;
						Event("ready", "registered IDs62101..62106");
					}
				}
				if (!ready)
				{
					ReportNow();
					return;
				}
				if (SharedWorld.Ready && !worldWasReady)
				{
					ScheduleResync();
				}
				worldWasReady = SharedWorld.Ready;
				if (players != PhotonNetwork.PlayerList.Length)
				{
					players = PhotonNetwork.PlayerList.Length;
					ScheduleResync();
				}
				if (resyncAgainAt > 0f && Time.unscaledTime >= resyncAgainAt)
				{
					resyncAt = Time.unscaledTime;
					resyncAgainAt = 0f;
				}
				if (resyncAt > 0f && Time.unscaledTime >= resyncAt)
				{
					resyncAt = 0f;
					int num = 0;
					ItemStateBehaviour[] array = ItemStateBehaviour.Active.ToArray();
					foreach (ItemStateBehaviour itemStateBehaviour in array)
					{
						if (Object.op_Implicit((Object)(object)itemStateBehaviour) && Object.op_Implicit((Object)(object)((MonoBehaviourPun)itemStateBehaviour).photonView) && ((MonoBehaviourPun)itemStateBehaviour).photonView.IsMine)
						{
							itemStateBehaviour.Sync();
							num++;
						}
					}
					resyncPasses++;
					resyncItems += num;
					Event("owner-state-resync", "pass=" + resyncPasses + " owned=" + num);
				}
				if (Time.unscaledTime >= nextPoll)
				{
					nextPoll = Time.unscaledTime + 0.5f;
					Transform val = FindFrame();
					bool localMapReady = SoloGenerationPlugin.LocalMapReady;
					if ((Object)(object)val != (Object)(object)frame || revision != RunData.Revision || !localMapReady)
					{
						frame = val;
						revision = RunData.Revision;
						sites = null;
					}
					if (Object.op_Implicit((Object)(object)frame) && sites == null && localMapReady)
					{
						ItemSites itemSites = ItemSites.Read(GeneratedData.Read("item-sites.bin"));
						if (itemSites.seed == RunData.Seed)
						{
							sites = itemSites;
							seedWarning = 0;
						}
						else if (seedWarning != RunData.Seed)
						{
							seedWarning = RunData.Seed;
							((BaseUnityPlugin)this).Logger.LogWarning((object)("Item sites for seed " + itemSites.seed + " wait for the selected map, seed " + RunData.Seed + "."));
						}
					}
					if (Object.op_Implicit((Object)(object)frame) && sites != null && SharedWorld.Ready && SharedWorld.Authority && !RunData.Pending)
					{
						SpawnSites();
					}
				}
				ReportNow();
			}
			catch (Exception e)
			{
				Fail(e);
			}
		}

		private void LateUpdate()
		{
			if (!Ready)
			{
				return;
			}
			try
			{
				eyes.Tick();
			}
			catch (Exception e)
			{
				Fail(e);
			}
		}

		public void ScheduleResync()
		{
			resyncAt = Time.unscaledTime + 1f;
			resyncAgainAt = Time.unscaledTime + 5f;
		}

		private void SpawnSites()
		{
			//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_0067: Unknown result type (might be due to invalid IL or missing references)
			ItemSite[] array = sites.sites;
			foreach (ItemSite itemSite in array)
			{
				string text = "items:" + itemSite.id;
				if (!SharedWorld.SiteClaimed(text) && SharedWorld.ClaimSite(text))
				{
					Spawn(itemSite.kind, frame.TransformPoint(itemSite.position), frame.rotation, itemSite);
				}
			}
		}

		private unsafe void Spawn(Kind kind, Vector3 position, Quaternion rotation, ItemSite site = null)
		{
			//IL_0018: 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_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = PhotonNetwork.InstantiateRoomObject("0_Items/TFItems/" + kind, position, rotation, (byte)0, (object[])null);
			Item component = val.GetComponent<Item>();
			if (!Object.op_Implicit((Object)(object)component) || !((MonoBehaviourPun)component).photonView.IsMine)
			{
				throw new InvalidOperationException("Native room item owner missing");
			}
			ItemData.SetCharge(component, 0f);
			if (site != null)
			{
				ItemData.SetInteger(component, (DataEntryKey)242, site.id);
				ItemData.SetInteger(component, (DataEntryKey)241, site.tree);
				if (kind == Kind.StormFruit || kind == Kind.Owlberry)
				{
					component.SetKinematicNetworked(true, position, rotation);
					if (kind == Kind.StormFruit)
					{
						((Component)component).GetComponent<ItemStateBehaviour>().TryTreeCharge(-1);
					}
				}
			}
			ItemData.Sync(component);
			spawned++;
			Event("spawn", kind.ToString() + " site=" + (site?.id.ToString() ?? "unsited") + " position=" + ((object)(*(Vector3*)(&position))/*cast due to .constrained prefix*/).ToString());
		}

		private void TreeStruck(int tree)
		{
			ItemStateBehaviour[] array = ItemStateBehaviour.Active.ToArray();
			foreach (ItemStateBehaviour itemStateBehaviour in array)
			{
				if (Object.op_Implicit((Object)(object)itemStateBehaviour))
				{
					itemStateBehaviour.TryTreeCharge(tree);
				}
			}
		}

		public void GrantEyes(Character c, float seconds)
		{
			eyes.Grant(c, seconds);
			Event("eye-beams", "duration=" + seconds);
		}

		private static Transform FindFrame()
		{
			//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)
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Expected O, but got Unknown
			Scene sceneByName = SceneManager.GetSceneByName("WilIsland");
			if (!((Scene)(ref sceneByName)).IsValid() || !((Scene)(ref sceneByName)).isLoaded)
			{
				return null;
			}
			GameObject val = ((IEnumerable<GameObject>)((Scene)(ref sceneByName)).GetRootGameObjects()).FirstOrDefault((Func<GameObject, bool>)((GameObject o) => ((Object)o).name == "Map"));
			Transform val2 = (Object.op_Implicit((Object)(object)val) ? val.transform.Find("Global") : null);
			if (!Object.op_Implicit((Object)(object)val2))
			{
				return null;
			}
			foreach (Transform item in val2)
			{
				Transform val3 = item;
				if (((Object)val3).name.Contains("first-ridge"))
				{
					Transform val4 = ((IEnumerable<Transform>)((Component)val3).GetComponentsInChildren<Transform>(true)).FirstOrDefault((Func<Transform, bool>)((Transform t) => ((Object)t).name == "PF_HybridTerrain" && Object.op_Implicit((Object)(object)t.parent) && ((Object)t.parent).name == "RootsTerrain"));
					if (Object.op_Implicit((Object)(object)val4) && ((Component)val4).gameObject.activeInHierarchy)
					{
						return val4;
					}
				}
			}
			return null;
		}

		public static void Event(string name, string detail)
		{
			ItemsTrial instance = Instance;
			if (!Object.op_Implicit((Object)(object)instance) || string.IsNullOrEmpty(instance.folder))
			{
				return;
			}
			((BaseUnityPlugin)instance).Logger.LogInfo((object)(name + ": " + detail));
			try
			{
				if (RuntimeDiagnostics.PeriodicSnapshots)
				{
					File.AppendAllText(Path.Combine(instance.folder, "events.tsv"), DateTime.UtcNow.ToString("O") + "\t" + name + "\t" + detail + "\n");
				}
			}
			catch
			{
			}
		}

		private void ReportNow()
		{
			if (RuntimeDiagnostics.PeriodicSnapshots && !(Time.unscaledTime < nextReport))
			{
				nextReport = Time.unscaledTime + 2f;
				Item val = ((Object.op_Implicit((Object)(object)Character.localCharacter) && (Object)(object)Character.localCharacter.data != (Object)null) ? Character.localCharacter.data.currentItem : null);
				ItemModelView itemModelView = (Object.op_Implicit((Object)(object)val) ? ((Component)val).GetComponent<ItemModelView>() : null);
				Report report = new Report();
				report.heldVisual = (Object.op_Implicit((Object)(object)itemModelView) ? (ItemData.KindOf(val).ToString() + " charge=" + ItemData.Charge(val).ToString("F4") + " " + itemModelView.Describe()) : null);
				report.utc = DateTime.UtcNow.ToString("O");
				report.ready = ready;
				report.failed = failed;
				report.error = error;
				report.seed = sites?.seed ?? 0;
				ItemSites itemSites = sites;
				report.sites = ((itemSites != null) ? itemSites.sites.Length : 0);
				report.naturalOwlberrySites = ((sites != null) ? sites.sites.Count((ItemSite s) => s.kind == Kind.Owlberry) : 0);
				report.resyncPasses = resyncPasses;
				report.resyncItems = resyncItems;
				report.spawned = spawned;
				report.liveItems = ItemStateBehaviour.Active.Count;
				report.eyeSeconds = eyes?.Remaining ?? 0.0;
				report.eyeObservedPlayers = eyes?.ObservedPlayers ?? 0;
				report.eyeVisibleShafts = eyes?.VisibleShafts ?? 0;
				report.eyeRenderStatus = eyes?.RenderStatus;
				report.hangingOwlberries = ItemStateBehaviour.Active.Count((ItemStateBehaviour s) => Object.op_Implicit((Object)(object)s) && Object.op_Implicit((Object)(object)((Component)s).GetComponent<OwlberryPlant>()) && ((Component)s).GetComponent<OwlberryPlant>().Planted);
				report.waitingOwlberryStalks = ItemStateBehaviour.Active.Count((ItemStateBehaviour s) => Object.op_Implicit((Object)(object)s) && Object.op_Implicit((Object)(object)((Component)s).GetComponent<OwlberryPlant>()) && ((Component)s).GetComponent<OwlberryPlant>().Waiting);
				report.stiffnessImmuneSeconds = ElectricalTrial.StiffnessImmunityRemaining;
				report.chestLootEnabled = ChestLootEnabled;
				report.chestLootDraws = Chests?.Draws ?? 0;
				report.chestLootFallbacks = Chests?.Fallbacks ?? 0;
				report.items = ItemStateBehaviour.Active.Where((ItemStateBehaviour s) => Object.op_Implicit((Object)(object)s)).Select(delegate(ItemStateBehaviour s)
				{
					//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
					//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
					Item component = ((Component)s).GetComponent<Item>();
					return ItemData.KindOf(component).ToString() + " view=" + ((MonoBehaviourPun)component).photonView.ViewID + " charge=" + ItemData.Charge(component).ToString("F4") + " cooked=" + ItemData.Cooked(component) + " uses=" + ItemData.Uses(component) + " site=" + ItemData.Integer(component, (DataEntryKey)242, -1) + " position=" + ((object)component.transform.position/*cast due to .constrained prefix*/).ToString();
				}).ToArray();
				Report report2 = report;
				string contents = JsonUtility.ToJson((object)report2, true);
				File.WriteAllText(Path.Combine(folder, "items-state.json"), contents);
				if (Object.op_Implicit((Object)(object)frame))
				{
					File.WriteAllText(Path.Combine(folder, "items-last-active.json"), contents);
				}
			}
		}

		private void Fail(Exception e)
		{
			failed = true;
			ready = false;
			error = e.ToString();
			((BaseUnityPlugin)this).Logger.LogError((object)error);
			nextReport = 0f;
			try
			{
				ReportNow();
			}
			catch
			{
			}
		}

		private void OnDestroy()
		{
			Release();
		}

		private void Release()
		{
			if (!released)
			{
				released = true;
				SceneManager.sceneLoaded -= SceneLoaded;
				if (Object.op_Implicit((Object)(object)roomSync))
				{
					((Behaviour)roomSync).enabled = false;
					Object.Destroy((Object)(object)roomSync);
				}
				ItemTreeAPI.Struck -= TreeStruck;
				if (Factory != null)
				{
					PrefabDispatch.RegisterExtension("0_Items/TFItems/", (IPunPrefabPool)null);
				}
				Harmony obj = harmony;
				if (obj != null)
				{
					obj.UnpatchSelf();
				}
				harmony = null;
				eyes?.Dispose();
				Chests?.Dispose();
				Factory?.Dispose();
				models?.Dispose();
				Icons?.Dispose();
				ready = false;
				if ((Object)(object)Instance == (Object)(object)this)
				{
					Instance = null;
				}
			}
		}
	}
	public sealed class ModelPart
	{
		public string name;

		public string material;

		public int bite;

		public Mesh mesh;

		public Color[] normal;

		public Color[] charged;
	}
	public sealed class ModelLibrary : IDisposable
	{
		private readonly Dictionary<Kind, ModelPart[]> models = new Dictionary<Kind, ModelPart[]>();

		private readonly Dictionary<string, Material> materials = new Dictionary<string, Material>();

		private static int Count(BinaryReader r, int min, int max)
		{
			int num = r.ReadInt32();
			if (num < min || num > max)
			{
				throw new InvalidDataException("Item model count outside bounds");
			}
			return num;
		}

		private static string Text(BinaryReader r)
		{
			int num = Count(r, 1, 96);
			byte[] array = r.ReadBytes(num);
			if (array.Length != num)
			{
				throw new EndOfStreamException();
			}
			return Encoding.UTF8.GetString(array);
		}

		private static float Number(BinaryReader r)
		{
			float num = r.ReadSingle();
			if (!ItemRules.Finite(num) || Math.Abs(num) > 10000f)
			{
				throw new InvalidDataException("Invalid item vertex");
			}
			return num;
		}

		public ModelLibrary(byte[] bytes)
		{
			//IL_017e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0183: Unknown result type (might be due to invalid IL or missing references)
			//IL_019e: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01de: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0204: Unknown result type (might be due to invalid IL or missing references)
			//IL_0209: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_02dc: Expected O, but got Unknown
			//IL_0280: Unknown result type (might be due to invalid IL or missing references)
			//IL_0285: Unknown result type (might be due to invalid IL or missing references)
			//IL_0286: Unknown result type (might be due to invalid IL or missing references)
			//IL_0288: Unknown result type (might be due to invalid IL or missing references)
			//IL_028d: Unknown result type (might be due to invalid IL or missing references)
			//IL_028f: Unknown result type (might be due to invalid IL or missing references)
			if (bytes == null || bytes.Length > 4000000)
			{
				throw new InvalidDataException("Invalid item model catalog");
			}
			using MemoryStream memoryStream = new MemoryStream(bytes);
			using BinaryReader binaryReader = new BinaryReader(memoryStream);
			if (new string(binaryReader.ReadChars(4)) != "TFIM" || binaryReader.ReadInt32() != 1)
			{
				throw new InvalidDataException("Item model catalog version");
			}
			int num = Count(binaryReader, 6, 6);
			for (int i = 0; i < num; i++)
			{
				Kind kind = (Kind)Count(binaryReader, 1, 6);
				int num2 = Count(binaryReader, 1, 40);
				ModelPart[] array = new ModelPart[num2];
				for (int j = 0; j < num2; j++)
				{
					ModelPart modelPart = new ModelPart
					{
						name = Text(binaryReader),
						material = Text(binaryReader),
						bite = binaryReader.ReadInt32()
					};
					int num3 = Count(binaryReader, 3, 20000);
					int num4 = Count(binaryReader, 3, 100000);
					if (num4 % 3 != 0 || modelPart.bite < -1 || modelPart.bite > 5)
					{
						throw new InvalidDataException("Invalid item topology");
					}
					Vector3[] array2 = (Vector3[])(object)new Vector3[num3];
					Vector3[] array3 = (Vector3[])(object)new Vector3[num3];
					Vector2[] array4 = (Vector2[])(object)new Vector2[num3];
					Color[] array5 = (Color[])(object)new Color[num3];
					Color[] array6 = (Color[])(object)new Color[num3];
					for (int k = 0; k < num3; k++)
					{
						array2[k] = new Vector3(Number(binaryReader), Number(binaryReader), Number(binaryReader));
						array3[k] = new Vector3(Number(binaryReader), Number(binaryReader), Number(binaryReader));
						array4[k] = new Vector2(Number(binaryReader), Number(binaryReader));
						array5[k] = new Color(Number(binaryReader), Number(binaryReader), Number(binaryReader), Number(binaryReader));
						array6[k] = new Color(Number(binaryReader), Number(binaryReader), Number(binaryReader), Number(binaryReader));
					}
					int[] array7 = new int[num4];
					for (int l = 0; l < num4; l++)
					{
						array7[l] = Count(binaryReader, 0, num3 - 1);
					}
					if (kind == Kind.Takoyaki && modelPart.name == "Tray")
					{
						for (int m = 0; m < num3; m++)
						{
							array5[m] = (array6[m] = Color.white);
						}
					}
					modelPart.mesh = new Mesh
					{
						name = "TFItem_" + kind.ToString() + "_" + modelPart.name
					};
					modelPart.mesh.vertices = array2;
					modelPart.mesh.normals = array3;
					modelPart.mesh.uv = array4;
					modelPart.mesh.colors = array5;
					modelPart.mesh.triangles = array7;
					modelPart.mesh.RecalculateBounds();
					modelPart.normal = array5;
					modelPart.charged = array6;
					array[j] = modelPart;
				}
				models.Add(kind, array);
			}
			if (memoryStream.Position != memoryStream.Length)
			{
				throw new InvalidDataException("Trailing item model bytes");
			}
		}

		public ModelPart[] Parts(Kind kind)
		{
			return models[kind];
		}

		public Material Material(string key, bool glow = false)
		{
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00de: Expected O, but got Unknown
			//IL_01a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c7: Expected O, but got Unknown
			//IL_021d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0202: Unknown result type (might be due to invalid IL or missing references)
			//IL_0345: Unknown result type (might be due to invalid IL or missing references)
			string key2 = key + (glow ? "_Lit" : "_Unlit");
			if (materials.TryGetValue(key2, out var value))
			{
				return value;
			}
			if (glow && key.StartsWith("Owlberry_", StringComparison.Ordinal))
			{
				Shader val = Shader.Find("Thunderfen/OwlberryGlow") ?? ((IEnumerable<Shader>)Resources.FindObjectsOfTypeAll<Shader>()).FirstOrDefault((Func<Shader, bool>)((Shader s) => Object.op_Implicit((Object)(object)s) && ((Object)s).name == "Thunderfen/OwlberryGlow"));
				if (!Object.op_Implicit((Object)(object)val) || !val.isSupported)
				{
					throw new InvalidOperationException("Owlberry colour-preserving glow shader unavailable");
				}
				Material val2 = new Material(val)
				{
					name = "TFItem_" + key + "_GentleGlow",
					hideFlags = (HideFlags)61
				};
				materials.Add(key2, val2);
				return val2;
			}
			bool flag = key.Contains("Glass") || (key.Contains("Ice") && !key.Contains("Glow"));
			glow = glow && !flag;
			string native = ((!flag) ? (glow ? "M_Scout_Star_Antizooka" : "M_Apple") : (key.StartsWith("ChargedMilk_", StringComparison.Ordinal) ? "Jug Glass" : "LanternGlass"));
			Material val3 = ((IEnumerable<Material>)Resources.FindObjectsOfTypeAll<Material>()).FirstOrDefault((Func<Material, bool>)((Material m) => Object.op_Implicit((Object)(object)m) && ((Object)m).name == native));
			if (!Object.op_Implicit((Object)(object)val3))
			{
				throw new InvalidOperationException("Native item material unavailable: " + native);
			}
			Material val4 = new Material(val3)
			{
				name = "TFItem_" + key,
				hideFlags = (HideFlags)61
			};
			string[] array = new string[2] { "_Tint", "_BaseColor" };
			foreach (string text in array)
			{
				if (val4.HasProperty(text))
				{
					val4.SetColor(text, (Color)(flag ? new Color(0.88f, 0.94f, 1f, 0.3f) : Color.white));
				}
			}
			if (val4.HasProperty("_BaseTexAmount"))
			{
				val4.SetFloat("_BaseTexAmount", 0f);
			}
			if (val4.HasProperty("_BaseTexture"))
			{
				val4.SetTexture("_BaseTexture", (Texture)(object)Texture2D.whiteTexture);
			}
			if (!flag)
			{
				string[] array2 = new string[5] { "_MainTex", "_Texture1", "_Texture2", "_Texture3", "_Texture4" };
				foreach (string text2 in array2)
				{
					if (val4.HasProperty(text2))
					{
						val4.SetTexture(text2, (Texture)(object)Texture2D.whiteTexture);
					}
				}
				string[] array3 = new string[5] { "_Color1", "_Color2", "_Color21", "_Color3", "_Color4" };
				foreach (string text3 in array3)
				{
					if (val4.HasProperty(text3))
					{
						val4.SetColor(text3, Color.white);
					}
				}
			}
			string[] array4 = new string[5] { "_UseSkinTone", "_UseTextureAlpha", "_Stepalphabyvertexcolor", "_HueStr1", "_HueStr2" };
			foreach (string text4 in array4)
			{
				if (val4.HasProperty(text4))
				{
					val4.SetFloat(text4, 0f);
				}
			}
			string[] array5 = new string[2] { "_VertexColorAmount", "_UseRawVertexColor" };
			foreach (string text5 in array5)
			{
				if (val4.HasProperty(text5))
				{
					val4.SetFloat(text5, 1f);
				}
			}
			if (val4.HasProperty("_BaseMetallic"))
			{
				val4.SetFloat("_BaseMetallic", (key.Contains("Metal") || key.Contains("Foil")) ? 0.7f : 0f);
			}
			if (val4.HasProperty("_StatusGlow"))
			{
				val4.SetFloat("_StatusGlow", 0f);
			}
			materials.Add(key2, val4);
			return val4;
		}

		public GameObject Build(Kind kind, Transform parent)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Expected O, but got Unknown
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Expected O, but got Unknown
			GameObject val = new GameObject("ThunderfenItemModel");
			val.transform.SetParent(parent, false);
			ModelPart[] array = Parts(kind);
			foreach (ModelPart modelPart in array)
			{
				GameObject val2 = new GameObject(modelPart.name);
				val2.transform.SetParent(val.transform, false);
				val2.AddComponent<MeshFilter>().sharedMesh = modelPart.mesh;
				MeshRenderer val3 = val2.AddComponent<MeshRenderer>();
				((Renderer)val3).sharedMaterial = Material(modelPart.material);
				((Renderer)val3).shadowCastingMode = (ShadowCastingMode)(!modelPart.material.Contains("Glass"));
				((Renderer)val3).receiveShadows = true;
			}
			return val;
		}

		public void Dispose()
		{
			foreach (ModelPart[] value in models.Values)
			{
				ModelPart[] array = value;
				foreach (ModelPart modelPart in array)
				{
					if (Object.op_Implicit((Object)(object)modelPart.mesh))
					{
						Object.Destroy((Object)(object)modelPart.mesh);
					}
				}
			}
			foreach (Material value2 in materials.Values)
			{
				if (Object.op_Implicit((Object)(object)value2))
				{
					Object.Destroy((Object)(object)value2);
				}
			}
			models.Clear();
			materials.Clear();
		}
	}
	public sealed class ItemModelView : MonoBehaviour
	{
		public Kind kind;

		public GameObject root;

		public ModelPart[] parts;

		private Renderer[] renderers;

		private Material[] unlit;

		private Material[] lit;

		private List<Mesh> owned;

		private bool fruitCharged;

		private bool lastPlanted;

		private float lastProgress = -1f;

		private int lastUses = -1;

		private MaterialPropertyBlock block;

		private Transform arcs;

		private Transform core;

		private void Awake()
		{
			Item component = ((Component)this).GetComponent<Item>();
			if (ItemData.IsCustom(component))
			{
				Apply(ItemData.Charge(component), ItemData.Uses(component));
			}
		}

		private bool Bind()
		{
			Item component = ((Component)this).GetComponent<Item>();
			if (ItemData.IsCustom(component))
			{
				kind = ItemData.KindOf(component);
			}
			if (!Object.op_Implicit((Object)(object)root))
			{
				Transform val = ((Component)this).transform.Find("ThunderfenItemModel");
				if (Object.op_Implicit((Object)(object)val))
				{
					root = ((Component)val).gameObject;
				}
			}
			if (parts == null && Object.op_Implicit((Object)(object)ItemsTrial.Instance) && ItemsTrial.Instance.Factory != null)
			{
				parts = ItemsTrial.Instance.Factory.ModelParts(kind);
			}
			return Object.op_Implicit((Object)(object)root) && parts != null;
		}

		private static void Glow(MaterialPropertyBlock block, Color color, float strength)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			block.SetColor("_EmissionColor", color * strength);
			block.SetColor("_StatusColor", color);
			block.SetFloat("_StatusGlow", strength);
		}

		public void Apply(float stored, int uses, bool force = false)
		{
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Expected O, but got Unknown
			//IL_01b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_0674: Unknown result type (might be due to invalid IL or missing references)
			//IL_0685: Unknown result type (might be due to invalid IL or missing references)
			//IL_06a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_024d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0261: Unknown result type (might be due to invalid IL or missing references)
			//IL_0267: Unknown result type (might be due to invalid IL or missing references)
			//IL_026c: Unknown result type (might be due to invalid IL or missing references)
			//IL_05f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0600: Unknown result type (might be due to invalid IL or missing references)
			if (!Bind())
			{
				return;
			}
			OwlberryPlant owlberryPlant = ((kind == Kind.Owlberry) ? ((Component)this).GetComponent<OwlberryPlant>() : null);
			owlberryPlant?.Apply();
			bool flag = Object.op_Implicit((Object)(object)owlberryPlant) && owlberryP

plugins/ThunderfenLightning/PoisonForestLightning.dll

Decompiled a week ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security.Cryptography;
using System.Text;
using BepInEx;
using ExitGames.Client.Photon;
using Microsoft.CodeAnalysis;
using Photon.Pun;
using Photon.Realtime;
using PoisonForest;
using PoisonForestSolo;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.SceneManagement;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyVersion("0.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace PoisonForestLightning
{
	[Serializable]
	public sealed class Grant
	{
		public int seq;

		public int actor;

		public int view;

		public int tree;

		public float amount;

		public float targetX;

		public float targetY;

		public float targetZ;

		public bool burst;

		public double expires;
	}
	[Serializable]
	public sealed class TransferStrike
	{
		public int seq;

		public int tree;

		public int actor;

		public int view;

		public float amount;

		public float sx;

		public float sy;

		public float sz;

		public float tx;

		public float ty;

		public float tz;

		public double at;
	}
	[Serializable]
	public sealed class SharedState
	{
		public string epoch;

		public string protocol;

		public string catalog;

		public int owner;

		public int snapshotSerial;

		public int serial;

		public int grantSerial;

		public int lastTree = -1;

		public int lastActor;

		public int warningTree = -1;

		public int warningActor;

		public bool automatic = true;

		public double snapshotAt;

		public double nextStrikeAt;

		public double warningAt;

		public double lastStrikeAt;

		public float abandonedCharge;

		public float[] charges;

		public float[] transferRemaining;

		public bool[] transferOccupied;

		public Grant[] grants = new Grant[0];

		public TransferStrike[] bursts = new TransferStrike[0];
	}
	[Serializable]
	public sealed class Ack
	{
		public string epoch;

		public int seq;

		public float used;
	}
	public sealed class GrantReceipts
	{
		private string epoch;

		private readonly Dictionary<int, float> used = new Dictionary<int, float>();

		private void Scope(string current)
		{
			if (epoch != current)
			{
				epoch = current;
				used.Clear();
			}
		}

		public bool TryRead(string current, int seq, out float value)
		{
			Scope(current);
			return used.TryGetValue(seq, out value);
		}

		public void Record(string current, int seq, float value)
		{
			Scope(current);
			used[seq] = value;
		}
	}
	public static class StormModel
	{
		public static float[] InitialCharges(int count, int seed, float fraction, float amount)
		{
			if (count < 0 || !Finite(fraction) || fraction < 0f || fraction > 1f || !Finite(amount) || amount < 0f)
			{
				throw new ArgumentOutOfRangeException();
			}
			float[] array = new float[count];
			int[] array2 = Enumerable.Range(0, count).ToArray();
			Random random = new Random(seed ^ 0x54F10A);
			for (int num = count - 1; num > 0; num--)
			{
				int num2 = random.Next(num + 1);
				int num3 = array2[num];
				array2[num] = array2[num2];
				array2[num2] = num3;
			}
			int num4 = (int)Math.Floor((double)count * (double)fraction + 0.5);
			for (int i = 0; i < num4; i++)
			{
				array[array2[i]] = amount;
			}
			return array;
		}

		public static bool Finite(double n)
		{
			return !double.IsNaN(n) && !double.IsInfinity(n);
		}

		public static double Next(double now, double random, double min, double max)
		{
			return now + min + Math.Max(0.0, Math.Min(1.0, random)) * (max - min);
		}

		public static float Strike(SharedState s, int tree, float amount, float cap)
		{
			float num = s.charges[tree];
			float num2 = s.grants.Where((Grant g) => g.tree == tree).Sum((Grant g) => g.amount);
			s.charges[tree] = Math.Min(Math.Max(0f, cap - num2), num + amount);
			return s.charges[tree] - num;
		}

		public static Grant Reserve(SharedState s, int actor, int view, int tree, float requested, double now, double lifetime)
		{
			if (s.grants.Any((Grant g) => g.actor == actor) || tree < 0 || tree >= s.charges.Length || !Finite(requested) || requested <= 0f)
			{
				return null;
			}
			float num = Math.Min(s.charges[tree], requested);
			if (num <= 1E-06f)
			{
				return null;
			}
			Grant grant = new Grant
			{
				seq = ++s.grantSerial,
				actor = actor,
				view = view,
				tree = tree,
				amount = num,
				expires = now + lifetime
			};
			s.charges[tree] = Math.Max(0f, s.charges[tree] - num);
			s.grants = s.grants.Concat(new Grant[1] { grant }).ToArray();
			return grant;
		}

		public static bool Resolve(SharedState s, int actor, int seq, float used, float cap)
		{
			Grant g = s.grants.FirstOrDefault((Grant x) => x.actor == actor && x.seq == seq);
			if (g == null || !Finite(used) || used < 0f || used > g.amount + 1E-05f)
			{
				return false;
			}
			float num = s.grants.Where((Grant x) => x != g && x.tree == g.tree).Sum((Grant x) => x.amount);
			s.charges[g.tree] = Math.Min(Math.Max(0f, cap - num), s.charges[g.tree] + Math.Max(0f, g.amount - used));
			s.grants = s.grants.Where((Grant x) => x != g).ToArray();
			return true;
		}

		public static float Accepted(float offered, float current, float cap, bool eligible)
		{
			return eligible ? Math.Max(0f, Math.Min(offered, cap - current)) : 0f;
		}

		public static void Abandon(SharedState s, int actor)
		{
			s.abandonedCharge += s.grants.Where((Grant g) => g.actor == actor).Sum((Grant g) => g.amount);
			s.grants = s.grants.Where((Grant g) => g.actor != actor).ToArray();
		}

		public static int Nearest(double[] squaredDistances)
		{
			int result = -1;
			double num = double.PositiveInfinity;
			for (int i = 0; i < squaredDistances.Length; i++)
			{
				if (Finite(squaredDistances[i]) && squaredDistances[i] < num - 1E-08)
				{
					num = squaredDistances[i];
					result = i;
				}
			}
			return result;
		}

		public static bool AdvanceTransfer(SharedState s, int tree, double delta, bool occupied, float interval)
		{
			float num = s.charges[tree] + s.grants.Where((Grant g) => g.tree == tree).Sum((Grant g) => g.amount);
			if (num <= 1E-06f)
			{
				s.transferRemaining[tree] = interval;
				return false;
			}
			if (!occupied)
			{
				return false;
			}
			s.transferRemaining[tree] = Math.Max(0f, s.transferRemaining[tree] - (float)Math.Max(0.0, delta));
			return s.transferRemaining[tree] <= 1E-06f && s.charges[tree] > 1E-06f;
		}

		public static Grant FireTransfer(SharedState s, int tree, int actor, int view, float amount, double now, double lifetime, float interval)
		{
			if (s.transferRemaining[tree] > 1E-06f)
			{
				return null;
			}
			Grant grant = Reserve(s, actor, view, tree, amount, now, lifetime);
			if (grant != null)
			{
				grant.burst = true;
				s.transferRemaining[tree] = interval;
			}
			return grant;
		}

		public static int RandomTarget(int count, double draw)
		{
			return (count <= 0) ? (-1) : Math.Min(count - 1, (int)(Math.Max(0.0, Math.Min(1.0, draw)) * (double)count));
		}

		public static void PruneBursts(SharedState s, double now)
		{
			HashSet<int> pending = new HashSet<int>(s.grants.Select((Grant g) => g.seq));
			TransferStrike[] array = s.bursts.Where((TransferStrike b) => pending.Contains(b.seq)).ToArray();
			IEnumerable<TransferStrike> second = (from b in s.bursts
				where !pending.Contains(b.seq) && now - b.at <= 6.0
				orderby b.seq descending
				select b).Take(Math.Max(0, 64 - array.Length));
			s.bursts = (from b in array.Concat(second)
				orderby b.seq
				select b).ToArray();
		}

		public static bool Validate(SharedState s, int count, float cap, float interval = 3f)
		{
			if (s == null || string.IsNullOrEmpty(s.epoch) || s.charges == null || s.charges.Length != count || s.transferRemaining == null || s.transferRemaining.Length != count || s.transferOccupied == null || s.transferOccupied.Length != count || s.grants == null || s.grants.Length > 16 || s.bursts == null || s.bursts.Length > 64 || !Finite(s.nextStrikeAt) || !Finite(s.warningAt) || !Finite(s.lastStrikeAt) || s.warningTree < -1 || s.warningTree >= count || s.lastTree < -1 || s.lastTree >= count || s.serial < 0 || s.grantSerial < 0)
			{
				return false;
			}
			if (s.charges.Any((float q) => !Finite(q) || q < 0f || q > cap + 1E-05f) || s.transferRemaining.Any((float q) => !Finite(q) || q < 0f || q > interval + 1E-05f) || s.grants.Any((Grant g) => g == null) || s.grants.Select((Grant g) => g.actor).Distinct().Count() != s.grants.Length || s.grants.Select((Grant g) => g.seq).Distinct().Count() != s.grants.Length)
			{
				return false;
			}
			if (!s.grants.All((Grant g) => g.seq > 0 && g.seq <= s.grantSerial && g.actor > 0 && g.view > 0 && g.tree >= 0 && g.tree < count && Finite(g.amount) && g.amount > 0f && g.amount <= cap && Finite(g.expires) && (!g.burst || (Finite(g.targetX) && Finite(g.targetY) && Finite(g.targetZ)))))
			{
				return false;
			}
			int i;
			for (i = 0; i < count; i++)
			{
				if (s.charges[i] + s.grants.Where((Grant g) => g.tree == i).Sum((Grant g) => g.amount) > cap + 1E-05f)
				{
					return false;
				}
			}
			int num = 0;
			TransferStrike[] bursts = s.bursts;
			foreach (TransferStrike transferStrike in bursts)
			{
				if (transferStrike == null || transferStrike.seq <= num || transferStrike.seq > s.grantSerial || transferStrike.tree < 0 || transferStrike.tree >= count || transferStrike.actor <= 0 || transferStrike.view <= 0 || !Finite(transferStrike.at) || !Finite(transferStrike.amount) || transferStrike.amount <= 0f || transferStrike.amount > cap || !Finite(transferStrike.sx) || !Finite(transferStrike.sy) || !Finite(transferStrike.sz) || !Finite(transferStrike.tx) || !Finite(transferStrike.ty) || !Finite(transferStrike.tz))
				{
					return false;
				}
				num = transferStrike.seq;
			}
			return true;
		}
	}
	[BepInDependency("local.peak.poisonforest.solo", "0.5.0")]
	[DefaultExecutionOrder(1000)]
	[BepInPlugin("local.peak.poisonforest.lightning", "Thunderfen Lightning", "1.0.0")]
	[BepInDependency("local.peak.poisonforest.electrical", "0.1.5")]
	public sealed class StormTrial : BaseUnityPlugin
	{
		[Serializable]
		public sealed class Settings
		{
			public float firstStrikeDelay = 12f;

			public float minInterval = 25f;

			public float maxInterval = 45f;

			public float warningSeconds = 1.2f;

			public float chargePerStrike = 0.5f;

			public float treeCapacity = 1f;

			public float transferAmount = 0.1f;

			public float transferInterval = 8f;

			public float transferRadius = 8f;

			public float grantLifetime = 4f;

			public float effectsDistance = 60f;

			public float initialChargedFraction = 0.1f;

			public float initialTreeCharge = 0.5f;

			public bool automatic = true;

			public bool reducedFlashes = false;
		}

		[Serializable]
		public sealed class Catalog
		{
			public int version;

			public int treeCount;

			public string biomeId;

			public string bundleSha256;

			public Variant[] variants;
		}

		[Serializable]
		public sealed class Variant
		{
			public int id;

			public Segment[] segments;

			public Anchor[] anchors;

			public Vector3 strike;
		}

		[Serializable]
		public sealed class Segment
		{
			public Vector3 a;

			public Vector3 b;
		}

		[Serializable]
		public sealed class Anchor
		{
			public Vector3 p;

			public Vector3 normal;

			public int ring;

			public int side;
		}

		public sealed class Tree
		{
			public int id;

			public Transform root;

			public Variant variant;

			public Vector3 strike;

			public Segment[] segments;

			public Renderer foliage;

			public Matrix4x4 cachedMatrix;

			public float fieldBottom;

			public float fieldTop;

			public float DisplayCharge(SharedState s)
			{
				return s.charges[id] + s.grants.Where((Grant g) => g.tree == id).Sum((Grant g) => g.amount);
			}
		}

		private sealed class Person
		{
			public Character c;

			public int actor;

			public int view;
		}

		[Serializable]
		private sealed class Status
		{
			public string utc;

			public string version;

			public string message;

			public string error;

			public string epoch;

			public string transferStatus;

			public bool ready;

			public bool compatible;

			public bool master;

			public bool inRun;

			public bool inside;

			public bool automatic;

			public bool visualsReady;

			public int trees;

			public int chargedTrees;

			public int warningTree;

			public int lastTree;

			public int lastActor;

			public int strikes;

			public int pendingGrants;

			public int transferTree;

			public float totalReservoir;

			public float reservedCharge;

			public float localCharge;

			public float transferRadius;

			public float transferDistance;

			public float transferAmountPoints;

			public float transferInterval;

			public float transferRemaining;

			public float treeChargePoints;

			public float fieldBottom;

			public float fieldTop;

			public double nextStrikeAt;

			public double now;

			public Vector3 localPosition;

			public int receivedOffers;

			public int appliedOffers;

			public int declinedOffers;

			public int retriedOffers;

			public int acknowledgedOffers;

			public int receivedSnapshots;

			public int acceptedSnapshots;

			public int rejectedSnapshots;

			public int shownTransferCount;

			public string snapshotRejection;
		}

		public const string Id = "local.peak.poisonforest.lightning";

		public const string Version = "1.0.0";

		private const string ProtocolKey = "PF_LProtocol";

		private const string StateKey = "PF_LState";

		private const string AckKey = "PF_LAck";

		private Settings settings;

		private Catalog catalog;

		private Tree[] trees;

		private Transform root;

		private Transform floor;

		private SharedState shared;

		private StormVisuals visuals;

		private string streamedRaw;

		private string lastStateSignature;

		private float nextRecovery;

		private string protocol;

		private string catalogHash;

		private string folder;

		private string lastRaw;

		private string error;

		private string message = "Waiting for the custom forest";

		private string lastEpoch;

		private int lastStrike = -1;

		private bool ready;

		private bool compatible;

		private bool master;

		private bool localInside;

		private float nextPoll;

		private float nextTick;

		private float nextReport;

		private double lastHostStep;

		private readonly Random random = new Random();

		private readonly RaycastHit[] hits = (RaycastHit[])(object)new RaycastHit[96];

		private readonly DischargeReceiver receiver = new DischargeReceiver();

		private readonly Dictionary<int, DischargeOffer> offers = new Dictionary<int, DischargeOffer>();

		private readonly Dictionary<int, double> nextOffer = new Dictionary<int, double>();

		private readonly Dictionary<int, string> waitingOffers = new Dictionary<int, string>();

		private readonly HashSet<int> shownTransfers = new HashSet<int>();

		private string offersEpoch;

		private string snapshotRejection;

		private int receivedOffers;

		private int appliedOffers;

		private int declinedOffers;

		private int retriedOffers;

		private int acknowledgedOffers;

		private int receivedSnapshots;

		private int acceptedSnapshots;

		private int rejectedSnapshots;

		private int shownTransferCount;

		private float transferDistance = -1f;

		private int transferTree = -1;

		private string transferStatus = "Waiting for forest";

		private string lastTransferLog;

		private static readonly FieldInfo electricalReady = typeof(ElectricalTrial).GetField("ready", BindingFlags.Instance | BindingFlags.NonPublic);

		private static readonly FieldInfo electricalFailed = typeof(ElectricalTrial).GetField("failed", BindingFlags.Instance | BindingFlags.NonPublic);

		private static readonly FieldInfo electricalCompatible = typeof(ElectricalTrial).GetField("compatible", BindingFlags.Instance | BindingFlags.NonPublic);

		private bool ActiveRoot => Object.op_Implicit((Object)(object)root) && Object.op_Implicit((Object)(object)floor) && ((Component)floor).gameObject.activeInHierarchy && trees != null;

		public static string Sha(byte[] data)
		{
			using SHA256 sHA = SHA256.Create();
			return BitConverter.ToString(sHA.ComputeHash(data)).Replace("-", "");
		}

		private void Awake()
		{
			ItemTreeAPI.ChargeAt = (int i) => (shared != null && shared.charges != null && i >= 0 && i < shared.charges.Length) ? shared.charges[i] : 0f;
			folder = Path.Combine(Application.persistentDataPath, "PoisonForestLightning");
			Directory.CreateDirectory(folder);
			try
			{
				byte[] bytes = File.ReadAllBytes(Path.Combine(Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location), "PoisonForestLightning.settings.json"));
				settings = JsonUtility.FromJson<Settings>(Encoding.UTF8.GetString(bytes));
				if (settings == null || !Valid(settings.firstStrikeDelay, 1f, 300f) || !Valid(settings.minInterval, 3f, 600f) || !Valid(settings.maxInterval, settings.minInterval, 900f) || !Valid(settings.warningSeconds, 0.3f, 5f) || !Valid(settings.chargePerStrike, 0.01f, 5f) || !Valid(settings.treeCapacity, settings.chargePerStrike, 10f) || !Valid(settings.transferAmount, 0.001f, 1f) || !Valid(settings.transferInterval, 0.3f, 60f) || !Valid(settings.transferRadius, 0.5f, 10f) || !Valid(settings.grantLifetime, 1f, 15f) || !Valid(settings.effectsDistance, 20f, 150f) || !Valid(settings.initialChargedFraction, 0f, 1f) || !Valid(settings.initialTreeCharge, 0f, settings.treeCapacity))
				{
					throw new Exception("Invalid lightning settings.");
				}
				using (Stream stream = typeof(StormTrial).Assembly.GetManifestResourceStream("PoisonForestLightning.TreeCatalog.bin"))
				{
					if (stream == null)
					{
						throw new Exception("Missing binary authored tree catalog.");
					}
					using MemoryStream memoryStream = new MemoryStream();
					stream.CopyTo(memoryStream);
					byte[] array = memoryStream.ToArray();
					catalogHash = Sha(array);
					TreeCatalogData treeCatalogData = TreeCatalogData.Read(array);
					catalog = new Catalog
					{
						version = treeCatalogData.version,
						treeCount = treeCatalogData.treeCount,
						biomeId = treeCatalogData.biomeId,
						bundleSha256 = treeCatalogData.bundleSha256,
						variants = treeCatalogData.variants.Select((TreeCatalogData.Variant v) => new Variant
						{
							id = v.id,
							strike = Vector(v.strike),
							segments = v.segments.Select((TreeCatalogData.Segment s) => new Segment
							{
								a = Vector(s.a),
								b = Vector(s.b)
							}).ToArray(),
							anchors = v.anchors.Select((TreeCatalogData.Anchor a) => new Anchor
							{
								p = Vector(a.p),
								normal = Vector(a.normal),
								ring = a.ring,
								side = a.side
							}).ToArray()
						}).ToArray()
					};
				}
				if (catalog == null || catalog.version != 1 || catalog.treeCount != 76 || catalog.variants == null || catalog.variants.Length != 12)
				{
					throw new Exception("Unexpected authored tree catalog.");
				}
				Log("catalog-loaded", catalog.treeCount + " source templates; " + catalog.variants.Length + " variants; binary=" + catalogHash);
				protocol = "0.3.3:" + Sha(Encoding.UTF8.GetBytes(JsonUtility.ToJson((object)settings))).Substring(0, 12) + ":" + catalogHash.Substring(0, 12);
				SharedWorld.Message += OnShared;
				ready = true;
				Log("started", "Independent lightning; first=" + settings.firstStrikeDelay + "s intervals=" + settings.minInterval + ".." + settings.maxInterval + "s; tree=" + settings.chargePerStrike + " cap=" + settings.treeCapacity + " burst=" + settings.transferAmount + " every=" + settings.transferInterval + "s radius=" + settings.transferRadius + "; no rain dependency.");
			}
			catch (Exception e)
			{
				Fail(e);
			}
		}

		private static Vector3 Vector(TreeCatalogData.Point p)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			return new Vector3(p.x, p.y, p.z);
		}

		private static bool Valid(float v, float min, float max)
		{
			return StormModel.Finite(v) && v >= min && v <= max;
		}

		private static bool InRun()
		{
			//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)
			Scene sceneByName = SceneManager.GetSceneByName("WilIsland");
			return ((Scene)(ref sceneByName)).isLoaded;
		}

		private void Update()
		{
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d2: Expected O, but got Unknown
			//IL_00da: Expected O, but got Unknown
			if (!ready)
			{
				return;
			}
			try
			{
				if (!PhotonNetwork.InRoom)
				{
					ResetLocal();
					Report();
					return;
				}
				Advertise();
				compatible = SharedWorld.Ready && PhotonNetwork.PlayerList.Where((Player p) => !p.IsInactive).All((Player p) => p.CustomProperties[(object)"PF_LProtocol"] is string text && text == protocol);
				if (!InRun())
				{
					if (PhotonNetwork.IsMasterClient && ((RoomInfo)PhotonNetwork.CurrentRoom).CustomProperties[(object)"PF_LState"] != null)
					{
						Room currentRoom = PhotonNetwork.CurrentRoom;
						Hashtable val = new Hashtable();
						((Dictionary<object, object>)val).Add((object)"PF_LState", (object)null);
						currentRoom.SetCustomProperties(val, (Hashtable)null, (WebFlags)null);
					}
					ResetLocal();
					Report();
					return;
				}
				if (Time.unscaledTime >= nextPoll)
				{
					nextPoll = Time.unscaledTime + 1f;
					FindRoot();
				}
				if (ActiveRoot)
				{
					RefreshGeometry();
				}
				Character localCharacter = Character.localCharacter;
				localInside = ActiveRoot && Eligible(localCharacter) && OnBiome(localCharacter);
				bool isMasterClient = PhotonNetwork.IsMasterClient;
				if (!isMasterClient || shared == null)
				{
					ReadShared();
				}
				if (isMasterClient && !master)
				{
					lastHostStep = PhotonNetwork.Time;
				}
				master = isMasterClient;
				if (compatible && ActiveRoot && master && shared == null)
				{
					shared = new SharedState
					{
						epoch = (SharedWorld.Online ? SharedWorld.Epoch : Guid.NewGuid().ToString("N")),
						protocol = protocol,
						catalog = catalogHash,
						owner = PhotonNetwork.LocalPlayer.ActorNumber,
						charges = StormModel.InitialCharges(trees.Length, RunData.Seed, settings.initialChargedFraction, settings.initialTreeCharge),
						transferRemaining = Enumerable.Repeat(settings.transferInterval, trees.Length).ToArray(),
						transferOccupied = new bool[trees.Length],
						automatic = settings.automatic
					};
					Publish();
				}
				if (!compatible)
				{
					message = "Waiting for matching lightning trial on all players";
					if (visuals != null)
					{
						visuals.Clear();
					}
					Report();
					return;
				}
				if (ActiveRoot && visuals == null)
				{
					visuals = new StormVisuals(root, settings);
				}
				if (shared != null)
				{
					if (offersEpoch != shared.epoch)
					{
						offersEpoch = shared.epoch;
						offers.Clear();
						shownTransfers.Clear();
						waitingOffers.Clear();
					}
					QueueSnapshotOffers();
					if (master && ActiveRoot && Time.unscaledTime >= nextTick)
					{
						nextTick = Time.unscaledTime + 0.2f;
						HostTick();
					}
					if (ActiveRoot)
					{
						if (visuals == null)
						{
							visuals = new StormVisuals(root, settings);
						}
						if (lastEpoch != shared.epoch)
						{
							lastEpoch = shared.epoch;
							lastStrike = shared.serial;
						}
						double time = PhotonNetwork.Time;
						if (shared.serial != lastStrike)
						{
							lastStrike = shared.serial;
							if (shared.lastTree >= 0 && time - shared.lastStrikeAt < 0.9)
							{
								visuals.Strike(trees[shared.lastTree], shared.serial);
							}
						}
						TransferStrike[] bursts = shared.bursts;
						foreach (TransferStrike transferStrike in bursts)
						{
							if (time - transferStrike.at < 1.0 && time - transferStrike.at >= -0.1)
							{
								ShowTransfer(transferStrike);
							}
						}
						visuals.Tick(trees, shared, localInside ? localCharacter : null, time);
					}
					else if (visuals != null)
					{
						visuals.Clear();
					}
				}
				ProcessOffers(localCharacter);
				message = ((!ActiveRoot) ? "Waiting for custom forest" : ((shared == null) ? "Waiting for host lightning state" : ((!localInside) ? "Lightning affects the custom forest" : ((shared.warningTree >= 0) ? ("Lightning is gathering at tree " + shared.warningTree.ToString("D3")) : "Charged trees fire timed discharges at nearby players"))));
				Report();
			}
			catch (Exception e)
			{
				Fail(e);
			}
		}

		private void ResetLocal()
		{
			offers.Clear();
			nextOffer.Clear();
			shownTransfers.Clear();
			offersEpoch = null;
			root = null;
			floor = null;
			trees = null;
			shared = null;
			lastRaw = null;
			lastEpoch = null;
			streamedRaw = null;
			lastStateSignature = null;
			master = false;
			localInside = false;
			message = "Waiting for a run";
			if (visuals != null)
			{
				visuals.Dispose();
				visuals = null;
			}
		}

		private void Advertise()
		{
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Expected O, but got Unknown
			//IL_0054: Expected O, but got Unknown
			if (!(PhotonNetwork.LocalPlayer.CustomProperties[(object)"PF_LProtocol"] is string text) || text != protocol)
			{
				Player localPlayer = PhotonNetwork.LocalPlayer;
				Hashtable val = new Hashtable();
				((Dictionary<object, object>)val).Add((object)"PF_LProtocol", (object)protocol);
				localPlayer.SetCustomProperties(val, (Hashtable)null, (WebFlags)null);
			}
		}

		private void ReadShared()
		{
			if (trees != null)
			{
				ReadCandidate(streamedRaw);
				ReadCandidate(((RoomInfo)PhotonNetwork.CurrentRoom).CustomProperties[(object)"PF_LState"] as string);
			}
		}

		private void ReadCandidate(string raw)
		{
			if (string.IsNullOrEmpty(raw) || raw == lastRaw)
			{
				return;
			}
			string rejected;
			SharedState sharedState = LightningSnapshot.Candidate(raw, shared, protocol, catalogHash, SharedWorld.Online ? SharedWorld.Epoch : null, PhotonNetwork.MasterClient.ActorNumber, trees.Length, settings.treeCapacity, settings.transferInterval, out rejected);
			if (rejected != null)
			{
				if (snapshotRejection != rejected)
				{
					snapshotRejection = rejected;
					rejectedSnapshots++;
					Log("snapshot-rejected", rejected);
				}
			}
			else if (sharedState != null)
			{
				shared = sharedState;
				lastRaw = raw;
				acceptedSnapshots++;
				snapshotRejection = "";
			}
		}

		private void Publish()
		{
			//IL_01a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b4: Expected O, but got Unknown
			//IL_01bc: Expected O, but got Unknown
			shared.owner = PhotonNetwork.LocalPlayer.ActorNumber;
			shared.snapshotAt = PhotonNetwork.Time;
			shared.snapshotSerial++;
			byte[] array = LightningSnapshot.Encode(shared, trees.Length, settings.treeCapacity, settings.transferInterval);
			string value = LightningSnapshot.Room(array);
			string text = shared.serial + ":" + shared.grantSerial + ":" + shared.warningTree + ":" + shared.automatic + ":" + string.Join(",", shared.grants.Select((Grant g) => g.seq));
			bool flag = text != lastStateSignature;
			lastStateSignature = text;
			if (SharedWorld.Online)
			{
				SharedWorld.Emit("lightning", new object[2] { array, shared.snapshotAt }, flag);
			}
			if (!SharedWorld.Online || flag || Time.unscaledTime >= nextRecovery)
			{
				nextRecovery = Time.unscaledTime + 2f;
				Room currentRoom = PhotonNetwork.CurrentRoom;
				Hashtable val = new Hashtable();
				((Dictionary<object, object>)val).Add((object)"PF_LState", (object)value);
				currentRoom.SetCustomProperties(val, (Hashtable)null, (WebFlags)null);
			}
			lastRaw = value;
		}

		private void OnShared(string kind, string id, object[] data)
		{
			if (kind == "lightning" && data != null && data.Length == 2 && data[0] is byte[] array && array.Length <= 65536)
			{
				receivedSnapshots++;
				streamedRaw = LightningSnapshot.Room(array);
			}
			else if (kind == "tree-discharge" && trees != null)
			{
				DischargeOffer dischargeOffer = DischargeWire.Read(data, SharedWorld.Epoch, trees.Length, settings.treeCapacity);
				if (dischargeOffer == null)
				{
					Log("offer-rejected", "invalid discharge packet");
					return;
				}
				receivedOffers++;
				QueueOffer(dischargeOffer, "reliable");
			}
		}

		private void QueueOffer(DischargeOffer offer, string source)
		{
			string text = (SharedWorld.Online ? SharedWorld.Epoch : shared?.epoch);
			if (!(offer.epoch != text))
			{
				if (offersEpoch != text)
				{
					offersEpoch = text;
					offers.Clear();
					shownTransfers.Clear();
				}
				bool flag = !offers.ContainsKey(offer.grant.seq);
				offers[offer.grant.seq] = offer;
				if (flag)
				{
					Log("offer-received", "epoch=" + text + " seq=" + offer.grant.seq + " actor=" + offer.grant.actor + " view=" + offer.grant.view + " tree=" + offer.grant.tree + " source=" + source);
				}
			}
		}

		private void QueueSnapshotOffers()
		{
			Grant[] grants = shared.grants;
			foreach (Grant g in grants)
			{
				TransferStrike transferStrike = shared.bursts.FirstOrDefault((TransferStrike b) => b.seq == g.seq);
				if (transferStrike != null)
				{
					QueueOffer(new DischargeOffer
					{
						epoch = shared.epoch,
						grant = g,
						hit = transferStrike
					}, "snapshot");
				}
			}
		}

		private bool ShowTransfer(TransferStrike hit)
		{
			if (!ActiveRoot || visuals == null || shownTransfers.Contains(hit.seq))
			{
				return false;
			}
			Character target = ((IEnumerable<Character>)Resources.FindObjectsOfTypeAll<Character>()).FirstOrDefault((Func<Character, bool>)((Character c) => Object.op_Implicit((Object)(object)c) && Object.op_Implicit((Object)(object)((MonoBehaviourPun)c).photonView) && ((MonoBehaviourPun)c).photonView.ViewID == hit.view));
			if (!visuals.TransferStrike(trees[hit.tree], hit, target))
			{
				return false;
			}
			shownTransfers.Add(hit.seq);
			shownTransferCount++;
			Log("transfer-visual", "epoch=" + offersEpoch + " seq=" + hit.seq + " actor=" + hit.actor + " view=" + hit.view);
			return true;
		}

		private void FindRoot()
		{
			//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_00a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00af: Expected O, but got Unknown
			//IL_0278: Unknown result type (might be due to invalid IL or missing references)
			//IL_027d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0282: Unknown result type (might be due to invalid IL or missing references)
			if (Object.op_Implicit((Object)(object)root) && trees != null)
			{
				return;
			}
			Scene sceneByName = SceneManager.GetSceneByName("WilIsland");
			GameObject val = ((IEnumerable<GameObject>)((Scene)(ref sceneByName)).GetRootGameObjects()).FirstOrDefault((Func<GameObject, bool>)((GameObject g) => ((Object)g).name == "Map"));
			if (!Object.op_Implicit((Object)(object)val))
			{
				return;
			}
			Transform val2 = val.transform.Find("Global");
			if (!Object.op_Implicit((Object)(object)val2))
			{
				return;
			}
			foreach (Transform item in val2)
			{
				Transform val3 = item;
				if (!((Object)val3).name.Contains(catalog.biomeId))
				{
					continue;
				}
				Transform val4 = (Transform)(Object.op_Implicit((Object)(object)val3.Find("FloorRoot/RootsTerrain/PF_TwistedFanTrees")) ? ((object)val3) : ((object)((IEnumerable<Transform>)((Component)val3).GetComponentsInChildren<Transform>(true)).FirstOrDefault((Func<Transform, bool>)((Transform x) => Object.op_Implicit((Object)(object)x.Find("FloorRoot/RootsTerrain/PF_TwistedFanTrees"))))));
				if (!Object.op_Implicit((Object)(object)val4))
				{
					continue;
				}
				Transform val5 = val4.Find("FloorRoot/RootsTerrain/PF_TwistedFanTrees");
				int num = TreeRoster.Count(from Transform n in (IEnumerable)val5
					select ((Object)n).name);
				Tree[] array = new Tree[num];
				for (int num2 = 0; num2 < array.Length; num2++)
				{
					Transform node = val5.Find("PF_TwistedFan_" + num2.ToString("D3"));
					if (!Object.op_Implicit((Object)(object)node))
					{
						throw new Exception("Authored tree missing: " + num2);
					}
					MeshFilter component = ((Component)node.Find("TwistedTrunk")).GetComponent<MeshFilter>();
					int num3 = num2 % catalog.variants.Length;
					if (!((Object)component.sharedMesh).name.EndsWith("_" + num3))
					{
						throw new Exception("Tree geometry/catalog mismatch.");
					}
					Variant variant = catalog.variants[num3];
					array[num2] = new Tree
					{
						id = num2,
						root = node,
						variant = variant,
						strike = node.TransformPoint(variant.strike),
						foliage = ((Component)node.Find("FoliageCanopy")).GetComponent<Renderer>(),
						segments = variant.segments.Select((Segment s) => new Segment
						{
							a = node.TransformPoint(s.a),
							b = node.TransformPoint(s.b)
						}).ToArray()
					};
				}
				root = val4;
				floor = val4.Find("FloorRoot");
				trees = array;
				RefreshGeometry();
				Log("trees-found", array.Length + " stable authored trees; catalog=" + catalogHash);
				break;
			}
		}

		private void RefreshGeometry()
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: 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_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f8: 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)
			Tree[] array = trees;
			foreach (Tree tree in array)
			{
				if (!Object.op_Implicit((Object)(object)tree.root))
				{
					continue;
				}
				Matrix4x4 localToWorldMatrix = tree.root.localToWorldMatrix;
				if (!(localToWorldMatrix == tree.cachedMatrix))
				{
					tree.cachedMatrix = localToWorldMatrix;
					tree.strike = ((Matrix4x4)(ref localToWorldMatrix)).MultiplyPoint3x4(tree.variant.strike);
					tree.fieldBottom = tree.root.position.y - settings.transferRadius;
					tree.fieldTop = tree.strike.y + 2f;
					for (int j = 0; j < tree.segments.Length; j++)
					{
						tree.segments[j].a = ((Matrix4x4)(ref localToWorldMatrix)).MultiplyPoint3x4(tree.variant.segments[j].a);
						tree.segments[j].b = ((Matrix4x4)(ref localToWorldMatrix)).MultiplyPoint3x4(tree.variant.segments[j].b);
						tree.fieldTop = Mathf.Max(tree.fieldTop, Mathf.Max(tree.segments[j].a.y, tree.segments[j].b.y) + 2f);
					}
				}
			}
		}

		private bool Eligible(Character c)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			int result;
			if (Object.op_Implicit((Object)(object)c))
			{
				Scene scene = ((Component)c).gameObject.scene;
				if (((Scene)(ref scene)).IsValid() && Object.op_Implicit((Object)(object)((MonoBehaviourPun)c).photonView) && ((MonoBehaviourPun)c).photonView.Owner != null && (Object)(object)c.data != (Object)null && !c.data.dead && c.refs != null && Object.op_Implicit((Object)(object)c.refs.ragdoll) && c.refs.ragdoll.partList != null)
				{
					result = ((c.refs.ragdoll.partList.Count > 0) ? 1 : 0);
					goto IL_009c;
				}
			}
			result = 0;
			goto IL_009c;
			IL_009c:
			return (byte)result != 0;
		}

		private List<Person> People()
		{
			return (from c in Resources.FindObjectsOfTypeAll<Character>()
				where Eligible(c) && OnBiome(c)
				select new Person
				{
					c = c,
					actor = ((MonoBehaviourPun)c).photonView.Owner.ActorNumber,
					view = ((MonoBehaviourPun)c).photonView.ViewID
				} into p
				group p by p.actor into g
				select g.First() into p
				orderby p.actor
				select p).ToList();
		}

		private bool Ignore(Collider c)
		{
			return !Object.op_Implicit((Object)(object)c) || c.isTrigger || Object.op_Implicit((Object)(object)((Component)c).GetComponentInParent<Bodypart>()) || Object.op_Implicit((Object)(object)((Component)c).GetComponentInParent<Character>()) || Object.op_Implicit((Object)(object)((Component)c).GetComponentInParent<Item>());
		}

		private bool OnBiome(Character c)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			int num = Physics.RaycastNonAlloc(c.Center + Vector3.up * 0.1f, Vector3.down, hits, 700f, -5, (QueryTriggerInteraction)1);
			float num2 = float.PositiveInfinity;
			Collider val = null;
			for (int i = 0; i < num; i++)
			{
				if (!Ignore(((RaycastHit)(ref hits[i])).collider) && ((RaycastHit)(ref hits[i])).distance < num2)
				{
					num2 = ((RaycastHit)(ref hits[i])).distance;
					val = ((RaycastHit)(ref hits[i])).collider;
				}
			}
			return Object.op_Implicit((Object)(object)val) && ((Component)val).transform.IsChildOf(root);
		}

		private static Vector3 Closest(Tree tree, Vector3 p, out float squared)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: 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_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: 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_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_007c: 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_0086: 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_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			squared = float.PositiveInfinity;
			Vector3 result = tree.root.position;
			Segment[] segments = tree.segments;
			foreach (Segment segment in segments)
			{
				Vector3 val = segment.b - segment.a;
				float num = ((((Vector3)(ref val)).sqrMagnitude > 1E-08f) ? Mathf.Clamp01(Vector3.Dot(p - segment.a, val) / ((Vector3)(ref val)).sqrMagnitude) : 0f);
				Vector3 val2 = segment.a + val * num;
				Vector3 val3 = p - val2;
				float sqrMagnitude = ((Vector3)(ref val3)).sqrMagnitude;
				if (sqrMagnitude < squared)
				{
					squared = sqrMagnitude;
					result = val2;
				}
			}
			return result;
		}

		private int Nearest(Vector3 p, bool charged, out Vector3 contact, out float distance)
		{
			//IL_00bf: 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_00c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			double[] array = new double[trees.Length];
			Vector3[] array2 = (Vector3[])(object)new Vector3[trees.Length];
			for (int i = 0; i < trees.Length; i++)
			{
				Tree tree = trees[i];
				if (!((Component)tree.root).gameObject.activeInHierarchy || (charged && shared.charges[tree.id] <= 1E-06f))
				{
					array[i] = double.PositiveInfinity;
					continue;
				}
				array2[i] = Closest(tree, p, out var squared);
				array[i] = squared;
			}
			int num = StormModel.Nearest(array);
			contact = ((num >= 0) ? array2[num] : Vector3.zero);
			distance = ((num >= 0) ? ((float)Math.Sqrt(array[num])) : float.PositiveInfinity);
			return num;
		}

		private bool InField(Tree tree, Vector3 p)
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			return Object.op_Implicit((Object)(object)tree.root) && ((Component)tree.root).gameObject.activeInHierarchy && TransferField.Contains(p.x, p.y, p.z, tree.root.position.x, tree.root.position.z, tree.fieldBottom, tree.fieldTop, settings.transferRadius);
		}

		private int NearestTransfer(Vector3 p, bool includeReserved, out float distance, out int nearest, out string reason)
		{
			//IL_009c: 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_00a3: 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_00b1: 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_00e5: 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)
			double num = double.PositiveInfinity;
			double num2 = double.PositiveInfinity;
			int num3 = -1;
			nearest = -1;
			reason = "No charged trees";
			Tree[] array = trees;
			foreach (Tree tree in array)
			{
				if (Object.op_Implicit((Object)(object)tree.root) && ((Component)tree.root).gameObject.activeInHierarchy && !((includeReserved ? tree.DisplayCharge(shared) : shared.charges[tree.id]) <= 1E-06f))
				{
					Vector3 position = tree.root.position;
					double num4 = TransferField.HorizontalSquared(p.x, p.z, position.x, position.z);
					if (num4 < num)
					{
						num = num4;
						nearest = tree.id;
					}
					if (InField(tree, p) && num4 < num2)
					{
						num2 = num4;
						num3 = tree.id;
					}
				}
			}
			distance = (double.IsPositiveInfinity(num) ? (-1f) : ((float)Math.Sqrt((num3 >= 0) ? num2 : num)));
			if (num3 >= 0)
			{
				nearest = num3;
				reason = "In range";
			}
			else if (nearest >= 0)
			{
				Tree tree2 = trees[nearest];
				reason = ((distance > settings.transferRadius) ? "Outside radius" : ((p.y < tree2.fieldBottom) ? "Below field" : "Above crown"));
			}
			return num3;
		}

		private void Warn(List<Person> people)
		{
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			if (shared.warningTree < 0 && people.Count != 0)
			{
				Person person = people[random.Next(people.Count)];
				Vector3 contact;
				float distance;
				int num = Nearest(person.c.Center, charged: false, out contact, out distance);
				if (num >= 0)
				{
					shared.warningTree = num;
					shared.warningActor = person.actor;
					shared.warningAt = PhotonNetwork.Time + (double)settings.warningSeconds;
					shared.nextStrikeAt = 0.0;
					Publish();
					Log("warning", "actor=" + person.actor + " nearestTree=" + num + " distance=" + distance.ToString("F2"));
				}
			}
		}

		private void HostTick()
		{
			//IL_0577: Unknown result type (might be due to invalid IL or missing references)
			//IL_057c: Unknown result type (might be due to invalid IL or missing references)
			//IL_05da: Unknown result type (might be due to invalid IL or missing references)
			//IL_05e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_05f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0609: Unknown result type (might be due to invalid IL or missing references)
			//IL_060b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0615: Unknown result type (might be due to invalid IL or missing references)
			//IL_061a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0621: Unknown result type (might be due to invalid IL or missing references)
			//IL_0626: Unknown result type (might be due to invalid IL or missing references)
			//IL_0628: Unknown result type (might be due to invalid IL or missing references)
			//IL_062a: Unknown result type (might be due to invalid IL or missing references)
			//IL_062c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0631: Unknown result type (might be due to invalid IL or missing references)
			//IL_06b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_06c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_06ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_06db: Unknown result type (might be due to invalid IL or missing references)
			//IL_06e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_06f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0647: Unknown result type (might be due to invalid IL or missing references)
			//IL_064b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0655: Unknown result type (might be due to invalid IL or missing references)
			//IL_065a: Unknown result type (might be due to invalid IL or missing references)
			//IL_065f: Unknown result type (might be due to invalid IL or missing references)
			double time = PhotonNetwork.Time;
			double delta = Math.Min(0.3, Math.Max(0.0, time - lastHostStep));
			lastHostStep = time;
			List<Person> list = People();
			Grant[] array = shared.grants.ToArray();
			foreach (Grant g in array)
			{
				Player val = ((IEnumerable<Player>)PhotonNetwork.PlayerList).FirstOrDefault((Func<Player, bool>)((Player p) => p.ActorNumber == g.actor));
				int seq;
				float used;
				double value;
				if (val == null || val.IsInactive)
				{
					StormModel.Abandon(shared, g.actor);
				}
				else if (DischargeWire.ReadAck(val.CustomProperties[(object)"PF_LAck"], shared.epoch, out seq, out used) && seq == g.seq && StormModel.Resolve(shared, g.actor, seq, used, settings.treeCapacity))
				{
					acknowledgedOffers++;
					nextOffer.Remove(seq);
					Log("grant-acknowledged", "epoch=" + shared.epoch + " seq=" + seq + " actor=" + g.actor + " used=" + used.ToString("F4"));
				}
				else if (!nextOffer.TryGetValue(g.seq, out value) || time >= value)
				{
					SendOffer(g, retry: true);
				}
			}
			if (list.Count == 0)
			{
				shared.nextStrikeAt = 0.0;
				shared.warningTree = -1;
			}
			else
			{
				if (shared.warningTree >= 0 && time >= shared.warningAt)
				{
					if (list.Any((Person p) => p.actor == shared.warningActor))
					{
						int warningTree = shared.warningTree;
						StormModel.Strike(shared, warningTree, settings.chargePerStrike, settings.treeCapacity);
						ItemTreeAPI.Notify(warningTree);
						shared.serial++;
						shared.lastTree = warningTree;
						shared.lastActor = shared.warningActor;
						shared.lastStrikeAt = time;
						Log("strike", "serial=" + shared.serial + " tree=" + warningTree + " actor=" + shared.lastActor);
					}
					shared.warningTree = -1;
					shared.nextStrikeAt = (shared.automatic ? StormModel.Next(time, random.NextDouble(), settings.minInterval, settings.maxInterval) : 0.0);
				}
				if (shared.automatic && shared.warningTree < 0)
				{
					if (shared.nextStrikeAt <= 0.0)
					{
						shared.nextStrikeAt = time + (double)settings.firstStrikeDelay;
					}
					else if (time >= shared.nextStrikeAt)
					{
						Warn(list);
					}
				}
			}
			StormModel.PruneBursts(shared, time);
			Tree[] array2 = trees;
			foreach (Tree tree in array2)
			{
				if (!Object.op_Implicit((Object)(object)tree.root) || !((Component)tree.root).gameObject.activeInHierarchy)
				{
					continue;
				}
				Person[] array3 = list.Where((Person p) => InField(tree, p.c.Center)).ToArray();
				shared.transferOccupied[tree.id] = array3.Length != 0 && tree.DisplayCharge(shared) > 1E-06f;
				if (!StormModel.AdvanceTransfer(shared, tree.id, delta, array3.Length != 0, settings.transferInterval))
				{
					continue;
				}
				Person[] array4 = array3.Where((Person p) => ElectricalReady(p.c) && !shared.grants.Any((Grant grant2) => grant2.actor == p.actor)).ToArray();
				int num2 = StormModel.RandomTarget(array4.Length, random.NextDouble());
				if (num2 < 0)
				{
					continue;
				}
				Person person = array4[num2];
				Vector3 center = person.c.Center;
				Grant grant = StormModel.FireTransfer(shared, tree.id, person.actor, person.view, settings.transferAmount, time, settings.grantLifetime, settings.transferInterval);
				if (grant != null)
				{
					grant.targetX = center.x;
					grant.targetY = center.y;
					grant.targetZ = center.z;
					float squared;
					Vector3 val2 = Closest(tree, center + Vector3.up * 3f, out squared);
					Vector3 val3 = center - val2;
					if (((Vector3)(ref val3)).sqrMagnitude > 0.0001f)
					{
						val2 += ((Vector3)(ref val3)).normalized * 0.15f;
					}
					TransferStrike transferStrike = new TransferStrike
					{
						seq = grant.seq,
						tree = tree.id,
						actor = person.actor,
						view = person.view,
						amount = grant.amount,
						at = time,
						sx = val2.x,
						sy = val2.y,
						sz = val2.z,
						tx = center.x,
						ty = center.y,
						tz = center.z
					};
					TransferStrike[] bursts = shared.bursts.Concat(new TransferStrike[1] { transferStrike }).ToArray();
					shared.bursts = bursts;
					StormModel.PruneBursts(shared, time);
					SendOffer(grant, retry: false);
					Log("tree-discharge", "seq=" + grant.seq + " tree=" + tree.id + " actor=" + person.actor + " offeredPoints=" + (grant.amount * 100f).ToString("F2") + " next=" + settings.transferInterval);
				}
			}
			Publish();
		}

		private bool ElectricalReady(Character c)
		{
			ElectricalTrial instance = ElectricalTrial.Instance;
			if (!Object.op_Implicit((Object)(object)instance) || electricalReady == null || electricalFailed == null || electricalCompatible == null || !(bool)electricalReady.GetValue(instance) || (bool)electricalFailed.GetValue(instance) || !(bool)electricalCompatible.GetValue(instance))
			{
				return false;
			}
			string protocol = PhotonNetwork.LocalPlayer.CustomProperties[(object)"PF_ETrial"] as string;
			if (string.IsNullOrEmpty(protocol) || PhotonNetwork.PlayerList.Where((Player p) => !p.IsInactive).Any((Player p) => !(p.CustomProperties[(object)"PF_ETrial"] is string text) || text != protocol))
			{
				return false;
			}
			Player owner = ((MonoBehaviourPun)c).photonView.Owner;
			return !owner.IsInactive && owner.CustomProperties[(object)"PF_EView"] is int num && num == ((MonoBehaviourPun)c).photonView.ViewID;
		}

		private void ProcessOffers(Character local)
		{
			//IL_0198: Unknown result type (might be due to invalid IL or missing references)
			if (trees == null || offers.Count == 0)
			{
				return;
			}
			double time = PhotonNetwork.Time;
			string text = (SharedWorld.Online ? SharedWorld.Epoch : shared?.epoch);
			int actorNumber = PhotonNetwork.LocalPlayer.ActorNumber;
			DischargeOffer[] array = offers.Values.ToArray();
			foreach (DischargeOffer dischargeOffer in array)
			{
				Grant grant = dischargeOffer.grant;
				if (dischargeOffer.epoch != text)
				{
					offers.Remove(grant.seq);
					continue;
				}
				if (grant.actor == actorNumber)
				{
					if (DischargeWire.ReadAck(PhotonNetwork.LocalPlayer.CustomProperties[(object)"PF_LAck"], text, out var seq, out var used) && seq == grant.seq)
					{
						receiver.Remember(text, grant.seq, used);
					}
					bool flag = Object.op_Implicit((Object)(object)local) && Object.op_Implicit((Object)(object)((MonoBehaviourPun)local).photonView) && (Object)(object)local.data != (Object)null;
					int num = (flag ? ((MonoBehaviourPun)local).photonView.ViewID : 0);
					bool alive = flag && !local.data.dead;
					bool flag2 = flag && ActiveRoot && ElectricalReady(local);
					bool firedInField = InField(trees[grant.tree], new Vector3(grant.targetX, grant.targetY, grant.targetZ));
					float num2 = (Object.op_Implicit((Object)(object)ElectricalTrial.Instance) ? ElectricalTrial.Instance.Model.Charge : 0f);
					float used2;
					string reason;
					DischargeResult dischargeResult = receiver.Apply(dischargeOffer, text, actorNumber, num, time, flag2, alive, firedInField, ElectricalTrial.Instance?.Model, out used2, out reason);
					if (dischargeResult == DischargeResult.Waiting && (!waitingOffers.TryGetValue(grant.seq, out var value) || value != reason))
					{
						waitingOffers[grant.seq] = reason;
						Log("grant-waiting", "epoch=" + text + " seq=" + grant.seq + " actor=" + actorNumber + " reason=" + reason);
					}
					if (dischargeResult == DischargeResult.Handled)
					{
						waitingOffers.Remove(grant.seq);
						if (reason != "duplicate")
						{
							if (used2 > 0f)
							{
								appliedOffers++;
								local.ClampStamina();
								ElectricalTrial.RefreshBar();
							}
							else
							{
								declinedOffers++;
							}
							Log("grant-result", "epoch=" + text + " seq=" + grant.seq + " actor=" + actorNumber + " view=" + num + " reason=" + reason + " before=" + num2.ToString("F4") + " used=" + used2.ToString("F4") + " after=" + (Object.op_Implicit((Object)(object)ElectricalTrial.Instance) ? ElectricalTrial.Instance.Model.Charge : 0f).ToString("F4"));
						}
						SendAck(text, grant.seq, used2);
						if (flag2 && num == grant.view && time <= grant.expires)
						{
							ShowTransfer(dischargeOffer.hit);
						}
					}
				}
				else if (time - dischargeOffer.hit.at >= -0.1 && time - dischargeOffer.hit.at < 1.0)
				{
					ShowTransfer(dischargeOffer.hit);
				}
				if (time > grant.expires + 6.0)
				{
					offers.Remove(grant.seq);
				}
			}
		}

		private void SendAck(string epoch, int seq, float used)
		{
			//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_0045: Expected O, but got Unknown
			//IL_004d: Expected O, but got Unknown
			object current = PhotonNetwork.LocalPlayer.CustomProperties[(object)"PF_LAck"];
			if (DischargeWire.ShouldWriteAck(current, epoch, seq, used))
			{
				Player localPlayer = PhotonNetwork.LocalPlayer;
				Hashtable val = new Hashtable();
				((Dictionary<object, object>)val).Add((object)"PF_LAck", (object)DischargeWire.Ack(epoch, seq, used));
				localPlayer.SetCustomProperties(val, (Hashtable)null, (WebFlags)null);
			}
		}

		private void SendOffer(Grant g, bool retry)
		{
			TransferStrike transferStrike = shared.bursts.FirstOrDefault((TransferStrike b) => b.seq == g.seq);
			if (transferStrike != null)
			{
				if (SharedWorld.Online)
				{
					SharedWorld.Emit("tree-discharge", DischargeWire.Pack(g, transferStrike), true);
				}
				else
				{
					QueueOffer(new DischargeOffer
					{
						epoch = shared.epoch,
						grant = g,
						hit = transferStrike
					}, "solo");
				}
				nextOffer[g.seq] = PhotonNetwork.Time + 1.0;
				if (retry)
				{
					retriedOffers++;
					Log("offer-retry", "epoch=" + shared.epoch + " seq=" + g.seq + " actor=" + g.actor);
				}
			}
		}

		private void InspectTransfer()
		{
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			transferTree = -1;
			transferDistance = -1f;
			transferStatus = "Waiting for forest";
			Character localCharacter = Character.localCharacter;
			if (ActiveRoot && shared != null && Eligible(localCharacter))
			{
				int num = NearestTransfer(localCharacter.Center, includeReserved: true, out transferDistance, out transferTree, out transferStatus);
				if (!compatible)
				{
					transferStatus = "Waiting for matching helpers";
				}
				else if (!localInside)
				{
					transferStatus = "Outside custom biome";
				}
				else if (!ElectricalReady(localCharacter))
				{
					transferStatus = "Waiting for electrical helper";
				}
				else if (ElectricalTrial.ChargeFor(localCharacter) >= 0.999999f)
				{
					transferStatus = "Player charge full";
				}
				else if (num >= 0)
				{
					transferStatus = (shared.grants.Any((Grant g) => g.actor == PhotonNetwork.LocalPlayer.ActorNumber) ? "Discharge arriving" : ("In range; next zap in " + shared.transferRemaining[num].ToString("F1") + "s"));
				}
				if (num < 0 && transferTree >= 0 && shared.transferRemaining[transferTree] < settings.transferInterval)
				{
					transferStatus = transferStatus + (shared.transferOccupied[transferTree] ? "; tree timer running at " : "; timer paused at ") + shared.transferRemaining[transferTree].ToString("F1") + "s";
				}
			}
			string text = transferTree + ":" + (transferStatus.StartsWith("In range;") ? "In range" : transferStatus);
			if (InRun() && text != lastTransferLog)
			{
				lastTransferLog = text;
				Log("transfer-area", "tree=" + transferTree + " state=" + transferStatus + " horizontalDistance=" + transferDistance.ToString("F2") + " radius=" + settings.transferRadius);
			}
		}

		private void Report()
		{
			//IL_04c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_04bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_04cd: Unknown result type (might be due to invalid IL or missing references)
			if (RuntimeDiagnostics.PeriodicSnapshots && !(Time.unscaledTime < nextReport))
			{
				nextReport = Time.unscaledTime + 1f;
				if (ready)
				{
					InspectTransfer();
				}
				Status status = new Status
				{
					receivedOffers = receivedOffers,
					appliedOffers = appliedOffers,
					declinedOffers = declinedOffers,
					retriedOffers = retriedOffers,
					acknowledgedOffers = acknowledgedOffers,
					receivedSnapshots = receivedSnapshots,
					acceptedSnapshots = acceptedSnapshots,
					rejectedSnapshots = rejectedSnapshots,
					shownTransferCount = shownTransferCount,
					snapshotRejection = snapshotRejection,
					utc = DateTime.UtcNow.ToString("O"),
					version = "1.0.0",
					message = message,
					error = error,
					ready = ready,
					compatible = compatible,
					master = master,
					inRun = InRun(),
					inside = localInside,
					visualsReady = (visuals != null && visuals.Ready),
					trees = ((trees != null) ? trees.Length : 0),
					epoch = ((shared != null) ? shared.epoch : null),
					automatic = (shared != null && shared.automatic),
					chargedTrees = ((shared != null) ? shared.charges.Count((float q) => q > 1E-06f) : 0),
					warningTree = ((shared != null) ? shared.warningTree : (-1)),
					lastTree = ((shared != null) ? shared.lastTree : (-1)),
					lastActor = ((shared != null) ? shared.lastActor : 0),
					strikes = ((shared != null) ? shared.serial : 0),
					pendingGrants = ((shared != null) ? shared.grants.Length : 0),
					totalReservoir = ((shared != null) ? shared.charges.Sum() : 0f),
					reservedCharge = ((shared != null) ? shared.grants.Sum((Grant g) => g.amount) : 0f),
					localCharge = (Object.op_Implicit((Object)(object)Character.localCharacter) ? ElectricalTrial.ChargeFor(Character.localCharacter) : 0f),
					nextStrikeAt = ((shared != null) ? shared.nextStrikeAt : 0.0),
					now = (PhotonNetwork.InRoom ? PhotonNetwork.Time : 0.0),
					transferStatus = transferStatus,
					transferDistance = transferDistance,
					transferTree = transferTree,
					transferRadius = ((settings != null) ? settings.transferRadius : 0f),
					transferAmountPoints = ((settings != null) ? (settings.transferAmount * 100f) : 0f),
					transferInterval = ((settings != null) ? settings.transferInterval : 0f),
					transferRemaining = ((trees != null && shared != null && transferTree >= 0) ? shared.transferRemaining[transferTree] : 0f),
					treeChargePoints = ((trees != null && shared != null && transferTree >= 0) ? (trees[transferTree].DisplayCharge(shared) * 100f) : 0f),
					fieldBottom = ((trees != null && transferTree >= 0) ? trees[transferTree].fieldBottom : 0f),
					fieldTop = ((trees != null && transferTree >= 0) ? trees[transferTree].fieldTop : 0f),
					localPosition = (Eligible(Character.localCharacter) ? Character.localCharacter.Center : Vector3.zero)
				};
				string contents = JsonUtility.ToJson((object)status, true);
				File.WriteAllText(Path.Combine(folder, "lightning-state.json"), contents);
				if (ActiveRoot)
				{
					File.WriteAllText(Path.Combine(folder, "lightning-last-active.json"), contents);
				}
			}
		}

		private void Log(string kind, string detail)
		{
			((BaseUnityPlugin)this).Logger.LogInfo((object)(kind + ": " + detail));
			if (RuntimeDiagnostics.PeriodicSnapshots)
			{
				File.AppendAllText(Path.Combine(folder, "events.tsv"), DateTime.UtcNow.ToString("O") + "\t" + kind + "\t" + detail + "\n");
			}
		}

		private void Fail(Exception e)
		{
			ready = false;
			error = e.ToString();
			message = "Lightning trial stopped; see diagnostics";
			((BaseUnityPlugin)this).Logger.LogError((object)error);
			if (visuals != null)
			{
				visuals.Dispose();
				visuals = null;
			}
			nextReport = 0f;
			try
			{
				Report();
			}
			catch
			{
			}
		}

		private void OnDestroy()
		{
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Expected O, but got Unknown
			//IL_0064: Expected O, but got Unknown
			ItemTreeAPI.ChargeAt = null;
			SharedWorld.Message -= OnShared;
			if (visuals != null)
			{
				visuals.Dispose();
			}
			ready = false;
			try
			{
				if (PhotonNetwork.LocalPlayer != null)
				{
					Player localPlayer = PhotonNetwork.LocalPlayer;
					Hashtable val = new Hashtable();
					((Dictionary<object, object>)val).Add((object)"PF_LProtocol", (object)null);
					localPlayer.SetCustomProperties(val, (Hashtable)null, (WebFlags)null);
				}
			}
			catch
			{
			}
		}
	}
	public sealed class StormVisuals : IDisposable
	{
		private sealed class Transient
		{
			public GameObject node;

			public float end;

			public float start;

			public ElectricRibbon[] lines;

			public Light light;

			public bool transfer;

			public Transform target;

			public Transform sourceTree;

			public Vector3 sourceLocal;

			public Vector3 targetLocal;

			public Vector3 fallbackTarget;

			public int seed;

			public Color[] baseStarts;

			public Color[] baseEnds;
		}

		private sealed class Charged : IDisposable
		{
			public readonly StormTrial.Tree tree;

			public readonly GameObject node;

			public readonly ElectricRibbon[] arcs;

			public readonly ParticleSystem sparks;

			public readonly AudioSource audio;

			private readonly MaterialPropertyBlock original = new MaterialPropertyBlock();

			private readonly MaterialPropertyBlock tint = new MaterialPropertyBlock();

			private readonly Color originalColor;

			private float tintAmount = -1f;

			public float nextSpark;

			public float sparkUntil;

			public float nextCrackle;

			public readonly float chargeVisibleAfter;

			public Charged(StormTrial.Tree t, Transform parent, Material material)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_000b: Expected O, but got Unknown
				//IL_000c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0016: Expected O, but got Unknown
				//IL_0057: Unknown result type (might be due to invalid IL or missing references)
				//IL_0061: Expected O, but got Unknown
				//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
				//IL_00f1: Expected O, but got Unknown
				//IL_011b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0120: Unknown result type (might be due to invalid IL or missing references)
				//IL_0143: Unknown result type (might be due to invalid IL or missing references)
				//IL_0155: Unknown result type (might be due to invalid IL or missing references)
				//IL_0167: Unknown result type (might be due to invalid IL or missing references)
				//IL_0185: Unknown result type (might be due to invalid IL or missing references)
				//IL_018a: 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_01af: Unknown result type (might be due to invalid IL or missing references)
				//IL_01b4: Unknown result type (might be due to invalid IL or missing references)
				//IL_021b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0222: Expected O, but got Unknown
				//IL_02d9: Unknown result type (might be due to invalid IL or missing references)
				//IL_02de: Unknown result type (might be due to invalid IL or missing references)
				chargeVisibleAfter = Time.time + 0.12f;
				tree = t;
				node = new GameObject("PF_ChargedTree_" + t.id);
				node.transform.SetParent(parent, false);
				arcs = new ElectricRibbon[10];
				for (int i = 0; i < arcs.Length; i++)
				{
					arcs[i] = Line(node.transform, material, (i < 8) ? 0.095f : 0.13f, ((i < 8) ? "BarkArc_" : "CrownArc_") + i);
				}
				GameObject val = new GameObject("CoronaSparks");
				val.transform.SetParent(node.transform, false);
				sparks = val.AddComponent<ParticleSystem>();
				MainModule main = sparks.main;
				((MainModule)(ref main)).playOnAwake = false;
				((MainModule)(ref main)).loop = true;
				((MainModule)(ref main)).simulationSpace = (ParticleSystemSimulationSpace)1;
				((MainModule)(ref main)).startLifetime = MinMaxCurve.op_Implicit(0.25f);
				((MainModule)(ref main)).startSize = MinMaxCurve.op_Implicit(0.08f);
				((MainModule)(ref main)).startSpeed = MinMaxCurve.op_Implicit(0f);
				((MainModule)(ref main)).maxParticles = 192;
				EmissionModule emission = sparks.emission;
				((EmissionModule)(ref emission)).enabled = false;
				ShapeModule shape = sparks.shape;
				((ShapeModule)(ref shape)).enabled = false;
				CollisionModule collision = sparks.collision;
				((CollisionModule)(ref collision)).enabled = false;
				ParticleSystemRenderer component = ((Component)sparks).GetComponent<ParticleSystemRenderer>();
				((Renderer)component).sharedMaterial = material;
				component.renderMode = (ParticleSystemRenderMode)1;
				component.lengthScale = 1.1f;
				component.velocityScale = 0.04f;
				((Renderer)component).shadowCastingMode = (ShadowCastingMode)0;
				((Renderer)component).receiveShadows = false;
				sparks.Play();
				GameObject val2 = new GameObject("TreeCrackleAudio");
				val2.transform.SetParent(node.transform, false);
				audio = val2.AddComponent<AudioSource>();
				audio.playOnAwake = false;
				audio.spatialBlend = 1f;
				audio.rolloffMode = (AudioRolloffMode)0;
				audio.minDistance = 2f;
				audio.maxDistance = 16f;
				tree.foliage.GetPropertyBlock(original);
				tree.foliage.GetPropertyBlock(tint);
				originalColor = tree.foliage.sharedMaterial.GetColor("_BaseColor");
			}

			public void Tint(float amount)
			{
				//IL_002e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0047: Unknown result type (might be due to invalid IL or missing references)
				//IL_004d: Unknown result type (might be due to invalid IL or missing references)
				if (!(Mathf.Abs(tintAmount - amount) < 0.01f))
				{
					tintAmount = amount;
					tint.SetColor("_BaseColor", Color.Lerp(originalColor, new Color(0.4f, 0.32f, 0.62f, 1f), amount));
					if (Object.op_Implicit((Object)(object)tree.foliage))
					{
						tree.foliage.SetPropertyBlock(tint);
					}
				}
			}

			public void Dispose()
			{
				if (Object.op_Implicit((Object)(object)tree.foliage))
				{
					tree.foliage.SetPropertyBlock(original);
				}
				if (Object.op_Implicit((Object)(object)node))
				{
					Object.Destroy((Object)(object)node);
				}
			}
		}

		private readonly Transform parent;

		private readonly StormTrial.Settings settings;

		private readonly Dictionary<int, Charged> charged = new Dictionary<int, Charged>();

		private readonly List<Transient> transient = new List<Transient>();

		private readonly Random random = new Random();

		private Material material;

		private AudioClip thunder;

		private AudioClip crackle;

		private float nextFind;

		private static readonly Plane[] viewPlanes = (Plane[])(object)new Plane[6];

		private static int viewFrame = -1;

		private static bool hasView;

		public bool Ready => Object.op_Implicit((Object)(object)material);

		public StormVisuals(Transform root, StormTrial.Settings settings)
		{
			parent = root;
			this.settings = settings;
			Ensure();
		}

		private bool Ensure()
		{
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: Expected O, but got Unknown
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			if (Object.op_Implicit((Object)(object)material))
			{
				return true;
			}
			if (Time.unscaledTime < nextFind)
			{
				return false;
			}
			nextFind = Time.unscaledTime + 1f;
			Shader val = Shader.Find("FirstRidge/CampfireParticle") ?? ((IEnumerable<Shader>)Resources.FindObjectsOfTypeAll<Shader>()).FirstOrDefault((Func<Shader, bool>)((Shader s) => Object.op_Implicit((Object)(object)s) && ((Object)s).name == "FirstRidge/CampfireParticle"));
			if (!Object.op_Implicit((Object)(object)val) || !val.isSupported)
			{
				return false;
			}
			material = new Material(val)
			{
				name = "PF_Lightning_Unlit_Runtime",
				hideFlags = (HideFlags)61
			};
			material.SetColor("_BaseColor", Color.white);
			material.renderQueue = 3100;
			float[] array = StormPresentation.Thunder(22050);
			thunder = AudioClip.Create("PF_Thunder_Heavy", array.Length, 1, 22050, false);
			thunder.SetData(array, 0);
			crackle = NoiseClip("PF_Crackle", 0.15f, 197, low: false);
			return true;
		}

		private static AudioClip NoiseClip(string name, float duration, int seed, bool low)
		{
			int num = 22050;
			int num2 = (int)(duration * (float)num);
			float[] array = new float[num2];
			Random random = new Random(seed);
			float num3 = 0f;
			float num4 = 0f;
			for (int i = 0; i < num2; i++)
			{
				float num5 = (float)i / (float)num;
				float num6 = (float)random.NextDouble() * 2f - 1f;
				num3 = num3 * 0.96f + num6 * 0.04f;
				float num7 = (low ? (Mathf.Exp((0f - num5) * 3f) * Mathf.Min(1f, num5 * 120f)) : (Mathf.Exp((0f - num5) * 35f) + 0.4f * Mathf.Exp((0f - Mathf.Abs(num5 - 0.06f)) * 180f)));
				array[i] = Mathf.Clamp((low ? (num3 * 2.8f + num6 * 0.15f * Mathf.Exp((0f - num5) * 35f)) : ((num6 - num4) * 0.22f)) * num7, -0.7f, 0.7f);
				num4 = num6;
			}
			AudioClip val = AudioClip.Create(name, num2, 1, num, false);
			val.SetData(array, 0);
			return val;
		}

		private static ElectricRibbon Line(Transform parent, Material material, float width, string name)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Expected O, but got Unknown
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: 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)
			GameObject val = new GameObject(name);
			val.transform.SetParent(parent, false);
			ElectricRibbon electricRibbon = val.AddComponent<ElectricRibbon>();
			electricRibbon.sharedMaterial = material;
			electricRibbon.widthMultiplier = width;
			electricRibbon.sortingOrder = ((name == "WhiteCore") ? 1 : 0);
			electricRibbon.startColor = new Color(0.65f, 0.45f, 1f, 1f);
			electricRibbon.endColor = new Color(0.88f, 0.9f, 1f, 1f);
			return electricRibbon;
		}

		private Charged Get(StormTrial.Tree tree)
		{
			if (!charged.TryGetValue(tree.id, out var value))
			{
				value = new Charged(tree, parent, material);
				charged.Add(tree.id, value);
			}
			return value;
		}

		private float R(float a, float b)
		{
			return a + (b - a) * (float)random.NextDouble();
		}

		private Vector3 Rand()
		{
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			return new Vector3(R(-1f, 1f), R(-1f, 1f), R(-1f, 1f));
		}

		public void Strike(StormTrial.Tree tree, int serial)
		{
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: 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)
			//IL_0077: 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_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0118: Unknown result type (might be due to invalid IL or missing references)
			//IL_011f: Expected O, but got Unknown
			//IL_0183: Unknown result type (might be due to invalid IL or missing references)
			//IL_0188: Unknown result type (might be due to invalid IL or missing references)
			//IL_0189: Unknown result type (might be due to invalid IL or missing references)
			//IL_018b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0190: Unknown result type (might be due to invalid IL or missing references)
			//IL_0192: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_021c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0221: Unknown result type (might be due to invalid IL or missing references)
			//IL_0223: Unknown result type (might be due to invalid IL or missing references)
			//IL_0267: Unknown result type (might be due to invalid IL or missing references)
			//IL_026c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0271: Unknown result type (might be due to invalid IL or missing references)
			//IL_0417: Unknown result type (might be due to invalid IL or missing references)
			//IL_041e: Expected O, but got Unknown
			//IL_0443: Unknown result type (might be due to invalid IL or missing references)
			//IL_0396: Unknown result type (might be due to invalid IL or missing references)
			//IL_039d: Expected O, but got Unknown
			//IL_03b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_03e3: 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_0286: Unknown result type (might be due to invalid IL or missing references)
			//IL_0291: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0343: Unknown result type (might be due to invalid IL or missing references)
			//IL_0348: Unknown result type (might be due to invalid IL or missing references)
			//IL_0349: Unknown result type (might be due to invalid IL or missing references)
			//IL_034b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0350: Unknown result type (might be due to invalid IL or missing references)
			//IL_0352: Unknown result type (might be due to invalid IL or missing references)
			//IL_0554: Unknown result type (might be due to invalid IL or missing references)
			//IL_0555: Unknown result type (might be due to invalid IL or missing references)
			//IL_0575: Unknown result type (might be due to invalid IL or missing references)
			if (!Ensure())
			{
				return;
			}
			Random random = new Random(serial * 104729 + tree.id * 7919);
			Vector3 strike = tree.strike;
			Vector3[] array = (Vector3[])(object)new Vector3[23];
			Vector3 val = strike + new Vector3((float)(random.NextDouble() - 0.5) * 24f, 150f, (float)(random.NextDouble() - 0.5) * 18f);
			for (int i = 0; i < array.Length; i++)
			{
				float num = (float)i / (float)(array.Length - 1);
				float num2 = Mathf.Sin(num * MathF.PI) * 6f;
				array[i] = Vector3.Lerp(val, strike, num) + new Vector3(((float)random.NextDouble() * 2f - 1f) * num2, 0f, ((float)random.NextDouble() * 2f - 1f) * num2);
			}
			GameObject val2 = new GameObject("PF_LightningStrike_" + serial);
			val2.transform.SetParent(parent, false);
			List<ElectricRibbon> list = new List<ElectricRibbon>();
			ElectricRibbon electricRibbon = Line(val2.transform, material, 1.5f, "VioletBolt");
			electricRibbon.positionCount = array.Length;
			electricRibbon.SetPositions(array);
			electricRibbon.startColor = (electricRibbon.endColor = new Color(0.58f, 0.38f, 1f, 0.85f));
			list.Add(electricRibbon);
			ElectricRibbon electricRibbon2 = Line(val2.transform, material, 0.4f, "WhiteCore");
			electricRibbon2.positionCount = array.Length;
			electricRibbon2.SetPositions(array);
			electricRibbon2.startColor = (electricRibbon2.endColor = new Color(0.92f, 0.96f, 1f, 1f));
			list.Add(electricRibbon2);
			for (int j = 0; j < 7; j++)
			{
				int num3 = 3 + j * 2;
				Vector3 val3 = array[num3];
				Vector3 val4 = val3 + new Vector3((float)(random.NextDouble() - 0.5) * 38f, 0f - (10f + 18f * (float)random.NextDouble()), (float)(random.NextDouble() - 0.5) * 38f);
				Vector3[] array2 = (Vector3[])(object)new Vector3[7];
				for (int k = 0; k < array2.Length; k++)
				{
					array2[k] = Vector3.Lerp(val3, val4, (float)k / 6f) + new Vector3((float)(random.NextDouble() - 0.5) * 2f, 0f, (float)(random.NextDouble() - 0.5) * 2f);
				}
				ElectricRibbon electricRibbon3 = Line(val2.transform, material, 0.18f, "Fork_" + j);
				electricRibbon3.positionCount = array2.Length;
				electricRibbon3.SetPositions(array2);
				electricRibbon3.startColor = (electricRibbon3.endColor = new Color(0.76f, 0.72f, 1f, 0.85f));
				list.Add(electricRibbon3);
			}
			Light val5 = null;
			if (!settings.reducedFlashes)
			{
				GameObject val6 = new GameObject("CrownImpactLight");
				val6.transform.SetParent(val2.transform, false);
				val6.transform.position = strike;
				val5 = val6.AddComponent<Light>();
				val5.type = (LightType)2;
				val5.color = new Color(0.65f, 0.55f, 1f);
				val5.intensity = 4.15f;
				val5.range = 28f;
				val5.shadows = (LightShadows)0;
			}
			GameObject val7 = new GameObject("ThunderAudio");
			val7.transform.SetParent(val2.transform, false);
			AudioSource val8 = val7.AddComponent<AudioSource>();
			((Component)val8).transform.position = strike;
			val8.playOnAwake = false;
			val8.spatialBlend = 1f;
			val8.minDistance = 10f;
			val8.maxDistance = 150f;
			val8.rolloffMode = (AudioRolloffMode)0;
			val8.PlayOneShot(thunder, 0.85f);
			transient.Add(new Transient
			{
				node = val2,
				start = Time.time,
				end = Time.time + 3.2f + 0.15f,
				lines = list.ToArray(),
				light = val5,
				baseStarts = list.Select((ElectricRibbon l) => l.startColor).ToArray(),
				baseEnds = list.Select((ElectricRibbon l) => l.endColor).ToArray()
			});
			Charged charged = Get(tree);
			Burst(charged, strike, Vector3.up, 64, 0.26f, new Color(0.85f, 0.78f, 1f, 1f), 0.7f, 2.5f, 2f);
			charged.sparkUntil = Time.time + 0.3f;
			charged.nextSpark = 0f;
		}

		public bool TransferStrike(StormTrial.Tree tree, TransferStrike hit, Character target)
		{
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Expected O, but got Unknown
			//IL_00aa: 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_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0100: Unknown result type (might be due to invalid IL or missing references)
			//IL_0102: Unknown result type (might be due to invalid IL or missing references)
			//IL_010c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0113: Expected O, but got Unknown
			//IL_012e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0186: Unknown result type (might be due to invalid IL or missing references)
			//IL_018d: Expected O, but got Unknown
			//IL_01ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01df: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_0203: Unknown result type (might be due to invalid IL or missing references)
			//IL_024b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0253: Unknown result type (might be due to invalid IL or missing references)
			//IL_0255: Unknown result type (might be due to invalid IL or missing references)
			//IL_025f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0264: Unknown result type (might be due to invalid IL or missing references)
			//IL_0272: Unknown result type (might be due to invalid IL or missing references)
			//IL_0287: Unknown result type (might be due to invalid IL or missing references)
			//IL_0373: Unknown result type (might be due to invalid IL or missing references)
			//IL_0374: Unknown result type (might be due to invalid IL or missing references)
			//IL_0379: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_02de: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0398: 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_03ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_03cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_03d0: Unknown result type (might be due to invalid IL or missing references)
			if (!Ensure())
			{
				return false;
			}
			Vector3 val = default(Vector3);
			((Vector3)(ref val))..ctor(hit.sx, hit.sy, hit.sz);
			Vector3 val2 = default(Vector3);
			((Vector3)(ref val2))..ctor(hit.tx, hit.ty, hit.tz);
			GameObject val3 = new GameObject("PF_TreeToPlayerZap_" + hit.seq);
			val3.transform.SetParent(parent, false);
			ElectricRibbon electricRibbon = Line(val3.transform, material, 0.62f, "VioletTransferBolt");
			electricRibbon.startColor = (electricRibbon.endColor = new Color(0.64f, 0.37f, 1f, 0.85f));
			ElectricRibbon electricRibbon2 = Line(val3.transform, material, 0.18f, "WhiteCore");
			electricRibbon2.startColor = (electricRibbon2.endColor = new Color(0.95f, 0.98f, 1f, 1f));
			GameObject val4 = new GameObject("DischargeSnap");
			val4.transform.SetParent(val3.transform, false);
			val4.transform.position = val2;
			AudioSource val5 = val4.AddComponent<AudioSource>();
			val5.playOnAwake = false;
			val5.spatialBlend = 1f;
			val5.minDistance = 3f;
			val5.maxDistance = 28f;
			val5.PlayOneShot(crackle, 0.65f);
			GameObject val6 = new GameObject("PlayerHitSparks");
			val6.transform.SetParent(val3.transform, false);
			ParticleSystem val7 = val6.AddComponent<ParticleSystem>();
			MainModule main = val7.main;
			((MainModule)(ref main)).playOnAwake = false;
			((MainModule)(ref main)).loop = false;
			((MainModule)(ref main)).simulationSpace = (ParticleSystemSimulationSpace)1;
			((MainModule)(ref main)).maxParticles = 32;
			((MainModule)(ref main)).startSpeed = MinMaxCurve.op_Implicit(0f);
			EmissionModule emission = val7.emission;
			((EmissionModule)(ref emission)).enabled = false;
			ShapeModule shape = val7.shape;
			((ShapeModule)(ref shape)).enabled = false;
			ParticleSystemRenderer component = ((Component)val7).GetComponent<ParticleSystemRenderer>();
			((Renderer)component).sharedMaterial = material;
			((Renderer)component).shadowCastingMode = (ShadowCastingMode)0;
			((Renderer)component).receiveShadows = false;
			val7.Play();
			for (int i = 0; i < 22; i++)
			{
				EmitParams val8 = default(EmitParams);
				((EmitParams)(ref val8)).position = val2 + Rand() * 0.25f;
				((EmitParams)(ref val8)).velocity = Rand() * R(1f, 4f);
				((EmitParams)(ref val8)).startSize = R(0.12f, 0.25f);
				((EmitParams)(ref val8)).startLifetime = R(0.15f, 0.45f);
				((EmitParams)(ref val8)).startColor = Color32.op_Implicit((Color)((i % 3 == 0) ? Color.white : new Color(0.72f, 0.45f, 1f, 1f)));
				val7.Emit(val8, 1);
			}
			Transient transient = new Transient();
			transient.node = val3;
			transient.start = Time.time;
			transient.end = Time.time + 1f;
			transient.lines = new ElectricRibbon[2] { electricRibbon, electricRibbon2 };
			transient.transfer = true;
			transient.sourceTree = tree.root;
			transient.sourceLocal = tree.root.InverseTransformPoint(val);
			transient.target = (Object.op_Implicit((Object)(object)target) ? ((Component)target).transform : null);
			transient.fallbackTarget = val2;
			transient.seed = hit.seq;
			Transient transient2 = transient;
			if (Object.op_Implicit((Object)(object)transient2.target))
			{
				transient2.targetLocal = transient2.target.InverseTransformPoint(val2);
			}
			UpdateTransferArc(transient2, 0f);
			this.transient.Add(transient2);
			return true;
		}

		private void UpdateTransferArc(Transient effect, float age)
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: 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_004e: 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_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: 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_0106: Unknown result type (might be due to invalid IL or missing references)
			//IL_010b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0110: 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_00ff: Unknown result type (might be due to invalid IL or missing references)
			Vector3 val = (Object.op_Implicit((Object)(object)effect.sourceTree) ? effect.sourceTree.TransformPoint(effect.sourceLocal) : effect.node.transform.position);
			Vector3 val2 = (Object.op_Implicit((Object)(object)effect.target) ? effect.target.TransformPoint(effect.targetLocal) : effect.fallbackTarget);
			Vector3[] array = (Vector3[])(object)new Vector3[15];
			Random random = new Random(effect.seed * 7919 + (int)(age * 30f));
			for (int i = 0; i < array.Length; i++)
			{
				float num = (float)i / (float)(array.Length - 1);
				float num2 = Mathf.Sin(num * MathF.PI) * 0.7f;
				array[i] = Vector3.Lerp(val, val2, num) + ((i == 0 || i == array.Length - 1) ? Vector3.zero : (new Vector3((float)random.NextDouble() * 2f - 1f, (float)random.NextDouble() * 2f - 1f, (float)random.NextDouble() * 2f - 1f) * num2));
			}
			bool enabled = (settings.reducedFlashes ? (age < 0.38f) : (age < 0.14f || (age > 0.19f && age < 0.38f)));
			ElectricRibbon[] lines = effect.lines;
			foreach (ElectricRibbon electricRibbon in lines)
			{
				electricRibbon.positionCount = array.Length;
				electricRibbon.SetPositions(array);
				((Behaviour)electricRibbon).enabled = enabled;
			}
		}

		private void Burst(Charged fx, Vector3 point, Vector3 normal, int count, float size, Color color, float spread = 0.25f, float speed = 1f, float lifetime = 1f)
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: 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_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: 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_00ca: Unknown result type (might be due to invalid IL or missing references)
			for (int i = 0; i < count; i++)
			{
				EmitParams val = default(EmitParams);
				((EmitParams)(ref val)).position = point + Rand() * spread;
				((EmitParams)(ref val)).velocity = (normal * R(0.4f, 1.2f) + Rand() * R(0.5f, 2f)) * speed;
				((EmitParams)(ref val)).startLifetime = R(0.12f, 0.4f) * lifetime;
				((EmitParams)(ref val)).startSize = size * R(0.7f, 1.3f);
				((EmitParams)(ref val)).startColor = Color32.op_Implicit((i % 4 == 0) ? Color.white : color);
				EmitParams val2 = val;
				fx.sparks.Emit(val2, 1);
			}
		}

		private void Arc(Charged fx, ElectricRibbon line)
		{
			//IL_007c: 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_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: 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_00ae: 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_00b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0108: Unknown result type (might be due to invalid IL or missing references)
			//IL_010a: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0113: Unknown result type (might be due to invalid IL or missing references)
			//IL_012b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0130: Unknown result type (might be due to invalid IL or missing references)
			//IL_014b: Unknown result type (might be due to invalid IL or missing references)
			//IL_013a: 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_0150: 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)
			StormTrial.Anchor[] anchors = fx.tree.variant.anchors;
			int num = random.Next(4, 10);
			int num2 = random.Next(0, 26 - num);
			int num3 = random.Next(10);
			int num4 = (num3 + random.Next(-3, 4) + 10) % 10;
			StormTrial.Anchor anchor = anchors[num2 * 10 + num3];
			StormTrial.Anchor anchor2 = anchors[(num2 + num) * 10 + num4];
			Vector3 val = fx.tree.root.TransformPoint(anchor.p);
			Vector3 val2 = fx.tree.root.TransformPoint(anchor2.p);
			Vector3 val3 = fx.tree.root.TransformDirection(anchor.normal);
			Vector3 normalized = ((Vector3)(ref val3)).normalized;
			float num5 = R(0.45f, 1.25f);
			Vector3[] array = (Vector3[])(object)new Vector3[11];
			for (int i = 0; i < array.Length; i++)
			{
				float num6 = (float)i / (float)(array.Length - 1);
				bool flag = i == 0 || i == array.Length - 1;
				array[i] = Vector3.Lerp(val, val2, num6) + normalized * (0.08f + Mathf.Sin(num6 * MathF.PI) * num5) + (flag ? Vector3.zero : (Rand() * 0.22f));
			}
			line.positionCount = array.Length;
			line.SetPositions(array);
		}

		private void CrownArc(Charged fx, ElectricRibbon line)
		{
			//IL_000c: 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_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c9: 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_00f3: 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_00fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
			Bounds bounds = fx.tree.foliage.bounds;
			Vector3 center = ((Bounds)(ref bounds)).center;
			Vector3 extents = ((Bounds)(ref bounds)).extents;
			float num = R(0f, MathF.PI * 2f);
			float num2 = R(0.75f, 1.85f);
			float num3 = R(-0.15f, 0.55f);
			Vector3[] array = (Vector3[])(object)new Vector3[11];
			for (int i = 0; i < array.Length; i++)
			{
				float num4 = (float)i / (float)(array.Length - 1);
				float num5 = num + num4 * num2;
				array[i] = center + new Vector3(Mathf.Cos(num5) * extents.x * 0.82f, extents.y * (num3 + Mathf.Sin(num4 * MathF.PI) * 0.2f), Mathf.Sin(num5) * extents.z * 0.82f) + ((i == 0 || i == array.Length - 1) ? Vector3.zero : (Rand() * 0.25f));
			}
			line.positionCount = array.Length;
			line.SetPositions(array);
		}

		public static bool AmbientInView(Bounds bounds)
		{
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			if (viewFrame != Time.frameCount)
			{
				viewFrame = Time.frameCount;
				Camera main = Camera.main;
				hasView = Object.op_Implicit((Object)(object)main) && ((Behaviour)main).isActiveAndEnabled;
				if (hasView)
				{
					GeometryUtility.CalculateFrustumPlanes(main, viewPlanes);
				}
			}
			return !hasView || GeometryUtility.TestPlanesAABB(viewPlanes, bounds);
		}

		public void Tick(StormTrial.Tree[] trees, SharedState state, Character local, double now)
		{
			//IL_0283: Unknown result type (might be due to invalid IL or missing references)
			//IL_0288: Unknown result type (might be due to invalid IL or missing references)
			//IL_0293: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_0100: 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_010f:

plugins/ThunderfenNativeProps/PoisonForestNativeProps.dll

Decompiled a week ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using BepInEx;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Peak;
using Photon.Pun;
using Photon.Realtime;
using PoisonForest;
using PoisonForestGeneration;
using PoisonForestLightning;
using PoisonForestSolo;
using UnityEngine;
using UnityEngine.SceneManagement;
using Zorro.Core;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyVersion("0.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace PoisonForestNativeProps
{
	public sealed class PropSite
	{
		public int kind;

		public int zone;

		public int room;

		public int group;

		public float x;

		public float y;

		public float z;

		public float yaw;

		public float scale;

		public float nx;

		public float ny = 1f;

		public float nz;
	}
	public sealed class CampSite
	{
		public int kind;

		public int model;

		public int requirement;

		public float x;

		public float y;

		public float z;

		public float nx;

		public float ny;

		public float nz;

		public float yaw;

		public float scale;
	}
	public sealed class PropCatalog
	{
		public int seed;

		public float radius;

		public float amount;

		public float interval;

		public float intervalMax;

		public PropSite[] sites;

		public CampSite[] camp = new CampSite[0];

		public static PropCatalog Read(byte[] bytes)
		{
			using MemoryStream memoryStream = new MemoryStream(bytes);
			using BinaryReader binaryReader = new BinaryReader(memoryStream);
			if (binaryReader.ReadInt32() != 1347307088)
			{
				throw new InvalidDataException("Native prop catalog signature");
			}
			int num = binaryReader.ReadInt32();
			if (num < 1 || num > 5)
			{
				throw new InvalidDataException("Native prop catalog version");
			}
			PropCatalog propCatalog = new PropCatalog
			{
				seed = binaryReader.ReadInt32()
			};
			int num2 = binaryReader.ReadInt32();
			if (num2 < 1 || num2 > 2000)
			{
				throw new InvalidDataException("Native prop count");
			}
			propCatalog.radius = binaryReader.ReadSingle();
			propCatalog.amount = binaryReader.ReadSingle();
			propCatalog.interval = binaryReader.ReadSingle();
			propCatalog.intervalMax = ((num >= 2) ? binaryReader.ReadSingle() : propCatalog.interval);
			if (!Finite(propCatalog.intervalMax) || propCatalog.intervalMax < propCatalog.interval || propCatalog.intervalMax > 30f)
			{
				throw new InvalidDataException("Grass interval range");
			}
			if (!Finite(propCatalog.radius) || !Finite(propCatalog.amount) || !Finite(propCatalog.interval) || propCatalog.radius < 1f || propCatalog.radius > 10f || propCatalog.amount <= 0f || propCatalog.amount > 0.25f || propCatalog.interval < 0.25f || propCatalog.interval > 30f)
			{
				throw new InvalidDataException("Grass dose settings");
			}
			propCatalog.sites = new PropSite[num2];
			for (int i = 0; i < num2; i++)
			{
				PropSite propSite = new PropSite
				{
					kind = binaryReader.ReadInt32(),
					zone = binaryReader.ReadInt32(),
					room = binaryReader.ReadInt32(),
					group = binaryReader.ReadInt32(),
					x = binaryReader.ReadSingle(),
					y = binaryReader.ReadSingle(),
					z = binaryReader.ReadSingle(),
					yaw = binaryReader.ReadSingle(),
					scale = binaryReader.ReadSingle()
				};
				if (propSite.kind < 0 || propSite.kind > 5 || propSite.zone < 0 || propSite.zone > 2 || propSite.zone == 2 != propSite.room >= 0 || propSite.kind == 0 != propSite.group >= 0 || !Finite(propSite.x) || !Finite(propSite.y) || !Finite(propSite.z) || !Finite(propSite.yaw) || !Finite(propSite.scale) || propSite.scale < 0.5f || propSite.scale > 2f)
				{
					throw new InvalidDataException("Invalid native prop site " + i);
				}
				if (num >= 5)
				{
					propSite.nx = binaryReader.ReadSingle();
					propSite.ny = binaryReader.ReadSingle();
					propSite.nz = binaryReader.ReadSingle();
					if (!Finite(propSite.nx) || !Finite(propSite.ny) || !Finite(propSite.nz) || propSite.ny < 0.8f || Math.Abs(propSite.nx * propSite.nx + propSite.ny * propSite.ny + propSite.nz * propSite.nz - 1f) > 0.01f)
					{
						throw new InvalidDataException("Invalid surface normal " + i);
					}
				}
				propCatalog.sites[i] = propSite;
			}
			if (num >= 3)
			{
				if (binaryReader.ReadInt32() != 1346586192)
				{
					throw new InvalidDataException("Camp catalog signature");
				}
				int num3 = binaryReader.ReadInt32();
				if (num3 != ((num == 3) ? 11 : 12))
				{
					throw new InvalidDataException("Camp site count");
				}
				propCatalog.camp = new CampSite[num3];
				int num4 = 0;
				int num5 = 0;
				int num6 = 0;
				int num7 = 0;
				int num8 = 0;
				int num9 = 0;
				for (int j = 0; j < num3; j++)
				{
					CampSite campSite = new CampSite
					{
						kind = binaryReader.ReadInt32(),
						model = binaryReader.ReadInt32(),
						requirement = binaryReader.ReadInt32(),
						x = binaryReader.ReadSingle(),
						y = binaryReader.ReadSingle(),
						z = binaryReader.ReadSingle(),
						nx = binaryReader.ReadSingle(),
						ny = binaryReader.ReadSingle(),
						nz = binaryReader.ReadSingle(),
						yaw = binaryReader.ReadSingle(),
						scale = binaryReader.ReadSingle()
					};
					if (campSite.kind < 0 || campSite.kind > ((num == 3) ? 3 : 4) || campSite.model < 0 || campSite.model > ((campSite.kind == 0 && num >= 4) ? 11 : 3) || campSite.requirement < 0 || campSite.requirement > 4 || !Finite(campSite.x) || !Finite(campSite.y) || !Finite(campSite.z) || !Finite(campSite.nx) || !Finite(campSite.ny) || !Finite(campSite.nz) || !Finite(campSite.yaw) || !Finite(campSite.scale) || campSite.scale < 0.5f || campSite.scale > ((num >= 4) ? 2.5f : 2f) || campSite.ny < 0.8f || Math.Abs(campSite.nx * campSite.nx + campSite.ny * campSite.ny + campSite.nz * campSite.nz - 1f) > 0.01f)
					{
						throw new InvalidDataException("Invalid camp site");
					}
					if (campSite.kind == 0)
					{
						num4++;
					}
					else if (campSite.kind == 1)
					{
						if (campSite.requirement < 1 || (num9 & (1 << campSite.requirement)) != 0)
						{
							throw new InvalidDataException("Duplicate food slot");
						}
						num9 |= 1 << campSite.requirement;
						num5++;
					}
					else if (campSite.kind == 2)
					{
						num6++;
					}
					else if (campSite.kind == 3)
					{
						num7++;
					}
					else
					{
						num8++;
					}
					if (campSite.kind != 1 && campSite.requirement != 0)
					{
						throw new InvalidDataException("Invalid player requirement");
					}
					propCatalog.camp[j] = campSite;
				}
				if (num4 != 5 || num5 != 4 || num6 != 1 || num7 != 1 || num8 != ((num != 3) ? 1 : 0) || num9 != 30)
				{
					throw new InvalidDataException("Incomplete camp clearing");
				}
			}
			if (memoryStream.Position != memoryStream.Length)
			{
				throw new InvalidDataException("Trailing native prop data");
			}
			return propCatalog;
		}

		public static bool Finite(float f)
		{
			return !float.IsNaN(f) && !float.IsInfinity(f);
		}
	}
	public sealed class PlantClock
	{
		private readonly double minimum;

		private readonly double maximum;

		private readonly Random random;

		private double remaining;

		public double Remaining => remaining;

		public double LastInterval { get; private set; }

		public PlantClock(double period = 2.0)
			: this(period, period, new Random())
		{
		}

		public PlantClock(double min, double max, Random source)
		{
			if (double.IsNaN(min) || double.IsInfinity(min) || double.IsNaN(max) || double.IsInfinity(max) || min < 0.25 || max < min || max > 30.0 || source == null)
			{
				throw new ArgumentOutOfRangeException();
			}
			minimum = min;
			maximum = max;
			random = source;
			remaining = Next();
		}

		private double Next()
		{
			LastInterval = minimum + (maximum - minimum) * random.NextDouble();
			return LastInterval;
		}

		public bool Tick(double dt)
		{
			if (double.IsNaN(dt) || double.IsInfinity(dt) || dt < 0.0)
			{
				throw new ArgumentOutOfRangeException();
			}
			remaining -= Math.Min(dt, 1.0);
			if (remaining > 1E-08)
			{
				return false;
			}
			remaining += Next();
			return true;
		}
	}
	public sealed class GrassStrikeClock
	{
		public const double Windup = 0.18;

		public const double VisualDuration = 0.55;

		private double doseAt;

		private double visualUntil;

		public bool Pending { get; private set; }

		public void Begin(double now)
		{
			if (double.IsNaN(now) || double.IsInfinity(now))
			{
				throw new ArgumentOutOfRangeException();
			}
			Pending = true;
			doseAt = now + 0.18;
			visualUntil = now + 0.55;
		}

		public bool TakeDose(double now)
		{
			if (!Pending || now + 1E-07 < doseAt)
			{
				return false;
			}
			Pending = false;
			return true;
		}

		public bool VisualActive(double now)
		{
			return now < visualUntil;
		}

		public void Cancel()
		{
			Pending = false;
			visualUntil = double.NegativeInfinity;
		}
	}
	[BepInPlugin("local.peak.poisonforest.nativeprops", "Thunderfen Hazards and Luggage", "1.0.1")]
	[BepInDependency("local.peak.poisonforest.electrical", "0.1.5")]
	[BepInDependency("local.peak.poisonforest.solo", "0.6.4")]
	[BepInDependency("local.peak.poisonforest.lightning", "0.3.4")]
	[BepInDependency("local.peak.poisonforest.cavebugs", "0.1.4")]
	[DefaultExecutionOrder(1150)]
	public sealed class NativePropsTrial : BaseUnityPlugin
	{
		private sealed class Plant
		{
			public SharedPulse shared;

			public Transform node;

			public PlantClock clock = new PlantClock();

			public GrassStrikeClock strikeClock = new GrassStrikeClock();

			public GrassDischargeVisual discharge;

			public Character target;

			public GrassAmbientArcs ambient;
		}

		[Serializable]
		private sealed class Report
		{
			public string utc;

			public string version = "1.0.1";

			public string message;

			public string error;

			public string grassModel = "thunderfen-arc-sedge-v1";

			public string prefabPool;

			public string amuletStatue;

			public int seed;

			public int revision;

			public int plants;

			public int bombs;

			public int chests;

			public int transfers;

			public int routedCreates;

			public int routedDeletes;

			public string[] cached;

			public string[] campLootConfiguration;

			public int[] modelVariants;

			public bool pending;

			public bool campReady;

			public bool routingReady;

			public int campBuiltSites;

			public string campWaiting;
		}

		public sealed class NativePool : IPunPrefabPool
		{
			public const string Prefix = "PFNativeProps/";

			public readonly IPunPrefabPool Previous;

			private readonly Dictionary<string, GameObject> prefabs;

			public Func<int, int, GameObject> makeCamp;

			public Func<bool> campReady;

			public Action ensureTemplates;

			public Func<Transform> worldParent;

			public static Action<GameObject> ConfigureCamp;

			private readonly HashSet<DeferredBombGroup> bombs = new HashSet<DeferredBombGroup>();

			public NativePool(IPunPrefabPool previous, Dictionary<string, GameObject> sources)
			{
				Previous = previous;
				prefabs = sources;
			}

			public GameObject Instantiate(string id, Vector3 p, Quaternion r)
			{
				//IL_001d: 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_0360: Unknown result type (might be due to invalid IL or missing references)
				//IL_0361: Unknown result type (might be due to invalid IL or missing references)
				//IL_02d5: Unknown result type (might be due to invalid IL or missing references)
				//IL_02d6: Unknown result type (might be due to invalid IL or missing references)
				//IL_01ca: Unknown result type (might be due to invalid IL or missing references)
				//IL_01cb: Unknown result type (might be due to invalid IL or missing references)
				if (!id.StartsWith("PFNativeProps/", StringComparison.Ordinal))
				{
					return Previous.Instantiate(id, p, r);
				}
				string text = id.Substring("PFNativeProps/".Length);
				string site = text;
				bool flag = false;
				GameObject val;
				if (text.StartsWith("Camp/", StringComparison.Ordinal))
				{
					string[] array = text.Split('/');
					if (array.Length != 4)
					{
						throw new Exception("Invalid camp site identity");
					}
					int num = int.Parse(array[1]);
					int num2 = int.Parse(array[2]);
					if (makeCamp != null && campReady != null && campReady())
					{
						val = makeCamp(num, num2);
					}
					else
					{
						if (!prefabs.ContainsKey(array[3]))
						{
							ensureTemplates?.Invoke();
						}
						val = DeferredCampSite.Create(array[3], num, num2, prefabs);
					}
					site = "camp:" + num;
					flag = true;
				}
				else
				{
					if (text == "Bombs" || text.StartsWith("Bombs/", StringComparison.Ordinal))
					{
						string text2 = ((text == "Bombs") ? "" : text.Substring(6));
						if (SharedWorld.Online && (text2.Length != 34 || (!text2.StartsWith("N:", StringComparison.Ordinal) && !text2.StartsWith("C:", StringComparison.Ordinal)) || !Guid.TryParseExact(text2.Substring(2), "N", out var _)))
						{
							throw new InvalidDataException("Invalid Thunderfen bomb run identity");
						}
						DeferredBombGroup deferredBombGroup = DeferredBombGroup.Create(text2, PhotonNetwork.CurrentRoom, p, r);
						bombs.Add(deferredBombGroup);
						return ((Component)deferredBombGroup).gameObject;
					}
					if (text.StartsWith("World/", StringComparison.Ordinal))
					{
						string[] array2 = text.Split('/');
						if (array2.Length != 3 || !int.TryParse(array2[1], out var result2) || result2 < 0 || result2 > 2000)
						{
							throw new Exception("Invalid world prop identity");
						}
						site = "world:" + result2;
						text = array2[2];
					}
					if (!prefabs.ContainsKey(text))
					{
						ensureTemplates?.Invoke();
					}
					if (!prefabs.TryGetValue(text, out var value) || (!text.StartsWith("Luggage", StringComparison.Ordinal) && !(text == "CampfireFoodSpawner") && !(text == "PF_RespawnStatue")))
					{
						throw new Exception("Unknown native prop alias");
					}
					val = Object.Instantiate<GameObject>(value, p, r);
					val.SetActive(false);
					if (text.StartsWith("Luggage", StringComparison.Ordinal))
					{
						ChestLootPolicy.Configure(val.GetComponent<Luggage>(), text);
					}
					val.AddComponent<OwnedNativeProp>();
					ConfigureCamp?.Invoke(val);
				}
				OwnedNativeProp ownedNativeProp = val.GetComponent<OwnedNativeProp>();
				if (!Object.op_Implicit((Object)(object)ownedNativeProp))
				{
					ownedNativeProp = val.AddComponent<OwnedNativeProp>();
				}
				ownedNativeProp.epoch = SharedWorld.Epoch;
				ownedNativeProp.site = site;
				ownedNativeProp.camp = flag;
				val.transform.SetPositionAndRotation(p, r);
				if (!flag && worldParent != null)
				{
					val.transform.SetParent(worldParent(), true);
				}
				return val;
			}

			public void Destroy(GameObject obj)
			{
				if (Object.op_Implicit((Object)(object)obj) && Object.op_Implicit((Object)(object)obj.GetComponent<OwnedNativeProp>()))
				{
					Object.Destroy((Object)(object)obj);
				}
				else
				{
					Previous.Destroy(obj);
				}
			}

			internal void PruneBombs()
			{
				DeferredBombGroup[] array = bombs.ToArray();
				foreach (DeferredBombGroup deferredBombGroup in array)
				{
					if (!Object.op_Implicit((Object)(object)deferredBombGroup))
					{
						bombs.Remove(deferredBombGroup);
					}
					else if (!deferredBombGroup.SameRoom || !deferredBombGroup.CanBelongTo(SharedWorld.RoomRun))
					{
						deferredBombGroup.Retire();
						bombs.Remove(deferredBombGroup);
					}
				}
			}

			internal void PopulateBombs(Transform frame, PropCatalog catalog, GameObject template)
			{
				foreach (DeferredBombGroup bomb in bombs)
				{
					if (Object.op_Implicit((Object)(object)bomb) && bomb.SameRoom && bomb.MatchesRun(SharedWorld.Epoch))
					{
						bomb.Populate(frame, catalog, template);
					}
				}
			}

			internal void ReleaseBombs()
			{
				foreach (DeferredBombGroup bomb in bombs)
				{
					if (Object.op_Implicit((Object)(object)bomb))
					{
						bomb.Retire();
					}
				}
				bombs.Clear();
			}
		}

		public const string Id = "local.peak.poisonforest.nativeprops";

		public const string Version = "1.0.1";

		private static readonly string[] Names = new string[6] { "ArcSedge", "Jungle_SporeMushroom", "LuggageSmall", "LuggageBig", "LuggageEpic", "LuggageAncient" };

		private PropCatalog activeCatalog;

		private readonly Dictionary<string, GameObject> templates = new Dictionary<string, GameObject>();

		private readonly List<GameObject> spawned = new List<GameObject>();

		private readonly List<Plant> plants = new List<Plant>();

		private Harmony harmony;

		private AssetBundle grassBundle;

		private GameObject[] grassVariants;

		private GrassSurfaceMaterials grassMaterials;

		private readonly int[] variantCounts = new int[6];

		private GameObject storage;

		private GameObject localRoot;

		private Transform frame;

		private NativePool pool;

		private Material spark;

		private int revision = -1;

		private int seed;

		private int transfers;

		private float grassRadius = 6.75f;

		private float grassAmount = 0.02f;

		private float nextPoll;

		private float nextCache;

		private float nextReport;

		private bool ready;

		private bool released;

		private string error;

		private string message = "Waiting for native prefab references";

		private readonly RaycastHit[] hits = (RaycastHit[])(object)new RaycastHit[64];

		private static readonly FieldInfo electricalReady = typeof(ElectricalTrial).GetField("ready", BindingFlags.Instance | BindingFlags.NonPublic);

		private static readonly FieldInfo electricalFailed = typeof(ElectricalTrial).GetField("failed", BindingFlags.Instance | BindingFlags.NonPublic);

		private static readonly FieldInfo electricalCompatible = typeof(ElectricalTrial).GetField("compatible", BindingFlags.Instance | BindingFlags.NonPublic);

		private bool startupFailed;

		public static string PrefabName(int kind)
		{
			return Names[kind];
		}

		private void Awake()
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Expected O, but got Unknown
			//IL_01c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cf: Expected O, but got Unknown
			try
			{
				NativeCompatibility.CheckPatches(typeof(NativePropsTrial).Assembly);
				storage = new GameObject("PF_NativePropTemplates");
				storage.SetActive(false);
				Object.DontDestroyOnLoad((Object)(object)storage);
				grassBundle = AssetBundle.LoadFromFile(Path.Combine(Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location), "pf-chargedgrass"));
				if (!Object.op_Implicit((Object)(object)grassBundle))
				{
					throw new Exception("Charged-grass model bundle missing");
				}
				grassVariants = (from i in Enumerable.Range(0, 6)
					select grassBundle.LoadAsset<GameObject>("ArcSedge_V" + i)).ToArray();
				if (grassVariants.Any((GameObject v) => !Object.op_Implicit((Object)(object)v) || !Object.op_Implicit((Object)(object)v.GetComponent<MeshFilter>()) || !Object.op_Implicit((Object)(object)v.GetComponent<MeshFilter>().sharedMesh) || !Object.op_Implicit((Object)(object)v.GetComponent<MeshRenderer>()) || !((Renderer)v.GetComponent<MeshRenderer>()).sharedMaterial.shader.isSupported || v.GetComponentsInChildren<Collider>(true).Length != 0))
				{
					throw new Exception("Charged-grass model library is invalid");
				}
				spark = ((IEnumerable<Material>)Resources.FindObjectsOfTypeAll<Material>()).FirstOrDefault((Func<Material, bool>)((Material m) => Object.op_Implicit((Object)(object)m) && ((Object)m).name == "CaveBugParticles"));
				if (!Object.op_Implicit((Object)(object)spark) || !Object.op_Implicit((Object)(object)spark.shader) || !spark.shader.isSupported)
				{
					throw new Exception("Electrical particle shader unsupported");
				}
				grassMaterials = new GrassSurfaceMaterials(((Renderer)grassVariants[0].GetComponent<MeshRenderer>()).sharedMaterial);
				pool = new NativePool(PhotonNetwork.PrefabPool, templates)
				{
					ensureTemplates = Cache
				};
				PrefabDispatch.Handler = (IPunPrefabPool)(object)pool;
				PrefabDispatch.Creates = (PrefabDispatch.Deletes = 0);
				SceneManager.sceneLoaded += Recover;
				harmony = new Harmony("local.peak.poisonforest.nativeprops.camp");
				harmony.PatchAll(typeof(NativePropsTrial).Assembly);
				SharedWorld.Message += OnShared;
				ready = true;
				((BaseUnityPlugin)this).Logger.LogInfo((object)"Props ready; lifecycle-safe native prefab routing, original arc-sedge model library, 2–4 plants/group, independent 2% doses every random 2–5s, radius 6.75; native poison mushrooms and weighted luggage. Shared solo/multiplayer factories; no input bindings.");
			}
			catch (Exception e)
			{
				startupFailed = true;
				Release();
				SharedWorld.MarkStartupFailure("Thunderfen native props");
				Fail(e);
			}
		}

		private void Recover(Scene scene, LoadSceneMode mode)
		{
			if (!ready && !startupFailed && !released && error != null && (!(((Scene)(ref scene)).name != "Title") || !(((Scene)(ref scene)).name != "Airport")))
			{
				error = null;
				message = "Recovered after a runtime failure";
				ready = true;
				((BaseUnityPlugin)this).Logger.LogInfo((object)("Native props recovered after a runtime failure, on loading " + ((Scene)(ref scene)).name + "."));
			}
		}

		private void Cache()
		{
			//IL_0272: Unknown result type (might be due to invalid IL or missing references)
			//IL_0279: Expected O, but got Unknown
			//IL_0373: Unknown result type (might be due to invalid IL or missing references)
			//IL_0378: Unknown result type (might be due to invalid IL or missing references)
			PropSpawner[] array = Resources.FindObjectsOfTypeAll<PropSpawner>();
			foreach (PropSpawner val in array)
			{
				if (Object.op_Implicit((Object)(object)val) && val.props != null)
				{
					GameObject[] props = val.props;
					foreach (GameObject go in props)
					{
						Consider(go);
					}
				}
			}
			if (!templates.ContainsKey("PF_RespawnStatue"))
			{
				GameObject val2 = (from p in Resources.FindObjectsOfTypeAll<PropSpawner>()
					where Object.op_Implicit((Object)(object)p) && p.props != null
					select p).SelectMany((PropSpawner p) => p.props).FirstOrDefault((Func<GameObject, bool>)delegate(GameObject g)
				{
					//IL_0009: Unknown result type (might be due to invalid IL or missing references)
					//IL_000e: Unknown result type (might be due to invalid IL or missing references)
					int result;
					if (Object.op_Implicit((Object)(object)g))
					{
						Scene scene2 = g.scene;
						if (!((Scene)(ref scene2)).IsValid() && ((Object)g).name == "RespawnChest")
						{
							result = (Object.op_Implicit((Object)(object)g.GetComponentInChildren<RespawnChest>(true)) ? 1 : 0);
							goto IL_0039;
						}
					}
					result = 0;
					goto IL_0039;
					IL_0039:
					return (byte)result != 0;
				});
				if (!Object.op_Implicit((Object)(object)val2))
				{
					RespawnChest val3 = ((IEnumerable<RespawnChest>)Resources.FindObjectsOfTypeAll<RespawnChest>()).FirstOrDefault((Func<RespawnChest, bool>)delegate(RespawnChest c)
					{
						//IL_000e: Unknown result type (might be due to invalid IL or missing references)
						//IL_0013: Unknown result type (might be due to invalid IL or missing references)
						int result;
						if (Object.op_Implicit((Object)(object)c))
						{
							Scene scene2 = ((Component)c).gameObject.scene;
							result = ((!((Scene)(ref scene2)).IsValid()) ? 1 : 0);
						}
						else
						{
							result = 0;
						}
						return (byte)result != 0;
					});
					if (Object.op_Implicit((Object)(object)val3))
					{
						Transform val4 = ((Component)val3).transform;
						while (Object.op_Implicit((Object)(object)val4.parent))
						{
							val4 = val4.parent;
						}
						if (((Object)val4).name == "RespawnChest")
						{
							val2 = ((Component)val4).gameObject;
						}
					}
				}
				if (Object.op_Implicit((Object)(object)val2))
				{
					GameObject val5 = Object.Instantiate<GameObject>(val2, storage.transform);
					((Object)val5).name = "PF_RespawnStatue";
					val5.SetActive(false);
					PhotonView[] componentsInChildren = val5.GetComponentsInChildren<PhotonView>(true);
					foreach (PhotonView val6 in componentsInChildren)
					{
						val6.ViewID = 0;
					}
					templates.Add(((Object)val5).name, val5);
					((BaseUnityPlugin)this).Logger.LogInfo((object)"Cached original native statue prefab with nested revive component");
				}
			}
			if (!templates.ContainsKey("PF_BackpackSpawner"))
			{
				SingleItemSpawner val7 = ((IEnumerable<SingleItemSpawner>)Resources.FindObjectsOfTypeAll<SingleItemSpawner>()).FirstOrDefault((Func<SingleItemSpawner, bool>)((SingleItemSpawner c) => Object.op_Implicit((Object)(object)c) && Object.op_Implicit((Object)(object)c.prefab) && ((Object)c.prefab).name.StartsWith("Backpack", StringComparison.Ordinal) && !((Object)c).name.StartsWith("PF_", StringComparison.Ordinal)));
				if (Object.op_Implicit((Object)(object)val7))
				{
					GameObject val8 = new GameObject("PF_BackpackSpawner");
					val8.SetActive(false);
					val8.transform.SetParent(storage.transform, false);
					SingleItemSpawner val9 = val8.AddComponent<SingleItemSpawner>();
					val9.prefab = val7.prefab;
					val9.isKinematic = val7.isKinematic;
					val9.playersInRoomRequirement = val7.playersInRoomRequirement;
					val9.belowAscentRequirement = val7.belowAscentRequirement;
					templates.Add(((Object)val8).name, val8);
					((BaseUnityPlugin)this).Logger.LogInfo((object)("Cached native backpack spawner configuration: " + ((Object)val9.prefab).name + " players=" + val9.playersInRoomRequirement + " ascent=" + val9.belowAscentRequirement));
				}
			}
			Luggage[] array2 = Resources.FindObjectsOfTypeAll<Luggage>();
			foreach (Luggage val10 in array2)
			{
				if (Object.op_Implicit((Object)(object)val10))
				{
					Scene scene = ((Component)val10).gameObject.scene;
					if (!((Scene)(ref scene)).IsValid())
					{
						Consider(((Component)val10).gameObject);
					}
				}
			}
		}

		private void Consider(GameObject go)
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
			Scene scene;
			if (Object.op_Implicit((Object)(object)go) && CampfireSiteRuntime.Extra.Contains(((Object)go).name))
			{
				scene = go.scene;
				if (!((Scene)(ref scene)).IsValid() && !templates.ContainsKey(((Object)go).name))
				{
					GameObject val = Object.Instantiate<GameObject>(go, storage.transform);
					((Object)val).name = ((Object)go).name;
					val.SetActive(false);
					PhotonView[] componentsInChildren = val.GetComponentsInChildren<PhotonView>(true);
					foreach (PhotonView val2 in componentsInChildren)
					{
						val2.ViewID = 0;
					}
					templates.Add(((Object)go).name, val);
					return;
				}
			}
			if (!Object.op_Implicit((Object)(object)go) || !Names.Contains(((Object)go).name) || templates.ContainsKey(((Object)go).name))
			{
				return;
			}
			scene = go.scene;
			if (((Scene)(ref scene)).IsValid())
			{
				return;
			}
			int num = Array.IndexOf(Names, ((Object)go).name);
			if (num >= 1 && (num != 1 || (Object.op_Implicit((Object)(object)go.GetComponent<TriggerEvent>()) && Object.op_Implicit((Object)(object)go.GetComponent<SpawnGameObject>()))) && (num < 2 || (Object.op_Implicit((Object)(object)go.GetComponent<Luggage>()) && Object.op_Implicit((Object)(object)go.GetComponent<PhotonView>()))))
			{
				GameObject val3 = Object.Instantiate<GameObject>(go, storage.transform);
				((Object)val3).name = ((Object)go).name;
				val3.SetActive(false);
				PhotonView[] componentsInChildren2 = val3.GetComponentsInChildren<PhotonView>(true);
				foreach (PhotonView val4 in componentsInChildren2)
				{
					val4.ViewID = 0;
				}
				templates.Add(((Object)go).name, val3);
				((BaseUnityPlugin)this).Logger.LogInfo((object)("Cached native prefab " + ((Object)go).name));
			}
		}

		private void Update()
		{
			//IL_0088: 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_0379: Unknown result type (might be due to invalid IL or missing references)
			//IL_0385: Unknown result type (might be due to invalid IL or missing references)
			//IL_038a: Unknown result type (might be due to invalid IL or missing references)
			//IL_038f: Unknown result type (might be due to invalid IL or missing references)
			//IL_067b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0680: Unknown result type (might be due to invalid IL or missing references)
			//IL_068a: Unknown result type (might be due to invalid IL or missing references)
			//IL_068f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0694: Unknown result type (might be due to invalid IL or missing references)
			//IL_069e: Unknown result type (might be due to invalid IL or missing references)
			//IL_06a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_03f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_0400: Unknown result type (might be due to invalid IL or missing references)
			//IL_0405: Unknown result type (might be due to invalid IL or missing references)
			//IL_040a: Unknown result type (might be due to invalid IL or missing references)
			//IL_042a: Unknown result type (might be due to invalid IL or missing references)
			//IL_042f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0439: Unknown result type (might be due to invalid IL or missing references)
			//IL_043e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0445: Unknown result type (might be due to invalid IL or missing references)
			//IL_0620: Unknown result type (might be due to invalid IL or missing references)
			//IL_0625: Unknown result type (might be due to invalid IL or missing references)
			//IL_05c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_05ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_05d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_05d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_05df: Unknown result type (might be due to invalid IL or missing references)
			if (!ready)
			{
				return;
			}
			try
			{
				pool.PruneBombs();
				if (Time.unscaledTime >= nextCache)
				{
					nextCache = Time.unscaledTime + 3f;
					AmuletStatue.CaptureNativeVariants();
					if (Names.Skip(1).Concat(CampfireSiteRuntime.Extra).Any((string n) => !templates.ContainsKey(n)))
					{
						Cache();
					}
				}
				Scene sceneByName = SceneManager.GetSceneByName("WilIsland");
				if (!((Scene)(ref sceneByName)).isLoaded || !PhotonNetwork.InRoom)
				{
					if (Object.op_Implicit((Object)(object)frame) || Object.op_Implicit((Object)(object)localRoot))
					{
						Clear();
					}
					SharedWorld.ModuleReady("nativeprops", false);
					ReportNow();
					return;
				}
				if (revision != RunData.Revision)
				{
					if (!SharedWorld.Online || Object.op_Implicit((Object)(object)localRoot))
					{
						Clear();
					}
					revision = RunData.Revision;
				}
				if (!SoloGenerationPlugin.LocalMapReady)
				{
					SharedWorld.ModuleReady("nativeprops", false);
					ReportNow();
					return;
				}
				if (Time.unscaledTime >= nextPoll)
				{
					AmuletStatue.EnsurePublished();
					nextPoll = Time.unscaledTime + 0.5f;
					NativeBarkTextures.Bind(grassMaterials.Outdoor, false);
					NativeBarkTextures.Bind(grassMaterials.Cave, false);
					Transform val = FindFrame();
					if ((Object)(object)val != (Object)(object)frame)
					{
						Clear();
						frame = val;
					}
					if (Object.op_Implicit((Object)(object)frame) && Names.Skip(1).Concat(CampfireSiteRuntime.Extra).All(templates.ContainsKey))
					{
						Prepare();
						pool.PopulateBombs(frame, activeCatalog, templates[Names[1]]);
						SharedWorld.ModuleReady("nativeprops", true);
					}
					if (Object.op_Implicit((Object)(object)frame) && !Object.op_Implicit((Object)(object)localRoot) && !RunData.Pending && SharedWorld.Ready && activeCatalog != null)
					{
						Build();
					}
					if (Object.op_Implicit((Object)(object)localRoot) && SharedWorld.Ready)
					{
						EnsureWorldSpawns();
						CampfireSiteRuntime.TryBuild(frame, activeCatalog, templates);
					}
				}
				if (!Object.op_Implicit((Object)(object)localRoot) || !Object.op_Implicit((Object)(object)frame) || !((Component)frame).gameObject.activeInHierarchy || !SharedWorld.Ready)
				{
					ReportNow();
					return;
				}
				Character localCharacter = Character.localCharacter;
				ElectricalTrial instance = ElectricalTrial.Instance;
				bool flag = ElectricalEligible(localCharacter);
				for (int num = 0; num < plants.Count; num++)
				{
					Plant plant = plants[num];
					if (!Object.op_Implicit((Object)(object)plant.node))
					{
						continue;
					}
					float num2;
					Vector3 val2;
					if (!Object.op_Implicit((Object)(object)localCharacter))
					{
						num2 = float.PositiveInfinity;
					}
					else
					{
						val2 = localCharacter.Center - plant.node.position;
						num2 = ((Vector3)(ref val2)).sqrMagnitude;
					}
					float num3 = num2;
					if (SharedWorld.Online)
					{
						bool flag2 = plant.shared.Tick(SharedWorld.Elapsed);
						if (SharedWorld.Authority && flag2)
						{
							foreach (Character allCharacter in Character.AllCharacters)
							{
								if (ElectricalEligible(allCharacter))
								{
									val2 = allCharacter.Center - plant.node.position;
									if (((Vector3)(ref val2)).sqrMagnitude <= grassRadius * grassRadius && LineClear(plant.node.position + Vector3.up * 0.65f, allCharacter.Center))
									{
										SharedWorld.Charge("grass:" + num, ((MonoBehaviourPun)allCharacter).photonView.ViewID, grassAmount, 0.18f, plant.shared.Serial);
									}
								}
							}
						}
					}
					else
					{
						if (plant.strikeClock.Pending && (!flag || (Object)(object)plant.target != (Object)(object)localCharacter))
						{
							plant.strikeClock.Cancel();
							plant.target = null;
						}
						if (plant.strikeClock.TakeDose(Time.time) && flag && (Object)(object)plant.target == (Object)(object)localCharacter)
						{
							float charge = instance.Model.Charge;
							instance.Model.Set(charge + grassAmount);
							if (instance.Model.Charge > charge)
							{
								localCharacter.ClampStamina();
								ElectricalTrial.RefreshBar();
								transfers++;
							}
							plant.target = null;
						}
						if (plant.clock.Tick(Time.deltaTime) && flag && instance.Model.Charge < 0.99999f && num3 <= grassRadius * grassRadius && LineClear(plant.node.position + Vector3.up * 0.65f, localCharacter.Center))
						{
							plant.target = localCharacter;
							plant.strikeClock.Begin(Time.time);
							Character struck = localCharacter;
							Vector3 lastCenter = localCharacter.Center;
							plant.discharge.Begin(Time.time, () => Object.op_Implicit((Object)(object)struck) ? struck.Center : lastCenter);
						}
					}
					plant.discharge.Tick(Time.time);
					plant.ambient.Tick(Time.time, num3 < 2025f && StormVisuals.AmbientInView(new Bounds(plant.node.position + Vector3.up * 0.6f, Vector3.one * 3f)));
				}
				ReportNow();
			}
			catch (Exception e)
			{
				Fail(e);
			}
		}

		private bool ElectricalEligible(Character c)
		{
			ElectricalTrial instance = ElectricalTrial.Instance;
			return ElectricalTrial.CanReceive(c) && ElectricalTrial.ChargeFor(c) < 0.99999f && Object.op_Implicit((Object)(object)instance) && electricalReady != null && (bool)electricalReady.GetValue(instance) && !(bool)electricalFailed.GetValue(instance) && (bool)electricalCompatible.GetValue(instance);
		}

		private void OnShared(string kind, string id, object[] data)
		{
			//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
			if (!SharedWorld.Online || kind != "charge" || data.Length != 5 || !Object.op_Implicit((Object)(object)localRoot) || !(data[0] is string text) || !text.StartsWith("grass:", StringComparison.Ordinal) || !int.TryParse(text.Substring(6), out var result) || result < 0 || result >= plants.Count)
			{
				return;
			}
			Character target = SharedWorld.CharacterFor(Convert.ToInt32(data[1]));
			if (Object.op_Implicit((Object)(object)target))
			{
				Vector3 point = target.Center;
				plants[result].discharge.Begin(Time.time, () => Object.op_Implicit((Object)(object)target) ? target.Center : point);
			}
		}

		private void Prepare()
		{
			if (activeCatalog == null)
			{
				activeCatalog = PropCatalog.Read(GeneratedData.Read("native-props.bin"));
				seed = activeCatalog.seed;
				grassRadius = activeCatalog.radius;
				grassAmount = activeCatalog.amount;
			}
			pool.worldParent = () => frame;
			pool.makeCamp = (int index, int segment) => CampfireSiteRuntime.CreateSite(frame, activeCatalog, index, segment, templates);
			pool.campReady = () => Object.op_Implicit((Object)(object)frame) && activeCatalog != null && Object.op_Implicit((Object)(object)CampfireSiteRuntime.CampRoot(frame));
			int num = CampfireSiteRuntime.CompleteDeferred(frame, activeCatalog, templates);
			if (num > 0)
			{
				((BaseUnityPlugin)this).Logger.LogInfo((object)("Set up " + num + " camp sites that arrived before the map was ready."));
			}
		}

		private void EnsureWorldSpawns()
		{
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0189: Unknown result type (might be due to invalid IL or missing references)
			//IL_018e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0199: Unknown result type (might be due to invalid IL or missing references)
			//IL_019e: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01dd: Unknown result type (might be due to invalid IL or missing references)
			if (!PhotonNetwork.IsMasterClient)
			{
				return;
			}
			HashSet<string> hashSet = (from n in OwnedNativeProp.All
				where Object.op_Implicit((Object)(object)n) && n.epoch == SharedWorld.Epoch
				select n.site).ToHashSet();
			if (!hashSet.Contains("bombs") && SharedWorld.ClaimSite("bombs"))
			{
				string text = (SharedWorld.Online ? ("/" + SharedWorld.Epoch) : "");
				spawned.Add(PhotonNetwork.InstantiateRoomObject("PFNativeProps/Bombs" + text, Vector3.zero, Quaternion.identity, (byte)0, (object[])null));
				pool.PopulateBombs(frame, activeCatalog, templates[Names[1]]);
			}
			for (int num = 0; num < activeCatalog.sites.Length; num++)
			{
				PropSite propSite = activeCatalog.sites[num];
				if (propSite.kind >= 2 && !hashSet.Contains("world:" + num) && SharedWorld.ClaimSite("world:" + num))
				{
					spawned.Add(PhotonNetwork.InstantiateRoomObject("PFNativeProps/World/" + num + "/" + Names[propSite.kind], frame.TransformPoint(Position(propSite)), frame.rotation * Quaternion.FromToRotation(Vector3.up, new Vector3(propSite.nx, propSite.ny, propSite.nz)) * Quaternion.Euler(0f, propSite.yaw, 0f), (byte)0, (object[])null));
				}
			}
		}

		private Transform FindFrame()
		{
			//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)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Expected O, but got Unknown
			Scene sceneByName = SceneManager.GetSceneByName("WilIsland");
			if (!((Scene)(ref sceneByName)).IsValid())
			{
				return null;
			}
			GameObject val = ((IEnumerable<GameObject>)((Scene)(ref sceneByName)).GetRootGameObjects()).FirstOrDefault((Func<GameObject, bool>)((GameObject o) => ((Object)o).name == "Map"));
			Transform val2 = (Object.op_Implicit((Object)(object)val) ? val.transform.Find("Global") : null);
			if (!Object.op_Implicit((Object)(object)val2))
			{
				return null;
			}
			foreach (Transform item in val2)
			{
				Transform val3 = item;
				if (((Object)val3).name.Contains("first-ridge"))
				{
					Transform val4 = ((IEnumerable<Transform>)((Component)val3).GetComponentsInChildren<Transform>(true)).FirstOrDefault((Func<Transform, bool>)((Transform x) => ((Object)x).name == "PF_HybridTerrain" && Object.op_Implicit((Object)(object)x.parent) && ((Object)x.parent).name == "RootsTerrain"));
					if (Object.op_Implicit((Object)(object)val4) && ((Component)val4).gameObject.activeInHierarchy)
					{
						return val4;
					}
				}
			}
			return null;
		}

		private void Build()
		{
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Expected O, but got Unknown
			//IL_0105: Unknown result type (might be due to invalid IL or missing references)
			//IL_0128: Unknown result type (might be due to invalid IL or missing references)
			//IL_013b: 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_01f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fe: Expected O, but got Unknown
			PropCatalog propCatalog = PropCatalog.Read(GeneratedData.Read("native-props.bin"));
			if (RunData.Dynamic && propCatalog.seed != RunData.Seed)
			{
				throw new Exception("Native prop seed differs from terrain");
			}
			activeCatalog = propCatalog;
			seed = propCatalog.seed;
			grassRadius = propCatalog.radius;
			grassAmount = propCatalog.amount;
			localRoot = new GameObject("PF_GeneratedNativeProps");
			localRoot.transform.SetParent(frame, false);
			PropSite[] sites = propCatalog.sites;
			foreach (PropSite propSite in sites)
			{
				if (propSite.kind == 0)
				{
					int num = ChargedGrassStyle.Variant(propCatalog.seed, plants.Count);
					variantCounts[num]++;
					GameObject val = Object.Instantiate<GameObject>(grassVariants[num], localRoot.transform);
					val.transform.localPosition = Position(propSite);
					val.transform.localRotation = Quaternion.Euler(0f, propSite.yaw, 0f);
					Transform transform = val.transform;
					transform.localScale *= propSite.scale;
					grassMaterials.Apply((Renderer)(object)val.GetComponent<MeshRenderer>(), propSite.zone);
					((Object)val).name = "PF_ChargedGrass_" + propSite.group;
					int num2 = propCatalog.seed * 173 + plants.Count * 104729;
					plants.Add(new Plant
					{
						node = val.transform,
						shared = new SharedPulse(propCatalog.seed * 397 + plants.Count * 7919, (double)propCatalog.interval, (double)propCatalog.intervalMax, SharedWorld.Elapsed),
						clock = new PlantClock(propCatalog.interval, propCatalog.intervalMax, new Random(propCatalog.seed * 397 + plants.Count * 7919)),
						ambient = new GrassAmbientArcs(localRoot.transform, val.transform, spark, num2, Time.time + (float)(plants.Count % 11) * 0.11f),
						discharge = new GrassDischargeVisual(localRoot.transform, val.transform, spark)
					});
					val.SetActive(true);
				}
			}
			message = "Generated props active";
			((BaseUnityPlugin)this).Logger.LogInfo((object)("Catalog seed=" + seed + ": arc-sedge plants=" + plants.Count + ", variants=" + string.Join(",", variantCounts) + ", poison mushrooms=" + propCatalog.sites.Count((PropSite s) => s.kind == 1) + ", luggage=" + propCatalog.sites.Count((PropSite s) => s.kind >= 2) + ". Original bomb/loot components retained."));
			ReportNow();
		}

		private static Vector3 Position(PropSite s)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			return new Vector3(s.x, s.y, s.z);
		}

		private bool LineClear(Vector3 a, Vector3 b)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			Vector3 val = b - a;
			int num = Physics.RaycastNonAlloc(a, ((Vector3)(ref val)).normalized, hits, ((Vector3)(ref val)).magnitude, -5, (QueryTriggerInteraction)1);
			if (num == hits.Length)
			{
				return false;
			}
			for (int i = 0; i < num; i++)
			{
				Collider collider = ((RaycastHit)(ref hits[i])).collider;
				if (Object.op_Implicit((Object)(object)collider) && !Object.op_Implicit((Object)(object)((Component)collider).GetComponentInParent<Character>()) && !Object.op_Implicit((Object)(object)((Component)collider).GetComponentInParent<Bodypart>()) && !Object.op_Implicit((Object)(object)((Component)collider).GetComponentInParent<Item>()))
				{
					return false;
				}
			}
			return true;
		}

		private void Clear()
		{
			SharedWorld.ModuleReady("nativeprops", false);
			activeCatalog = null;
			plants.Clear();
			Array.Clear(variantCounts, 0, variantCounts.Length);
			foreach (GameObject item in spawned)
			{
				if (Object.op_Implicit((Object)(object)item))
				{
					DeferredBombGroup component = item.GetComponent<DeferredBombGroup>();
					if (Object.op_Implicit((Object)(object)component) && (!component.SameRoom || !component.CanBelongTo(SharedWorld.RoomRun)))
					{
						component.Retire();
					}
					else if (PhotonNetwork.InRoom && Object.op_Implicit((Object)(object)item.GetComponent<PhotonView>()) && item.GetComponent<PhotonView>().IsMine)
					{
						PhotonNetwork.Destroy(item);
					}
					else
					{
						Object.Destroy((Object)(object)item);
					}
				}
			}
			spawned.Clear();
			if (Object.op_Implicit((Object)(object)localRoot))
			{
				Object.Destroy((Object)(object)localRoot);
			}
			localRoot = null;
			frame = null;
			transfers = 0;
			if (pool != null)
			{
				pool.makeCamp = null;
				pool.campReady = null;
				pool.worldParent = null;
			}
		}

		private CampfireSiteRuntime CampState()
		{
			Transform val = (Object.op_Implicit((Object)(object)frame) ? CampfireSiteRuntime.CampRoot(frame) : null);
			return Object.op_Implicit((Object)(object)val) ? ((Component)val).GetComponent<CampfireSiteRuntime>() : null;
		}

		private void ReportNow()
		{
			if (!RuntimeDiagnostics.PeriodicSnapshots || Time.unscaledTime < nextReport)
			{
				return;
			}
			nextReport = Time.unscaledTime + 2f;
			try
			{
				string text = Path.Combine(Application.persistentDataPath, "ThunderfenProps");
				Directory.CreateDirectory(text);
				Report report = new Report();
				report.amuletStatue = AmuletStatue.Status + ";" + AmuletStatue.Describe();
				report.utc = DateTime.UtcNow.ToString("O");
				report.seed = seed;
				report.revision = revision;
				report.plants = plants.Count;
				report.bombs = spawned.Where((GameObject o) => Object.op_Implicit((Object)(object)o) && Object.op_Implicit((Object)(object)o.GetComponent<TriggerRelay>())).Sum((GameObject o) => o.transform.childCount);
				report.chests = spawned.Count((GameObject o) => Object.op_Implicit((Object)(object)o) && Object.op_Implicit((Object)(object)o.GetComponent<Luggage>()));
				report.transfers = transfers;
				report.cached = templates.Keys.ToArray();
				report.modelVariants = variantCounts;
				report.pending = RunData.Pending;
				report.message = message;
				report.error = error;
				report.campLootConfiguration = CampState()?.LootConfiguration ?? new string[0];
				report.campReady = CampState()?.Complete ?? false;
				report.campBuiltSites = CampState()?.BuiltSites ?? 0;
				report.campWaiting = CampState()?.Waiting;
				report.prefabPool = ((object)PhotonNetwork.PrefabPool)?.GetType().FullName;
				report.routingReady = (object)PrefabDispatch.Handler == pool && ready;
				report.routedCreates = PrefabDispatch.Creates;
				report.routedDeletes = PrefabDispatch.Deletes;
				string contents = JsonUtility.ToJson((object)report, true);
				File.WriteAllText(Path.Combine(text, "native-props-state.json"), contents);
				if (Object.op_Implicit((Object)(object)localRoot) && Object.op_Implicit((Object)(object)frame) && ((Component)frame).gameObject.activeInHierarchy)
				{
					File.WriteAllText(Path.Combine(text, "native-props-last-active.json"), contents);
				}
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)ex.Message);
			}
		}

		private void Fail(Exception e)
		{
			error = e.ToString();
			ready = false;
			message = "Native props stopped; see diagnostic log";
			((BaseUnityPlugin)this).Logger.LogError((object)error);
			Debug.LogError((object)("Thunderfen native props failed: " + error));
			nextReport = 0f;
			ReportNow();
			Clear();
		}

		private void OnDestroy()
		{
			Release();
		}

		private void Release()
		{
			if (!released)
			{
				released = true;
				SceneManager.sceneLoaded -= Recover;
				SharedWorld.Message -= OnShared;
				Harmony obj = harmony;
				if (obj != null)
				{
					obj.UnpatchSelf();
				}
				harmony = null;
				Clear();
				pool?.ReleaseBombs();
				if ((object)PrefabDispatch.Handler == pool)
				{
					PrefabDispatch.Handler = null;
				}
				if (Object.op_Implicit((Object)(object)storage))
				{
					Object.Destroy((Object)(object)storage);
				}
				grassMaterials?.Dispose();
				if (Object.op_Implicit((Object)(object)grassBundle))
				{
					grassBundle.Unload(false);
				}
			}
		}
	}
	public sealed class OwnedNativeProp : MonoBehaviour
	{
		public static readonly HashSet<OwnedNativeProp> All = new HashSet<OwnedNativeProp>();

		public string epoch;

		public string site;

		public bool camp;

		private bool deleting;

		internal void SuppressNetworkCleanup()
		{
			deleting = true;
		}

		private void OnEnable()
		{
			All.Add(this);
		}

		private void OnDisable()
		{
			if (deleting || !Application.isPlaying || !PhotonNetwork.InRoom || !PhotonNetwork.IsMasterClient)
			{
				return;
			}
			PhotonView component = ((Component)this).GetComponent<PhotonView>();
			if (!Object.op_Implicit((Object)(object)component) || component.ViewID == 0)
			{
				return;
			}
			deleting = true;
			try
			{
				PhotonNetwork.Destroy(((Component)this).gameObject);
			}
			catch (Exception ex)
			{
				Debug.LogWarning((object)("Thunderfen network prop cleanup: " + ex.Message));
			}
		}

		private void OnDestroy()
		{
			All.Remove(this);
		}
	}
	public static class ChestLootPolicy
	{
		public static int SpotCount(Luggage c)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Invalid comparison between Unknown and I4
			if ((int)((Spawner)c).spawnPointMode == 1)
			{
				int num = 0;
				if (((Spawner)c).weightedSpawnSpots != null)
				{
					foreach (WeightedSpawnPointEntry weightedSpawnSpot in ((Spawner)c).weightedSpawnSpots)
					{
						if (weightedSpawnSpot != null && weightedSpawnSpot.spawnSpots != null && weightedSpawnSpot.weight > 0)
						{
							num = Math.Max(num, weightedSpawnSpot.spawnSpots.Count);
						}
					}
				}
				return num;
			}
			return ((Spawner)c).spawnSpots?.Count ?? 0;
		}

		public static bool Configure(Luggage chest, string sourceName = "LuggageSmall")
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Invalid comparison between Unknown and I4
			//IL_0047: 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)
			if (!Object.op_Implicit((Object)(object)chest))
			{
				throw new ArgumentNullException("chest");
			}
			if ((int)((Spawner)chest).spawnMode != 2)
			{
				return false;
			}
			((Spawner)chest).spawnPool = (SpawnPool)((sourceName == "LuggageAncient") ? 32768 : 2048);
			((Spawner)chest).spawnMode = (SpawnMode)1;
			return true;
		}
	}
	public sealed class GrassDischargeVisual
	{
		private readonly Transform parent;

		private readonly Transform source;

		private readonly Material material;

		private Func<Vector3> target;

		private double end;

		public ElectricRibbon ribbon { get; private set; }

		public Vector3[] Points { get; private set; }

		public GrassDischargeVisual(Transform parent, Transform plant, Material material)
		{
			this.parent = parent;
			source = plant;
			this.material = material;
		}

		private void EnsureRibbon()
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Expected O, but got Unknown
			//IL_0077: 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_0096: 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)
			if (!Object.op_Implicit((Object)(object)ribbon))
			{
				GameObject val = new GameObject("PF_GrassPlayerStrike");
				val.transform.SetParent(parent, false);
				ribbon = val.AddComponent<ElectricRibbon>();
				ribbon.sharedMaterial = material;
				ribbon.widthMultiplier = 0.1f;
				ribbon.startColor = new Color(0.64f, 0.72f, 1f);
				ribbon.endColor = new Color(0.94f, 0.9f, 1f);
				val.SetActive(false);
			}
		}

		public void Begin(double now, Func<Vector3> endpoint)
		{
			target = endpoint ?? throw new ArgumentNullException("endpoint");
			end = now + 0.55;
			EnsureRibbon();
			((Component)ribbon).gameObject.SetActive(true);
			Render(now);
		}

		public void Tick(double now)
		{
			if (target != null)
			{
				if (now >= end || !Object.op_Implicit((Object)(object)source))
				{
					((Component)ribbon).gameObject.SetActive(false);
					target = null;
				}
				else
				{
					Render(now);
				}
			}
		}

		private void Render(double now)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: 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_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: 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_006f: 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_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: 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_00e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
			Vector3 val = source.position + Vector3.up * 0.65f;
			Vector3 val2 = target();
			Vector3[] array = (Vector3[])(object)new Vector3[13];
			float num = (float)now * 45f;
			for (int i = 0; i < array.Length; i++)
			{
				float num2 = (float)i / (float)(array.Length - 1);
				float num3 = Mathf.Sin(num2 * MathF.PI) * 0.24f;
				array[i] = Vector3.Lerp(val, val2, num2) + new Vector3(Mathf.Sin((float)i * 15.3f + num), Mathf.Sin((float)i * 23.1f + num * 0.93f), Mathf.Cos((float)i * 19.7f + num * 0.97f)) * num3;
			}
			array[0] = val;
			array[^1] = val2;
			Points = array;
			float num4 = Mathf.Clamp01((float)((end - now) / 0.2));
			ribbon.widthMultiplier = 0.1f * num4;
			ribbon.SetPositions(array);
		}
	}
	public static class ChargedGrassStyle
	{
		public const string Id = "thunderfen-arc-sedge-v1";

		public const int Variants = 6;

		public static int Variant(int seed, int site)
		{
			uint num = (uint)(seed ^ ((site + 1) * -1640531527));
			num ^= num >> 16;
			num *= 2246822507u;
			num ^= num >> 13;
			return (int)(num % 6);
		}
	}
	public sealed class GrassSurfaceMaterials : IDisposable
	{
		public readonly Material Outdoor;

		public readonly Material Cave;

		public GrassSurfaceMaterials(Material source)
		{
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: 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_006d: Expected O, but got Unknown
			if (!Object.op_Implicit((Object)(object)source) || !source.HasProperty("_CaveWeight") || !source.HasProperty("_OutdoorFill"))
			{
				throw new InvalidOperationException("Charged grass lighting asset is out of date");
			}
			Outdoor = new Material(source)
			{
				name = "PF_ArcSedge_Outdoor"
			};
			Cave = new Material(source)
			{
				name = "PF_ArcSedge_Cave"
			};
			Outdoor.SetFloat("_CaveWeight", 0f);
			Cave.SetFloat("_CaveWeight", 1f);
		}

		public void Apply(Renderer renderer, int zone)
		{
			if (!Object.op_Implicit((Object)(object)renderer) || zone < 0 || zone > 2)
			{
				throw new ArgumentOutOfRangeException();
			}
			renderer.sharedMaterial = ((zone == 2) ? Cave : Outdoor);
		}

		private static void Release(Object value)
		{
			if (Object.op_Implicit(value))
			{
				if (Application.isPlaying)
				{
					Object.Destroy(value);
				}
				else
				{
					Object.DestroyImmediate(value);
				}
			}
		}

		public void Dispose()
		{
			Release((Object)(object)Outdoor);
			Release((Object)(object)Cave);
		}
	}
	public sealed class CampfireSiteRuntime : MonoBehaviour
	{
		public static readonly string[] Extra = new string[4] { "Campfire", "CampfireFoodSpawner", "PF_RespawnStatue", "PF_BackpackSpawner" };

		private readonly List<GameObject> owned = new List<GameObject>();

		private List<SpawnedItemTracker> registry;

		private CampBuildPlan plan;

		private bool visualReady;

		private float nextAttempt;

		private string lastWaiting;

		private static readonly BindingFlags Fields = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;

		public bool Complete { get; private set; }

		public int BuiltSites => plan?.Built ?? 0;

		public string Waiting { get; private set; }

		public string[] LootConfiguration => (from c in ((Component)this).GetComponentsInChildren<Luggage>(true)
			where Object.op_Implicit((Object)(object)c) && ((Object)c).name.StartsWith("PF_Camp_3_", StringComparison.Ordinal)
			select ((Object)c).name + "|mode=" + ((object)Unsafe.As<SpawnMode, SpawnMode>(ref ((Spawner)c).spawnMode)/*cast due to .constrained prefix*/).ToString() + "|pool=" + ((object)Unsafe.As<SpawnPool, SpawnPool>(ref ((Spawner)c).spawnPool)/*cast due to .constrained prefix*/).ToString()).ToArray();

		public static Transform CampRoot(Transform frame)
		{
			Transform val = frame;
			while (Object.op_Implicit((Object)(object)val))
			{
				Transform val2 = val.Find("CampfireRoot");
				if (Object.op_Implicit((Object)(object)val2))
				{
					return val2;
				}
				val = val.parent;
			}
			return null;
		}

		public static string Prefab(CampSite s)
		{
			return (s.kind == 0) ? "BakedThunderfenTree" : ((s.kind == 1) ? "CampfireFoodSpawner" : ((s.kind == 2) ? "PF_RespawnStatue" : ((s.kind == 4) ? "PF_BackpackSpawner" : NativePropsTrial.PrefabName(s.model + 2))));
		}

		public static bool TryBuild(Transform frame, PropCatalog catalog, Dictionary<string, GameObject> templates)
		{
			if (catalog.camp.Length == 0)
			{
				return true;
			}
			Transform val = CampRoot(frame);
			if (!Object.op_Implicit((Object)(object)val))
			{
				return false;
			}
			CampfireSiteRuntime campfireSiteRuntime = ((Component)val).GetComponent<CampfireSiteRuntime>();
			if (!Object.op_Implicit((Object)(object)campfireSiteRuntime))
			{
				campfireSiteRuntime = ((Component)val).gameObject.AddComponent<CampfireSiteRuntime>();
			}
			Transform val2 = val.Find("RetainedHybridSummit/PF_RetainedSummitWall");
			if (Object.op_Implicit((Object)(object)val2))
			{
				Transform val3 = frame;
				while (Object.op_Implicit((Object)(object)val3) && ((Object)val3).name != "FloorRoot")
				{
					val3 = val3.parent;
				}
				RetainedSummitWall retainedSummitWall = ((Component)val).GetComponent<RetainedSummitWall>();
				if (!Object.op_Implicit((Object)(object)retainedSummitWall))
				{
					retainedSummitWall = ((Component)val).gameObject.AddComponent<RetainedSummitWall>();
				}
				retainedSummitWall.Configure(val3, val2);
			}
			if (campfireSiteRuntime.Complete && campfireSiteRuntime.plan != null && campfireSiteRuntime.plan.Complete(PhotonNetwork.CurrentRoom.PlayerCount))
			{
				return true;
			}
			if (Time.unscaledTime < campfireSiteRuntime.nextAttempt)
			{
				return false;
			}
			campfireSiteRuntime.nextAttempt = Time.unscaledTime + 1f;
			campfireSiteRuntime.Build(frame, catalog, templates);
			return campfireSiteRuntime.Complete;
		}

		public static GameObject CreateSite(Transform frame, PropCatalog catalog, int index, int segment, Dictionary<string, GameObject> templates)
		{
			CampSite campSite = Site(catalog, index);
			Transform val = CampRoot(frame);
			if (!Object.op_Implicit((Object)(object)val))
			{
				throw new Exception("Native camp root not ready");
			}
			GameObject val2 = NewNode(campSite.kind, Prefab(campSite), index, templates);
			Configure(val2, campSite, segment, val, templates, keepWorldPose: false);
			return val2;
		}

		private static CampSite Site(PropCatalog catalog, int index)
		{
			if (index < 0 || index >= catalog.camp.Length)
			{
				throw new Exception("Invalid shared camp site");
			}
			CampSite campSite = catalog.camp[index];
			if (campSite.kind == 0)
			{
				throw new Exception("Baked trees must not be network-spawned");
			}
			return campSite;
		}

		public static int KindOf(string prefab)
		{
			int result;
			switch (prefab)
			{
			default:
				if (prefab.StartsWith("Luggage", StringComparison.Ordinal))
				{
					result = 3;
					break;
				}
				goto case null;
			case null:
				result = -1;
				break;
			case "PF_BackpackSpawner":
				result = 4;
				break;
			case "PF_RespawnStatue":
				result = 2;
				break;
			case "CampfireFoodSpawner":
				result = 1;
				break;
			}
			return result;
		}

		public static GameObject NewNode(int kind, string prefab, int index, Dictionary<string, GameObject> templates)
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Expected O, but got Unknown
			GameObject val;
			if (kind == 4)
			{
				val = new GameObject("PF_Camp_" + kind + "_" + index);
				val.SetActive(false);
				val.AddComponent<PhotonView>();
			}
			else
			{
				if (!templates.TryGetValue(prefab, out var value))
				{
					throw new Exception("Camp template not cached: " + prefab);
				}
				val = Object.Instantiate<GameObject>(value);
				val.SetActive(false);
				((Object)val).name = "PF_Camp_" + kind + "_" + index;
			}
			return val;
		}

		private static void Configure(GameObject node, CampSite s, int segment, Transform camp, Dictionary<string, GameObject> templates, bool keepWorldPose)
		{
			if (s.kind == 4)
			{
				NativeCampSetup.Backpack(node, templates[Prefab(s)].GetComponent<SingleItemSpawner>());
			}
			if (s.kind == 1)
			{
				NativeCampSetup.Food(node, s.requirement);
			}
			if (s.kind == 3)
			{
				ChestLootPolicy.Configure(node.GetComponent<Luggage>(), Prefab(s));
			}
			node.transform.SetParent(camp, keepWorldPose);
			NativeCampSetup.Track(node, NativeCampSetup.Registry());
			if (s.kind == 2)
			{
				RespawnChest componentInChildren = node.GetComponentInChildren<RespawnChest>(true);
				if (!Object.op_Implicit((Object)(object)componentInChildren))
				{
					throw new Exception("Native statue behavior missing");
				}
				PropertyInfo property = typeof(RespawnChest).GetProperty("SegmentNumber", Fields);
				property.SetValue(componentInChildren, Enum.ToObject(property.PropertyType, segment), null);
				node.AddComponent<CampStatuePalette>().Apply(camp);
			}
		}

		public static int CompleteDeferred(Transform frame, PropCatalog catalog, Dictionary<string, GameObject> templates)
		{
			Transform val = CampRoot(frame);
			if (!Object.op_Implicit((Object)(object)val) || catalog == null)
			{
				return 0;
			}
			int num = 0;
			DeferredCampSite[] array = DeferredCampSite.All.ToArray();
			foreach (DeferredCampSite deferredCampSite in array)
			{
				if (!Object.op_Implicit((Object)(object)deferredCampSite))
				{
					DeferredCampSite.All.Remove(deferredCampSite);
					continue;
				}
				CampSite s = Site(catalog, deferredCampSite.index);
				if (Prefab(s) != deferredCampSite.prefab)
				{
					throw new Exception("Deferred camp site " + deferredCampSite.index + " does not match this map");
				}
				Configure(((Component)deferredCampSite).gameObject, s, deferredCampSite.segment, val, templates, keepWorldPose: true);
				OwnedNativeProp component = ((Component)deferredCampSite).GetComponent<OwnedNativeProp>();
				if (Object.op_Implicit((Object)(object)component))
				{
					component.epoch = SharedWorld.Epoch;
				}
				DeferredCampSite.All.Remove(deferredCampSite);
				Object.Destroy((Object)(object)deferredCampSite);
				num++;
			}
			return num;
		}

		private void Build(Transform frame, PropCatalog catalog, Dictionary<string, GameObject> templates)
		{
			//IL_0092: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Expected O, but got Unknown
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: 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: Expected O, but got Unknown
			//IL_021e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0223: Unknown result type (might be due to invalid IL or missing references)
			//IL_0228: Unknown result type (might be due to invalid IL or missing references)
			//IL_022b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0230: Unknown result type (might be due to invalid IL or missing references)
			//IL_024a: 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_0254: Unknown result type (might be due to invalid IL or missing references)
			//IL_026a: Unknown result type (might be due to invalid IL or missing references)
			//IL_026f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0274: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e3: Unknown result type (might be due to invalid IL or missing references)
			if (plan == null)
			{
				plan = new CampBuildPlan(catalog.camp);
				registry = NativeCampSetup.Registry();
			}
			int players = PhotonNetwork.CurrentRoom.PlayerCount;
			if (!visualReady && templates.TryGetValue("Campfire", out var value))
			{
				Campfire componentInChildren = ((Component)this).GetComponentInChildren<Campfire>(true);
				if (Object.op_Implicit((Object)(object)componentInChildren))
				{
					NativeCampfirePresentation.Install((Component)(object)componentInChildren, (Component)(object)value.GetComponent<Campfire>());
					Campfire_Set_Segment val = new Campfire_Set_Segment();
					val.Segment = componentInChildren.advanceToSegment;
					((PropSpawnerMod)val).ModifyObject(((Component)componentInChildren).gameObject, new SpawnData());
					visualReady = true;
				}
			}
			bool flag = false;
			int[] array = plan.Pending(players, (CampSite s) => s.kind == 0 || templates.ContainsKey(Prefab(s)));
			for (int num = 0; num < array.Length; num++)
			{
				int num2 = array[num];
				CampSite campSite = catalog.camp[num2];
				if (campSite.kind == 0)
				{
					if (!Object.op_Implicit((Object)(object)((Component)this).transform.Find("PF_CampTrees/PF_CampTree_" + num2)))
					{
						throw new Exception("Generated Thunderfen camp tree missing");
					}
					plan.Commit(num2);
					continue;
				}
				Transform val2 = ((Component)this).transform.Find("PF_Camp_" + campSite.kind + "_" + num2);
				if (Object.op_Implicit((Object)(object)val2) || SharedWorld.SiteClaimed("camp:" + num2))
				{
					plan.Commit(num2);
				}
				else if (PhotonNetwork.IsMasterClient && SharedWorld.ClaimSite("camp:" + num2))
				{
					Vector3 val3 = frame.TransformPoint(new Vector3(campSite.x, campSite.y, campSite.z));
					Quaternion val4 = frame.rotation * Quaternion.FromToRotation(Vector3.up, new Vector3(campSite.nx, campSite.ny, campSite.nz)) * Quaternion.Euler(0f, campSite.yaw, 0f);
					int num3 = (int)typeof(MapHandler).GetField("currentSegment", Fields).GetValue(Singleton<MapHandler>.Instance);
					GameObject item = PhotonNetwork.InstantiateRoomObject("PFNativeProps/Camp/" + num2 + "/" + num3 + "/" + Prefab(campSite), val3, val4, (byte)0, (object[])null);
					owned.Add(item);
					plan.Commit(num2);
					flag = true;
				}
			}
			if (flag && PhotonNetwork.IsMasterClient)
			{
				NativeCampSetup.Populate(((Component)this).gameObject);
			}
			Waiting = string.Join(",", (from n in catalog.camp.Where((CampSite s) => s.kind != 0 && (s.kind != 1 || s.requirement <= players)).Select(Prefab)
				where !templates.ContainsKey(n)
				select n).Concat(visualReady ? new string[0] : new string[1] { "Campfire presentation" }).Distinct());
			Complete = visualReady && plan.Complete(players);
			if (Waiting != lastWaiting)
			{
				lastWaiting = Waiting;
				Debug.Log((object)("Thunderfen native camp progress: " + plan.Built + " sites; " + (Complete ? "complete" : ("waiting only for " + Waiting))));
			}
		}

		private void OnDestroy()
		{
			foreach (GameObject item2 in owned)
			{
				if (!Object.op_Implicit((Object)(object)item2))
				{
					continue;
				}
				if (registry != null)
				{
					SpawnedItemTracker[] componentsInChildren = item2.GetComponentsInChildren<SpawnedItemTracker>(true);
					foreach (SpawnedItemTracker item in componentsInChildren)
					{
						registry.Remove(item);
					}
				}
				PhotonView component = item2.GetComponent<PhotonView>();
				if (PhotonNetwork.InRoom && Object.op_Implicit((Object)(object)component) && component.IsMine)
				{
					PhotonNetwork.Destroy(item2);
				}
				else
				{
					Object.Destroy((Object)(object)item2);
				}
			}
			owned.Clear();
		}
	}
	public sealed class DeferredCampSite : MonoBehaviour
	{
		public static readonly HashSet<DeferredCampSite> All = new HashSet<DeferredCampSite>();

		private static Transform holder;

		public int index;

		public int segment;

		public string prefab;

		public static GameObject Create(string prefab, int index, int segment, Dictionary<string, GameObject> templates)
		{
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Expected O, but got Unknown
			int num = CampfireSiteRuntime.KindOf(prefab);
			if (num < 1)
			{
				throw new Exception("Unknown camp site prefab: " + prefab);
			}
			if (!Object.op_Implicit((Object)(object)holder))
			{
				GameObject val = new GameObject("PF_DeferredCampSites");
				val.SetActive(false);
				holder = val.transform;
			}
			GameObject val2 = CampfireSiteRuntime.NewNode(num, prefab, index, templates);
			val2.transform.SetParent(holder, false);
			DeferredCampSite deferredCampSite = val2.AddComponent<DeferredCampSite>();
			deferredCampSite.index = index;
			deferredCampSite.segment = segment;
			deferredCampSite.prefab = prefab;
			All.Add(deferredCampSite);
			Debug.Log((object)("Thunderfen camp site " + index + " (" + prefab + ") arrived before the map was ready; it will be set up once the map is ready."));
			return val2;
		}

		private void OnDestroy()
		{
			All.Remove(this);
		}
	}
	public static class NativeCampfirePresentation
	{
		private const BindingFlags Flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;

		private static T Get<T>(Component c, string name)
		{
			return (T)((object)c).GetType().GetField(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).GetValue(c);
		}

		private static void Set(Component c, string name, object value)
		{
			FieldInfo field = ((object)c).GetType().GetField(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			if (field == null)
			{
				throw new MissingFieldException(((object)c).GetType().Name, name);
			}
			field.SetValue(c, value);
		}

		private static string Relative(Transform p, Transform root)
		{
			List<string> list = new List<string>();
			while (Object.op_Implicit((Object)(object)p) && (Object)(object)p != (Object)(object)root)
			{
				list.Add(((Object)p).name);
				p = p.parent;
			}
			if ((Object)(object)p != (Object)(object)root)
			{
				throw new Exception("Native fire reference leaves its prefab");
			}
			list.Reverse();
			return string.Join("/", list);
		}

		public static GameObject Install(Component target, Component source)
		{
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Expected O, but got Unknown
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Expected O, but got Unknown
			//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f4: Expected O, but got Unknown
			//IL_03dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_03e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_03e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_03eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0400: Unknown result type (might be due to invalid IL or missing references)
			//IL_0405: Unknown result type (might be due to invalid IL or missing references)
			//IL_0409: Unknown result type (might be due to invalid IL or missing references)
			//IL_040e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0424: Unknown result type (might be due to invalid IL or missing references)
			if (!Object.op_Implicit((Object)(object)target) || !Object.op_Implicit((Object)(object)source) || !Object.op_Implicit((Object)(object)Get<Transform>(source, "logRoot")))
			{
				throw new Exception("Native campfire presentation is incomplete");
			}
			foreach (Transform item in target.transform)
			{
				Transform val = item;
				((Component)val).gameObject.SetActive(false);
			}
			GameObject visuals = new GameObject("PF_NativeCampfireVisuals");
			visuals.SetActive(false);
			visuals.transform.SetParent(target.transform, false);
			foreach (Transform item2 in source.transform)
			{
				Transform val2 = item2;
				GameObject val3 = Object.Instantiate<GameObject>(((Component)val2).gameObject, visuals.transform, false);
				((Object)val3).name = ((Object)val2).name;
				MonoBehaviour[] componentsInChildren = val3.GetComponentsInChildren<MonoBehaviour>(true);
				foreach (MonoBehaviour val4 in componentsInChildren)
				{
					Object.DestroyImmediate((Object)(object)val4);
				}
			}
			Func<Component, Transform> func = (Component c) => visuals.transform.Find(Relative(c.transform, source.transform));
			Set(target, "logRoot", func((Component)(object)Get<Transform>(source, "logRoot")));
			string[] array = new string[3] { "fireParticles", "smokeParticlesOff", "smokeParticlesLit" };
			foreach (string text in array)
			{
				ParticleSystem val5 = Get<ParticleSystem>(source, text);
				if (!Object.op_Implicit((Object)(object)val5))
				{
					throw new Exception("Native campfire particle reference missing: " + text);
				}
				Set(target, text, ((Component)func((Component)(object)val5)).GetComponent<ParticleSystem>());
			}
			string[] array2 = new string[2] { "enableWhenLit", "disableWhenLit" };
			foreach (string name in array2)
			{
				GameObject val6 = Get<GameObject>(source, name);
				Set(target, name, Object.op_Implicit((Object)(object)val6) ? ((Component)func((Component)(object)val6.transform)).gameObject : null);
			}
			string[] array3 = new string[11]
			{
				"endSize", "endRot", "burnsFor", "cookTime", "moraleBoostRadius", "moraleBoostBaseline", "moraleBoostPerAdditionalScout", "injuryReduction", "fireStart", "extinguish",
				"moraleBoost"
			};
			foreach (string name2 in array3)
			{
				Set(target, name2, Get<object>(source, name2));
			}
			AudioSource val7 = Get<AudioSource>(source, "loop");
			if (Object.op_Implicit((Object)(object)val7))
			{
				AudioSource val8 = visuals.AddComponent<AudioSource>();
				val8.clip = val7.clip;
				val8.loop = val7.loop;
				val8.spatialBlend = val7.spatialBlend;
				val8.volume = val7.volume;
				val8.minDistance = val7.minDistance;
				val8.maxDistance = val7.maxDistance;
				Set(target, "loop", val8);
			}
			Set(target, "mainRenderer", visuals.GetComponentsInChildren<MeshRenderer>(true).FirstOrDefault());
			ParticleSystem val9 = Get<ParticleSystem>(target, "fireParticles");
			EmissionModule emission = val9.emission;
			MinMaxCurve rateOverTime = ((EmissionModule)(ref emission)).rateOverTime;
			Set(target, "startRot", ((MinMaxCurve)(ref rateOverTime)).constant);
			MainModule main = val9.main;
			MinMaxCurve startSize = ((MainModule)(ref main)).startSize;
			Set(target, "startSize", (object)new Vector2(((MinMaxCurve)(ref startSize)).constantMin, ((MinMaxCurve)(ref startSize)).constantMax));
			visuals.SetActive(true);
			bool flag = (bool)((object)target).GetType().GetProperty("Lit", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).GetValue(target, null);
			GameObject val10 = Get<GameObject>(target, "enableWhenLit");
			GameObject val11 = Get<GameObject>(target, "disableWhenLit");
			if (Object.op_Implicit((Object)(object)val10))
			{
				val10.SetActive(flag);
			}
			if (Object.op_Implicit((Object)(object)val11))
			{
				val11.SetActive(!flag);
			}
			return visuals;
		}
	}
	public sealed class CampBuildPlan
	{
		private readonly CampSite[] sites;

		private readonly bool[] done;

		public int Built => done.Count((bool x) => x);

		public CampBuildPlan(CampSite[] sites)
		{
			this.sites = sites ?? throw new ArgumentNullException();
			done = new bool[sites.Length];
		}

		public int[] Pending(int players, Func<CampSite, bool> available)
		{
			return (from i in Enumerable.Range(0, sites.Length)
				where !done[i] && (sites[i].kind != 1 || sites[i].requirement <= players) && available(sites[i])
				select i).ToArray();
		}

		public bool Complete(int players)
		{
			return Enumerable.Range(0, sites.Length).All((int i) => done[i] || (sites[i].kind == 1 && sites[i].requirement > players));
		}

		public void Commit(int site)
		{
			if (site < 0 || site >= done.Length || done[site])
			{
				throw new InvalidOperationException("Camp site already created or invalid");
			}
			done[site] = true;
		}
	}
	public static class NativeCampSetup
	{
		private const BindingFlags Flags = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;

		private static readonly PropertyInfo Trackers = typeof(MapHandler).GetProperty("SpawnTrackers", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);

		private static readonly MethodInfo SpawnPass = typeof(MapHandler).GetMethod("SpawnCampfireItems", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);

		public static List<SpawnedItemTracker> Registry()
		{
			return (List<SpawnedItemTracker>)Trackers.GetValue(null, null);
		}

		public static void Track(GameObject root, List<SpawnedItemTracker> registry)
		{
			MonoBehaviour[] array = (from c in root.GetComponentsInChildren<MonoBehaviour>(true)
				where c is ISpawner
				select c).ToArray();
			foreach (MonoBehaviour val in array)
			{
				SpawnedItemTracker val2 = ((Component)val).GetComponent<SpawnedItemTracker>();
				if (!Object.op_Implicit((Object)(object)val2))
				{
					val2 = ((Component)val).gameObject.AddComponent<SpawnedItemTracker>();
					val2.Init();
				}
				if (!registry.Contains(val2))
				{
					registry.Add(val2);
				}
			}
		}

		public static void Food(GameObject node, int slot)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Expected O, but got Unknown
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Expected O, but got Unknown
			//IL_0048: 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_0079: 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_0097: Unknown result type (might be due to invalid IL or missing references)
			BerryBush component = node.GetComponent<BerryBush>();
			if (!Object.op_Implicit((Object)(object)component))
			{
				throw new Exception("Native camp food behavior missing");
			}
			PSM_SetSpawnerPlayerCountRequirement val = new PSM_SetSpawnerPlayerCountRequirement();
			val.onePerPlayer = true;
			((PropSpawnerMod)val).ModifyObject(node, new SpawnData
			{
				spawnCount = slot - 1
			});
			Transform transform = new GameObject("NativeFoodAnchor").transform;
			transform.SetParent(node.transform, false);
			transform.localPosition = Vector3.up * 0.12f;
			((Spawner)component).spawnPointMode = (SpawnPointMode)0;
			((Spawner)component).spawnSpots = new List<Transform> { transform };
			if (component.possibleBerries != Vector2.one)
			{
				throw new Exception("Native camp food quantity changed; review required");
			}
			node.AddComponent<CampItemSpawnGuard>();
		}

		public static void Backpack(GameObject node, SingleItemSpawner source)
		{
			SingleItemSpawner val = node.AddComponent<SingleItemSpawner>();
			val.prefab = source.prefab;
			val.isKinematic = source.isKinematic;
			val.playersInRoomRequirement = source.playersInRoomRequirement;
			val.belowAscentRequirement = source.belowAscentRequirement;
			node.AddComponent<CampItemSpawnGuard>();
		}

		public static void Populate(GameObject camp)
		{
			SpawnPass.Invoke(null, new object[2] { camp, false });
		}
	}
	public sealed class CampItemSpawnGuard : MonoBehaviour
	{
		public bool completed;

		public List<PhotonView> result;
	}
	[HarmonyPatch(typeof(Spawner), "TrySpawnItems", new Type[] { })]
	public static class CampFoodOnce
	{
		public static bool Prefix(Component __instance, ref List<PhotonView> __result)
		{
			CampItemSpawnGuard component = __instance.GetComponent<CampItemSpawnGuard>();
			if (!Object.op_Implicit((Object)(object)component) || !component.completed)
			{
				return true;
			}
			__result = component.result?.Where((PhotonView x) => Object.op_Implicit((Object)(object)x)).ToList() ?? new List<PhotonView>();
			return false;
		}

		public static void Postfix(Component __instance, List<PhotonView> __result)
		{
			CampItemSpawnGuard component = __instance.GetComponent<CampItemSpawnGuard>();
			if (Object.op_Implicit((Object)(object)component) && !component.completed && __result != null && __result.Count > 0)
			{
				component.completed = true;
				component.result = __result;
			}
		}
	}
	[HarmonyPatch(typeof(SingleItemSpawner), "TrySpawnItems", new Type[] { })]
	public static class CampBackpackOnce
	{
		public static bool Prefix(Component __instance, ref List<PhotonView> __result)
		{
			return CampFoodOnce.Prefix(__instance, ref __result);
		}

		public static void Postfix(Component __instance, List<PhotonView> __result)
		{
			CampFoodOnce.Postfix(__instance, __result);
		}
	}
	public sealed class CampStatuePalette : MonoBehaviour
	{
		private readonly List<Material> owned = new List<Material>();

		public void Apply(Transform camp)
		{
			//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f1: Expected O, but got Unknown
			//IL_0144: Unknown result type (might be due to invalid IL or missing references)
			//IL_014b: Expected O, but got Unknown
			//IL_015d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0167: Expected O, but got Unknown
			//IL_012b: Unknown result type (might be due to invalid IL or missing references)
			Material val = ((Component)camp.Find("RetainedHybridSummit")).GetComponentsInChildren<MeshRenderer>(true).SelectMany((MeshRenderer r) => ((Renderer)r).sharedMaterials).FirstOrDefault((Func<Material, bool>)((Material m) => Object.op_Implicit((Object)(object)m) && m.HasProperty("_TopColor")));
			if (!Object.op_Implicit((Object)(object)val))
			{
				throw new Exception("Native summit rock material unavailable");
			}
			MeshRenderer[] componentsInChildren = ((Component)this).GetComponentsInChildren<MeshRenderer>(true);
			foreach (MeshRenderer val2 in componentsInChildren)
			{
				Material sharedMaterial = ((Renderer)val2).sharedMaterial;
				if (!Object.op_Implicit((Object)(object)sharedMaterial))
				{
					continue;
				}
				bool flag = ((Object)val2).name == "Fake Ground Plane";
				if (flag || ((Object)sharedMaterial).name.StartsWith("M_Rock", StringComparison.Ordinal))
				{
					Material val3 = new Material(flag ? val : sharedMaterial);
					((Object)val3).name = "Thunderfen camp stone (owned)";
					if (val3.HasProperty("_TopColor"))
					{
						val3.SetColor("_TopColor", new Color(0.62f, 0.4f, 0.76f, 1f));
					}
					owned.Add(val3);
					PSM_SetMaterial val4 = new PSM_SetMaterial();
					val4.mat = val3;
					((PropSpawnerMod)val4).ModifyObject(((Component)val2).gameObject, new SpawnData());
				}
			}
		}

		private void OnDestroy()
		{
			foreach (Material item in owned)
			{
				if (Object.op_Implicit((Object)(object)item))
				{
					Object.Destroy((Object)(object)item);
				}
			}
		}
	}
	public sealed class RetainedSummitWall : MonoBehaviour
	{
		private Transform floor;

		private Transform wall;

		private Transform cap;

		private Renderer[] visuals;

		private Collider[] solids;

		private bool configured;

		private bool shown;

		public bool Shown => configured && shown;

		public void Configure(Transform sourceFloor, Transform body)
		{
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Expected O, but got Unknown
			if (configured || !Object.op_Implicit((Object)(object)body))
			{
				return;
			}
			floor = sourceFloor;
			wall = body;
			foreach (Transform item in body.parent)
			{
				Transform val = item;
				if (((Object)val).name.StartsWith("PF_Summit_WallTop_", StringComparison.Ordinal))
				{
					cap = val;
				}
			}
			visuals = ((Component)body).GetComponentsInChildren<Renderer>(true);
			solids = ((Component)body).GetComponentsInChildren<Collider>(true);
			configured = true;
			Apply(!Object.op_Implicit((Object)(object)floor) || !((Component)floor).gameObject.activeInHierarchy);
		}

		public void Refresh()
		{
			if (configured)
			{
				Apply(!Object.op_Implicit((Object)(object)floor) || !((Component)floor).gameObject.activeInHierarchy);
			}
		}

		private void Update()
		{
			Refresh();
		}

		private void Apply(bool value)
		{
			if (Object.op_Implicit((Object)(object)cap) && ((Component)cap).gameObject.activeSelf == value)
			{
				((Component)cap).gameObject.SetActive(!value);
			}
			if (Object.op_Implicit((Object)(object)wall) && ((Component)wall).gameObject.activeSelf != value)
			{
				((Component)wall).gameObject.SetActive(value);
			}
			Renderer[] array = visuals;
			foreach (Renderer val in array)
			{
				if (Object.op_Implicit((Object)(object)val))
				{
					val.enabled = value;
				}
			}
			Collider[] array2 = solids;
			foreach (Collider val2 in array2)
			{
				if (Object.op_Implicit((Object)(object)val2))
				{
					val2.enabled = value;
				}
			}
			if (shown != value)
			{
				shown = value;
				Debug.Log((object)("Thunderfen retained summit wall " + (value ? "revealed after floor unload" : "hidden during climb")));
			}
		}
	}
	public static class PrefabDispatch
	{
		public static IPunPrefabPool Handler;

		private static readonly Dictionary<string, IPunPrefabPool> extensions = new Dictionary<string, IPunPrefabPool>(StringComparer.Ordinal);

		public static int Creates;

		public static int Deletes;

		public static void RegisterExtension(string prefix, IPunPrefabPool factory)
		{
			if (string.IsNullOrEmpty(prefix) || !prefix.StartsWith("0_Items/TFItems/", StringComparison.Ordinal))
			{
				throw new ArgumentException("Reserved Thunderfen item prefix required");
			}
			if (factory == null)
			{
				extensions.Remove(prefix);
			}
			else
			{
				extensions[prefix] = factory;
			}
		}

		public static GameObject Instantiate(IPunPrefabPool current, string id, Vector3 position, Quaternion rotation)
		{
			//IL_013a: Unknown result type (might be due to invalid IL or missing references)
			//IL_013b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fc: 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_0040: 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)
			if (id != null)
			{
				foreach (KeyValuePair<string, IPunPrefabPool> extension in extensions)
				{
					if (id.StartsWith(extension.Key, StringComparison.Ordinal))
					{
						GameObject val = extension.Value.Instantiate(id, position, rotation);
						if (!Object.op_Implicit((Object)(object)val))
						{
							throw new InvalidOperationException("Thunderfen item factory returned no object: " + id);
						}
						RoutedNativeItem routedNativeItem = val.GetComponent<RoutedNativeItem>() ?? val.AddComponent<RoutedNativeItem>();
						routedNativeItem.prefix = extension.Key;
						Creates++;
						return val;
					}
				}
			}
			if (id != null && id.StartsWith("PFNativeProps/", StringComparison.Ordinal))
			{
				if (Handler == null)
				{
					throw new InvalidOperationException("Thunderfen native prefab factory is not initialized: " + id);
				}
				GameObject val2 = Handler.Instantiate(id, position, rotation);
				if (!Object.op_Implicit((Object)(object)val2))
				{
					throw new InvalidOperationException("Thunderfen native prefab factory returned no object: " + id);
				}
				Creates++;
				return val2;
			}
			return current.Instantiate(id, position, rotation);
		}

		public static void Destroy(IPunPrefabPool current, GameObject obj)
		{
			RoutedNativeItem routedNativeItem = (Object.op_Implicit((Object)(object)obj) ? obj.GetComponent<RoutedNativeItem>() : null);
			if (Object.op_Implicit((Object)(object)routedNativeItem))
			{
				if (extensions.TryGetValue(routedNativeItem.prefix, out var value))
				{
					value.Destroy(obj);
				}
				else
				{
					Object.Destroy((Object)(object)obj);
				}
				Deletes++;
			}
			else if (Object.op_Implicit((Object)(object)obj) && Object.op_Implicit((Object)(object)obj.GetComponent<OwnedNativeProp>()))
			{
				if (Handler == null)
				{
					throw new InvalidOperationException("Thunderfen native prefab factory is not initialized for destruction");
				}
				Handler.Destroy(obj);
				Deletes++;
			}
			else
			{
				current.Destroy(obj);
			}
		}
	}
	public sealed class RoutedNativeItem : MonoBehaviour
	{
		public string prefix;
	}
	[HarmonyPatch]
	public static class NativePrefabRouting
	{
		public static IEnumerable<MethodBase> TargetMethods()
		{
			yield return ExactMethod("NetworkInstantiate", new string[3] { "Photon.Pun.InstantiateParameters", "System.Boolean", "System.Boolean" });
			yield return ExactMethod("RemoveInstantiatedGO", new string[2] { "UnityEngine.GameObject", "System.Boolean" });
		}

		private static MethodInfo ExactMethod(string name, string[] parameters)
		{
			MethodInfo[] array = (from m in typeof(PhotonNetwork).GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)
				where m.Name == name && (from p in m.GetParameters()
					select p.ParameterType.FullName).SequenceEqual<string>(parameters)
				select m).ToArray();
			if (array.Length != 1)
			{
				throw new MissingMethodException("Expected one exact PUN " + name + " overload; found " + array.Length);
			}
			return array[0];
		}

		public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions, MethodBase original)
		{
			string text = ((original.Name == "NetworkInstantiate") ? "Instantiate" : "Destroy");
			MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(IPunPrefabPool), text, (Type[])null, (Type[])null);
			MethodInfo operand = AccessTools.DeclaredMethod(typeof(PrefabDispatch), text, (Type[])null, (Type[])null);
			List<CodeInstruction> list = new List<CodeInstruction>();
			int num = 0;
			foreach (CodeInstruction instruction in instructions)
			{
				if (CodeInstructionExtensions.Calls(instruction, methodInfo))
				{
					instruction.opcode = OpCodes.Call;
					instruction.operand = operand;
					num++;
				}
				list.Add(instruction);
			}
			if (num != 1)
			{
				throw new InvalidOperationException("PUN prefab routing changed: " + original.Name + " has " + num + " factory calls; expected one");
			}
			return list;
		}
	}
	public sealed class AmuletStatueSite
	{
		public int seed;

		public int index;

		public Vector3 position;

		public Vector3 normal;

		public float yaw;

		public float radius;

		public static AmuletStatueSite Read(byte[] bytes)
		{
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_00ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			using BinaryReader binaryReader = new BinaryReader(new MemoryStream(bytes));
			if (bytes.Length != 48 || binaryReader.ReadInt32() != 1396786772 || binaryReader.ReadInt32() != 1)
			{
				throw new InvalidDataException("Amulet statue catalog signature");
			}
			AmuletStatueSite amuletStatueSite = new AmuletStatueSite
			{
				seed = binaryReader.ReadInt32(),
				index = binaryReader.ReadInt32(),
				position = new Vector3(binaryReader.ReadSingle(), binaryReader.ReadSingle(), binaryReader.ReadSingle()),
				normal = new Vector3(binaryReader.ReadSingle(), binaryReader.ReadSingle(), binaryReader.ReadSingle()),
				yaw = binaryReader.ReadSingle(),
				radius = binaryReader.ReadSingle()
			};
			if (amuletStatueSite.index != 2 || !Finite(amuletStatueSite.position) || !Finite(amuletStatueSite.normal) || !PropCatalog.Finite(amuletStatueSite.yaw) || !PropCatalog.Finite(amuletStatueSite.radius) || amuletStatueSite.radius < 0.5f || amuletStatueSite.radius > 3f || amuletStatueSite.normal.y < 0.8f || Mathf.Abs(((Vector3)(ref amuletStatueSite.normal)).sqrMagnitude - 1f) > 0.01f)
			{
				throw new InvalidDataException("Invalid amulet statue site");
			}
			return amuletStatueSite;
		}

		private static bool Finite(Vector3 p)
		{
			//IL_0000: 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_001a: Unknown result type (might be due to invalid IL or missing references)
			return PropCatalog.Finite(p.x) && PropCatalog.Finite(p.y) && PropCatalog.Finite(p.z);
		}
	}
	public sealed class ThunderfenAmuletStatue : MonoBehaviour
	{
		public int seed;

		public int routeIndex;

		public int amuletType;

		public FakeItem item;
	}
	[HarmonyPatch(typeof(FakeItemManager), "RefreshList", new Type[] { })]
	public static class AmuletStatue
	{
		public const int StableIndex = 62100;

		private const string Name = "TF_NativeAmuletStatue";

		private static readonly MethodInfo Select = AccessTools.Method(typeof(PropSpawner_AmuletStatues), "GetPropToSpawn", Type.EmptyTypes, (Type[])null);

		public static string Status = "waiting for published custom root";

		private static GameObject[] variants;

		public static string Describe()
		{
			return string.Join(";", from s in Object.FindObjectsByType<ThunderfenAmuletStatue>((FindObjectsInactive)1, (FindObjectsSortMode)0)
				select "seed=" + s.seed + " route=" + s.routeIndex + " type=" + s.amuletType + " fakeIndex=" + (Object.op_Implicit((Object)(object)s.item) ? s.item.index : (-1)) + " active=" + ((Component)s).gameObject.activeInHierarchy + " picked=" + (Object.op_Implicit((Object)(object)s.item) && s.item.pickedUp));
		}

		private static bool UnderGlobal(Transform t)
		{
			Transform val = t;
			while (Object.op_Implicit((Object)(object)val))
			{
				if (((Object)val).name == "Global" && Object.op_Implicit((Object)(object)val.parent) && ((Object)val.parent).name == "Map")
				{
					return true;
				}
				val = val.parent;
			}
			return false;
		}

		public static void CaptureNativeVariants()
		{
			PropSpawner_AmuletStatues val = (from s in Resources.FindObjectsOfTypeAll<PropSpawner_AmuletStatues>()
				where Object.op_Implicit((Object)(object)s) && ((PropSpawner)s).props != null && ((PropSpawner)s).props.Length == 4 && ((PropSpawner)s).props.All(delegate(GameObject p)
				{
					//IL_0009: Unknown result type (might be due to invalid IL or missing references)
					//IL_000e: Unknown result type (might be due to invalid IL or missing references)
					int result;
					if (Object.op_Implicit((Object)(object)p))
					{
						Scene scene = p.scene;
						result = ((!((Scene)(ref scene)).IsValid()) ? 1 : 0);
					}
					else
					{
						result = 0;
					}
					return (byte)result != 0;
				})
				orderby ((Object)s).name == "ScoutStatueSpawner_Alpine" descending
				select s).FirstOrDefault();
			if (Object.op_Implicit((Object)(object)val))
			{
				variants = ((PropSpawner)val).props.ToArray();
			}
		}

		public static void Prefix()
		{
			CaptureNativeVariants();
			EnsurePublished();
		}

		public static void EnsurePublished()
		{
			if (!SoloGenerationPlugin.LocalMapReady)
			{
				Status = "waiting for selected Thunderfen map";
				return;
			}
			Transform[] array = (from t in Resources.FindObjectsOfTypeAll<Transform>().Where(delegate(Transform t)
				{
					//IL_000e: Unknown result type (might be due to invalid IL or missing references)
					//IL_0013: Unknown result type (might be due to invalid IL or missing references)
					//IL_0023: Unknown result type (might be due to invalid IL or missing references)
					//IL_0028: Unknown result type (might be due to invalid IL or missing references)
					int result;
					if (Object.op_Implicit((Object)(object)t))
					{
						Scene scene = ((Component)t).gameObject.scene;
						if (((Scene)(ref scene)).IsValid())
						{
							scene = ((Component)t).gameObject.scene;
							if (((Scene)(ref scene)).name == "WilIsland" && ((Object)t).name == "PF_HybridTerrain" && UnderGlobal(t) && Object.op_Implicit((Object)(object)t.parent))
							{
								result = ((((Object)t.parent).name == "RootsTerrain") ? 1 : 0);
								goto IL_007b;
							}
						}
					}
					result = 0;
					goto IL_007b;
					IL_007b:
					return (byte)result != 0;
				})
				select ThunderfenSceneScope.Find(t.parent.parent.parent) into t
				where Object.op_Implicit((Object)(object)t)
				select t).Distinct().ToArray();
			if (array.Length == 0)
			{
				Status = "waiting for published custom root";
				return;
			}
			if (array.Length != 1)
			{
				throw new InvalidOperationException("Ambiguous Thunderfen amulet root");
			}
			Amule

plugins/ThunderfenPalette/PoisonForestPalette.dll

Decompiled a week ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using BepInEx;
using Microsoft.CodeAnalysis;
using PoisonForestSolo;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.SceneManagement;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyVersion("0.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace PoisonForestPalette
{
	[BepInPlugin("local.peak.poisonforest.palette", "Thunderfen Terrain Palette", "1.0.0")]
	[BepInDependency("local.peak.poisonforest.solo", "0.6.2")]
	public sealed class PaletteTrial : BaseUnityPlugin
	{
		[Serializable]
		public sealed class Settings
		{
			public Color topColor = new Color(0.62f, 0.4f, 0.76f);
		}

		[Serializable]
		private sealed class State
		{
			public string utc;

			public string version = "1.0.0";

			public string root;

			public string error;

			public int renderers;

			public int slots;

			public int clonedMaterials;

			public int scans;

			public int unresolvedTargets;

			public int nativePending;

			public int expectedSlots;

			public int replacements;

			public int repairs;

			public int beforeRenderPasses;

			public bool ready;

			public bool floorActive;
		}

		public const string Version = "1.0.0";

		private readonly TerrainPaletteBindings bindings = new TerrainPaletteBindings();

		private Target[] targets;

		private Settings settings;

		private Transform root;

		private bool ready;

		private string error;

		private int scans;

		private int beforeRenderPasses;

		private float nextRefresh;

		private float nextReport;

		private string Folder => Path.Combine(Application.persistentDataPath, "PoisonForestPalette");

		private bool FloorActive => Object.op_Implicit((Object)(object)root) && Object.op_Implicit((Object)(object)root.Find("FloorRoot")) && ((Component)root.Find("FloorRoot")).gameObject.activeInHierarchy;

		private void Awake()
		{
			//IL_013d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0147: Expected O, but got Unknown
			//IL_0147: Unknown result type (might be due to invalid IL or missing references)
			//IL_0151: Expected O, but got Unknown
			try
			{
				string path = Path.Combine(Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location), "PoisonForestPalette.settings.json");
				settings = (File.Exists(path) ? JsonUtility.FromJson<Settings>(File.ReadAllText(path)) : new Settings());
				if (settings == null)
				{
					throw new InvalidOperationException("Palette settings missing.");
				}
				float[] array = new float[3]
				{
					settings.topColor.r,
					settings.topColor.g,
					settings.topColor.b
				};
				foreach (float num in array)
				{
					if (float.IsNaN(num) || float.IsInfinity(num) || num < 0f || num > 1f)
					{
						throw new InvalidOperationException("Palette RGB must be within 0..1.");
					}
				}
				using (Stream stream = typeof(PaletteTrial).Assembly.GetManifestResourceStream("PoisonForestPalette.TerrainTargets"))
				{
					targets = TargetManifest.Read(stream);
				}
				ready = true;
				RenderPipelineManager.beginCameraRendering += BeforeCamera;
				Camera.onPreCull = (CameraCallback)Delegate.Combine((Delegate?)(object)Camera.onPreCull, (Delegate?)new CameraCallback(BeforeBuiltin));
				((BaseUnityPlugin)this).Logger.LogInfo((object)"Purple terrain ready: before-render binding and continuous replacement repair; private native material copies only.");
				Report();
			}
			catch (Exception e)
			{
				Stop(e);
			}
		}

		private Transform FindRoot()
		{
			//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)
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Expected O, but got Unknown
			Scene sceneByName = SceneManager.GetSceneByName("WilIsland");
			if (!((Scene)(ref sceneByName)).IsValid() || !((Scene)(ref sceneByName)).isLoaded)
			{
				return null;
			}
			GameObject val = ((IEnumerable<GameObject>)((Scene)(ref sceneByName)).GetRootGameObjects()).FirstOrDefault((Func<GameObject, bool>)((GameObject g) => ((Object)g).name == "Map"));
			Transform val2 = (Object.op_Implicit((Object)(object)val) ? val.transform.Find("Global") : null);
			if (!Object.op_Implicit((Object)(object)val2))
			{
				return null;
			}
			foreach (Transform item in val2)
			{
				Transform val3 = item;
				if (((Object)val3).name.IndexOf("first-ridge", StringComparison.Ordinal) >= 0)
				{
					Transform val4 = (Transform)(Object.op_Implicit((Object)(object)val3.Find("FloorRoot/RootsTerrain")) ? ((object)val3) : ((object)((IEnumerable<Transform>)((Component)val3).GetComponentsInChildren<Transform>(true)).FirstOrDefault((Func<Transform, bool>)((Transform x) => Object.op_Implicit((Object)(object)x.Find("FloorRoot/RootsTerrain"))))));
					if (Object.op_Implicit((Object)(object)val4))
					{
						return val4;
					}
				}
			}
			return null;
		}

		private void Step()
		{
			//IL_0106: Unknown result type (might be due to invalid IL or missing references)
			if (!ready)
			{
				return;
			}
			try
			{
				Transform val = (Object.op_Implicit((Object)(object)root) ? root : FindRoot());
				if ((Object)(object)val != (Object)(object)root || (!Object.op_Implicit((Object)(object)val) && root != null))
				{
					root = val;
					bindings.SetRoot(root, targets);
					nextRefresh = Time.unscaledTime + 1f;
					scans = 0;
				}
				else if (Object.op_Implicit((Object)(object)root) && (bindings.Renderers == 0 || Time.unscaledTime >= nextRefresh))
				{
					bindings.RefreshTargets();
					nextRefresh = Time.unscaledTime + 1f;
				}
				if (Object.op_Implicit((Object)(object)root))
				{
					bindings.Apply(settings.topColor);
					scans++;
				}
			}
			catch (Exception e)
			{
				Stop(e);
			}
		}

		private void LateUpdate()
		{
			Step();
			if (Time.unscaledTime >= nextReport)
			{
				nextReport = Time.unscaledTime + 2f;
				Report();
			}
		}

		private void BeforeCamera(ScriptableRenderContext context, Camera camera)
		{
			if (ready)
			{
				beforeRenderPasses++;
				Step();
			}
		}

		private void BeforeBuiltin(Camera camera)
		{
			if (ready)
			{
				beforeRenderPasses++;
				Step();
			}
		}

		private void Report()
		{
			if (!RuntimeDiagnostics.PeriodicSnapshots)
			{
				return;
			}
			try
			{
				Directory.CreateDirectory(Folder);
				string contents = JsonUtility.ToJson((object)new State
				{
					utc = DateTime.UtcNow.ToString("O"),
					root = (Object.op_Implicit((Object)(object)root) ? ((Object)root).name : null),
					error = error,
					ready = ready,
					floorActive = FloorActive,
					renderers = bindings.Renderers,
					slots = bindings.Bound,
					expectedSlots = bindings.Slots,
					clonedMaterials = bindings.Clones,
					scans = scans,
					unresolvedTargets = bindings.Unresolved,
					nativePending = bindings.Pending,
					replacements = bindings.Replacements,
					repairs = bindings.Repairs,
					beforeRenderPasses = beforeRenderPasses
				}, true);
				File.WriteAllText(Path.Combine(Folder, "palette-state.json"), contents);
				if (Object.op_Implicit((Object)(object)root) && bindings.Bound > 0 && FloorActive)
				{
					File.WriteAllText(Path.Combine(Folder, "palette-last-active.json"), contents);
				}
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)("Palette report: " + ex.Message));
			}
		}

		private void Stop(Exception e)
		{
			ready = false;
			error = e.ToString();
			((BaseUnityPlugin)this).Logger.LogError((object)error);
			bindings.Dispose();
			Report();
		}

		private void OnDestroy()
		{
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Expected O, but got Unknown
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Expected O, but got Unknown
			ready = false;
			RenderPipelineManager.beginCameraRendering -= BeforeCamera;
			Camera.onPreCull = (CameraCallback)Delegate.Remove((Delegate?)(object)Camera.onPreCull, (Delegate?)new CameraCallback(BeforeBuiltin));
			bindings.Dispose();
		}
	}
	public sealed class TerrainPaletteBindings : IDisposable
	{
		private sealed class Binding
		{
			public Renderer renderer;

			public int slot;

			public Material original;

			public Material copy;

			public bool statue;
		}

		private readonly Dictionary<Renderer, HashSet<int>> targets = new Dictionary<Renderer, HashSet<int>>();

		private readonly Dictionary<long, Binding> bindings = new Dictionary<long, Binding>();

		private readonly Dictionary<int, Material> copies = new Dictionary<int, Material>();

		private Transform root;

		private Target[] legacy;

		private readonly HashSet<Renderer> statueRenderers = new HashSet<Renderer>();

		public int Renderers { get; private set; }

		public int Slots { get; private set; }

		public int Bound { get; private set; }

		public int Pending { get; private set; }

		public int Unresolved { get; private set; }

		public int Replacements { get; private set; }

		public int Repairs { get; private set; }

		public int Clones => copies.Count;

		public void SetRoot(Transform value, Target[] routes)
		{
			if (root != value)
			{
				Dispose();
				root = value;
				legacy = routes;
				RefreshTargets();
			}
		}

		private static bool RuntimeBranch(Transform node, Transform boundary)
		{
			Transform val = node;
			while (Object.op_Implicit((Object)(object)val) && (Object)(object)val != (Object)(object)boundary)
			{
				if (((Object)val).name == "PF_GeneratedNativeProps" || ((Object)val).name == "PF_Groundcover")
				{
					return true;
				}
				val = val.parent;
			}
			return false;
		}

		private void AddTerrain(Transform parent)
		{
			if (!Object.op_Implicit((Object)(object)parent))
			{
				return;
			}
			MeshRenderer[] componentsInChildren = ((Component)parent).GetComponentsInChildren<MeshRenderer>(true);
			foreach (MeshRenderer val in componentsInChildren)
			{
				if (!((Object)val).name.StartsWith("PF_PoolWater", StringComparison.Ordinal) && Object.op_Implicit((Object)(object)((Component)val).GetComponent<MeshCollider>()) && !RuntimeBranch(((Component)val).transform, parent))
				{
					targets[(Renderer)(object)val] = null;
				}
			}
		}

		private void AddStatueTerrain()
		{
			Transform val = root.Find("FloorRoot/TF_NativeAmuletStatue");
			if (!Object.op_Implicit((Object)(object)val))
			{
				return;
			}
			MeshRenderer[] componentsInChildren = ((Component)val).GetComponentsInChildren<MeshRenderer>(true);
			foreach (MeshRenderer val2 in componentsInChildren)
			{
				Material[] sharedMaterials = ((Renderer)val2).sharedMaterials;
				HashSet<int> hashSet = new HashSet<int>();
				for (int j = 0; j < sharedMaterials.Length; j++)
				{
					Material val3 = sharedMaterials[j];
					if (Object.op_Implicit((Object)(object)val3) && Object.op_Implicit((Object)(object)val3.shader) && ((Object)val3.shader).name == "W/Peak_Rock" && val3.HasProperty("_TopColor"))
					{
						hashSet.Add(j);
					}
				}
				if (hashSet.Count > 0)
				{
					targets[(Renderer)(object)val2] = hashSet;
					statueRenderers.Add((Renderer)(object)val2);
				}
			}
		}

		public void RefreshTargets()
		{
			targets.Clear();
			statueRenderers.Clear();
			Unresolved = 0;
			if (!Object.op_Implicit((Object)(object)root))
			{
				return;
			}
			Transform val = root.Find("FloorRoot/RootsTerrain/PF_HybridTerrain");
			if (Object.op_Implicit((Object)(object)val))
			{
				AddTerrain(val);
				AddTerrain(root.Find("CampfireRoot/RetainedHybridSummit"));
				AddStatueTerrain();
				return;
			}
			if (legacy != null)
			{
				Target[] array = legacy;
				foreach (Target target in array)
				{
					Transform val2 = root;
					for (int j = 0; j < target.indices.Length; j++)
					{
						if (!Object.op_Implicit((Object)(object)val2))
						{
							break;
						}
						int num = target.indices[j];
						val2 = ((num >= 0 && num < val2.childCount) ? val2.GetChild(num) : null);
						if (Object.op_Implicit((Object)(object)val2) && ((Object)val2).name != target.names[j])
						{
							val2 = null;
						}
					}
					MeshRenderer val3 = (Object.op_Implicit((Object)(object)val2) ? ((Component)val2).GetComponent<MeshRenderer>() : null);
					if (!Object.op_Implicit((Object)(object)val3))
					{
						Unresolved++;
						continue;
					}
					if (!targets.TryGetValue((Renderer)(object)val3, out var value))
					{
						value = new HashSet<int>();
						targets.Add((Renderer)(object)val3, value);
					}
					value.Add(target.slot);
				}
			}
			Transform val4 = root.Find("FloorRoot/PF_TerraceTrial");
			if (!Object.op_Implicit((Object)(object)val4))
			{
				return;
			}
			MeshRenderer[] componentsInChildren = ((Component)val4).GetComponentsInChildren<MeshRenderer>(true);
			foreach (MeshRenderer val5 in componentsInChildren)
			{
				if (((Object)val5).name.StartsWith("PF_TerraceRock", StringComparison.Ordinal))
				{
					targets[(Renderer)(object)val5] = null;
				}
			}
		}

		public static bool NativeReady(Material m)
		{
			return Object.op_Implicit((Object)(object)m) && Object.op_Implicit((Object)(object)m.shader) && m.shader.isSupported && !((Object)m.shader).name.StartsWith("FirstRidge/", StringComparison.Ordinal) && !((Object)m).name.StartsWith("PF_PurpleTerrain_", StringComparison.Ordinal) && m.HasProperty("_TopColor") && m.HasProperty("_Texture1") && Object.op_Implicit((Object)(object)m.GetTexture("_Texture1"));
		}

		private static Color Tint(Material m, Color top)
		{
			//IL_0009: 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_0019: 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)
			top.a = m.GetColor("_TopColor").a;
			return top;
		}

		private Material BiomeStone(Renderer statue)
		{
			Transform frame = root.Find("FloorRoot/RootsTerrain/PF_HybridTerrain");
			if (!Object.op_Implicit((Object)(object)frame))
			{
				return null;
			}
			return (from r in ((Component)frame).GetComponentsInChildren<MeshRenderer>(true)
				where Object.op_Implicit((Object)(object)r) && Object.op_Implicit((Object)(object)((Component)r).GetComponent<MeshCollider>()) && !((Object)r).name.StartsWith("PF_PoolWater", StringComparison.Ordinal) && !RuntimeBranch(((Component)r).transform, frame)
				select r).OrderBy(delegate(MeshRenderer r)
			{
				//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)
				//IL_000f: 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_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_0027: Unknown result type (might be due to invalid IL or missing references)
				//IL_002c: Unknown result type (might be due to invalid IL or missing references)
				//IL_002f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0034: Unknown result type (might be due to invalid IL or missing references)
				//IL_0039: Unknown result type (might be due to invalid IL or missing references)
				Bounds bounds = ((Renderer)r).bounds;
				Bounds bounds2 = statue.bounds;
				Vector3 val = ((Bounds)(ref bounds)).ClosestPoint(((Bounds)(ref bounds2)).center);
				bounds = statue.bounds;
				Vector3 val2 = val - ((Bounds)(ref bounds)).center;
				return ((Vector3)(ref val2)).sqrMagnitude;
			}).SelectMany((MeshRenderer r) => ((Renderer)r).sharedMaterials).FirstOrDefault((Func<Material, bool>)((Material m) => Object.op_Implicit((Object)(object)m) && Object.op_Implicit((Object)(object)m.shader) && ((Object)m.shader).name == "W/Peak_Rock" && m.HasProperty("_Texture1") && Object.op_Implicit((Object)(object)m.GetTexture("_Texture1"))));
		}

		public void Apply(Color top)
		{
			//IL_0174: Unknown result type (might be due to invalid IL or missing references)
			//IL_0179: Unknown result type (might be due to invalid IL or missing references)
			//IL_018a: Expected O, but got Unknown
			//IL_0264: Unknown result type (might be due to invalid IL or missing references)
			//IL_0265: Unknown result type (might be due to invalid IL or missing references)
			//IL_026a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0273: Unknown result type (might be due to invalid IL or missing references)
			//IL_0278: Unknown result type (might be due to invalid IL or missing references)
			//IL_020c: Unknown result type (might be due to invalid IL or missing references)
			//IL_020d: Unknown result type (might be due to invalid IL or missing references)
			//IL_028d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0314: Unknown result type (might be due to invalid IL or missing references)
			//IL_0319: Unknown result type (might be due to invalid IL or missing references)
			//IL_0333: Expected O, but got Unknown
			//IL_0383: Unknown result type (might be due to invalid IL or missing references)
			//IL_0384: Unknown result type (might be due to invalid IL or missing references)
			int num = (Pending = 0);
			int num3 = (Bound = num);
			int renderers = (Slots = num3);
			Renderers = renderers;
			if (!Object.op_Implicit((Object)(object)root))
			{
				return;
			}
			foreach (KeyValuePair<Renderer, HashSet<int>> target in targets)
			{
				Renderer key = target.Key;
				if (!Object.op_Implicit((Object)(object)key))
				{
					continue;
				}
				Renderers++;
				Material[] sharedMaterials = key.sharedMaterials;
				bool flag = false;
				for (int i = 0; i < sharedMaterials.Length; i++)
				{
					if (target.Value != null && !target.Value.Contains(i))
					{
						continue;
					}
					Slots++;
					Material val = sharedMaterials[i];
					long key2 = ((long)((Object)key).GetInstanceID() << 32) | (uint)i;
					bindings.TryGetValue(key2, out var value);
					if (statueRenderers.Contains(key))
					{
						Material val2 = BiomeStone(key);
						if (!Object.op_Implicit((Object)(object)val2))
						{
							Pending++;
							continue;
						}
						if (value == null)
						{
							value = new Binding
							{
								renderer = key,
								slot = i,
								original = val,
								copy = new Material(val2)
								{
									name = "TF_StatueBiomeStone_Private"
								},
								statue = true
							};
							bindings.Add(key2, value);
						}
						else if ((Object)(object)val != (Object)(object)value.copy)
						{
							value.original = val;
							Replacements++;
						}
						value.copy.shader = val2.shader;
						value.copy.CopyPropertiesFromMaterial(val2);
						value.copy.SetColor("_TopColor", Tint(value.copy, top));
						sharedMaterials[i] = value.copy;
						flag = true;
						Bound++;
						continue;
					}
					if (value != null && Object.op_Implicit((Object)(object)val) && (Object)(object)val == (Object)(object)value.copy)
					{
						Color val3 = Tint(val, top);
						if (val.GetColor("_TopColor") != val3)
						{
							val.SetColor("_TopColor", val3);
							Repairs++;
						}
						Bound++;
						continue;
					}
					if (!NativeReady(val))
					{
						Pending++;
						continue;
					}
					int instanceID = ((Object)val).GetInstanceID();
					if (!copies.TryGetValue(instanceID, out var value2) || !Object.op_Implicit((Object)(object)value2))
					{
						value2 = new Material(val)
						{
							name = "PF_PurpleTerrain_" + instanceID
						};
						copies[instanceID] = value2;
					}
					else
					{
						if ((Object)(object)value2.shader != (Object)(object)val.shader)
						{
							value2.shader = val.shader;
						}
						value2.CopyPropertiesFromMaterial(val);
					}
					value2.SetColor("_TopColor", Tint(val, top));
					if (value == null)
					{
						value = new Binding
						{
							renderer = key,
							slot = i
						};
						bindings.Add(key2, value);
					}
					else
					{
						Replacements++;
					}
					value.original = val;
					value.copy = value2;
					sharedMaterials[i] = value2;
					flag = true;
					Bound++;
					Repairs++;
				}
				if (flag)
				{
					key.sharedMaterials = sharedMaterials;
				}
			}
		}

		public void Dispose()
		{
			foreach (Binding value in bindings.Values)
			{
				if (Object.op_Implicit((Object)(object)value.renderer))
				{
					Material[] sharedMaterials = value.renderer.sharedMaterials;
					if (value.slot < sharedMaterials.Length && (Object)(object)sharedMaterials[value.slot] == (Object)(object)value.copy)
					{
						sharedMaterials[value.slot] = value.original;
						value.renderer.sharedMaterials = sharedMaterials;
					}
				}
			}
			foreach (Binding value2 in bindings.Values)
			{
				if (value2.statue && Object.op_Implicit((Object)(object)value2.copy))
				{
					if (Application.isPlaying)
					{
						Object.Destroy((Object)(object)value2.copy);
					}
					else
					{
						Object.DestroyImmediate((Object)(object)value2.copy);
					}
				}
			}
			bindings.Clear();
			statueRenderers.Clear();
			foreach (Material value3 in copies.Values)
			{
				if (Object.op_Implicit((Object)(object)value3))
				{
					if (Application.isPlaying)
					{
						Object.Destroy((Object)(object)value3);
					}
					else
					{
						Object.DestroyImmediate((Object)(object)value3);
					}
				}
			}
			copies.Clear();
			targets.Clear();
			root = null;
			legacy = null;
			int num = (Repairs = 0);
			int num3 = (Replacements = num);
			int num5 = (Unresolved = num3);
			int num7 = (Pending = num5);
			int num9 = (Bound = num7);
			int renderers = (Slots = num9);
			Renderers = renderers;
		}
	}
	public sealed class Target
	{
		public int[] indices;

		public string[] names;

		public int slot;
	}
	public static class TargetManifest
	{
		public static Target[] Read(Stream stream)
		{
			if (stream == null)
			{
				throw new InvalidDataException("Embedded terrain manifest stream is missing.");
			}
			using BinaryReader binaryReader = new BinaryReader(stream, Encoding.UTF8, leaveOpen: true);
			if (binaryReader.ReadInt32() != 1346785329)
			{
				throw new InvalidDataException("Unexpected terrain manifest format.");
			}
			int num = binaryReader.ReadInt32();
			if (num != 2974)
			{
				throw new InvalidDataException("Expected 2974 terrain targets; got " + num);
			}
			Target[] array = new Target[num];
			for (int i = 0; i < num; i++)
			{
				int num2 = binaryReader.ReadInt32();
				int num3 = binaryReader.ReadInt32();
				if (num2 < 0 || num2 > 15 || num3 < 2 || num3 > 32)
				{
					throw new InvalidDataException("Invalid terrain target route.");
				}
				Target target = new Target();
				target.slot = num2;
				target.indices = new int[num3];
				target.names = new string[num3];
				Target target2 = target;
				for (int j = 0; j < num3; j++)
				{
					target2.indices[j] = binaryReader.ReadInt32();
					target2.names[j] = binaryReader.ReadString();
					if (target2.indices[j] < 0 || string.IsNullOrEmpty(target2.names[j]))
					{
						throw new InvalidDataException("Invalid target node.");
					}
				}
				if ((!(target2.names[0] == "FloorRoot") || !(target2.names[1] == "RootsTerrain")) && (!(target2.names[0] == "CampfireRoot") || !(target2.names[1] == "RetainedRootsSummit")))
				{
					throw new InvalidDataException("Target is outside custom Roots terrain.");
				}
				array[i] = target2;
			}
			if (stream.ReadByte() != -1)
			{
				throw new InvalidDataException("Trailing terrain manifest bytes.");
			}
			return array;
		}
	}
}

plugins/ThunderfenPools/PoisonForestPools.dll

Decompiled a week ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security.Cryptography;
using BepInEx;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using PoisonForestGeneration;
using PoisonForestSolo;
using UnityEngine;
using UnityEngine.SceneManagement;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyVersion("0.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace PoisonForestPools
{
	[BepInPlugin("local.peak.poisonforest.pools", "Thunderfen Shallow Pools", "1.0.0")]
	[BepInDependency("local.peak.poisonforest.solo", "0.1.0")]
	public sealed class PoolsPlugin : BaseUnityPlugin
	{
		[Serializable]
		private sealed class State
		{
			public string version = "1.0.0";

			public string utc;

			public string error;

			public string root;

			public string catalogSha256;

			public string waterMaterialSource;

			public string waterShader;

			public string waterVisualMessage;

			public float waterFoamDepth;

			public Color waterFinalTint;

			public Color waterPreFoamTint;

			public bool nativeWaterReady;

			public int nativeWaterRenderers;

			public bool ready;

			public bool floorActive;

			public bool poolPoisonImplemented = false;

			public int immersion;

			public int waterRenderers;

			public float waterLevel;

			public float bedLevel;

			public float poolDepth;

			public float headToFootHeight;

			public float movementMultiplier;

			public float jumpVelocityMultiplier;

			public float jumpHeightTargetMultiplier;

			public Vector3 character;
		}

		public const string Version = "1.0.0";

		private string catalogSha;

		private int dataRevision = -1;

		internal static PoolsPlugin Instance;

		private PoolField field;

		private Transform root;

		private Harmony harmony;

		private float nextScan;

		private float nextReport;

		private int state;

		private int waterRenderers;

		private bool ready;

		private string error;

		private State report = new State();

		private PoolWaterVisuals waterVisuals = new PoolWaterVisuals();

		private string lastWaterMessage;

		private string Folder => Path.Combine(Application.persistentDataPath, "PoisonForestPools");

		private bool Active => ready && Object.op_Implicit((Object)(object)root) && ((Component)root).gameObject.activeInHierarchy;

		private void Awake()
		{
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Expected O, but got Unknown
			Instance = this;
			try
			{
				NativeCompatibility.CheckPatches(typeof(PoolsPlugin).Assembly);
				byte[] array = GeneratedData.Read("pool-catalog.bin");
				using (SHA256 sHA = SHA256.Create())
				{
					catalogSha = BitConverter.ToString(sHA.ComputeHash(array)).Replace("-", "");
				}
				field = PoolField.Read(array);
				if (field == null || !field.Valid)
				{
					throw new Exception("Pool catalog shape invalid");
				}
				harmony = new Harmony("local.peak.poisonforest.pools");
				harmony.PatchAll(typeof(PoolsPlugin).Assembly);
				ready = true;
				((BaseUnityPlugin)this).Logger.LogInfo((object)"Seeded shallow pools ready: precise shore query + native wading modifiers. No pool poison in this layout trial.");
			}
			catch (Exception e)
			{
				Harmony obj = harmony;
				if (obj != null)
				{
					obj.UnpatchSelf();
				}
				harmony = null;
				SharedWorld.MarkStartupFailure("Thunderfen pools");
				Fail(e);
				return;
			}
			WriteReport();
		}

		private Transform FindRoot()
		{
			//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)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Expected O, but got Unknown
			Scene sceneByName = SceneManager.GetSceneByName("WilIsland");
			if (!((Scene)(ref sceneByName)).IsValid() || !((Scene)(ref sceneByName)).isLoaded)
			{
				return null;
			}
			GameObject val = ((IEnumerable<GameObject>)((Scene)(ref sceneByName)).GetRootGameObjects()).FirstOrDefault((Func<GameObject, bool>)((GameObject g) => ((Object)g).name == "Map"));
			if (!Object.op_Implicit((Object)(object)val))
			{
				return null;
			}
			Transform val2 = val.transform.Find("Global");
			if (!Object.op_Implicit((Object)(object)val2))
			{
				return null;
			}
			foreach (Transform item in val2)
			{
				Transform val3 = item;
				if (((Object)val3).name.IndexOf("first-ridge", StringComparison.Ordinal) >= 0)
				{
					Transform val4 = (Transform)(Object.op_Implicit((Object)(object)val3.Find("FloorRoot/RootsTerrain/PF_HybridTerrain")) ? ((object)val3) : ((object)((IEnumerable<Transform>)((Component)val3).GetComponentsInChildren<Transform>(true)).FirstOrDefault((Func<Transform, bool>)((Transform x) => Object.op_Implicit((Object)(object)x.Find("FloorRoot/RootsTerrain/PF_HybridTerrain"))))));
					if (Object.op_Implicit((Object)(object)val4))
					{
						return val4.Find("FloorRoot/RootsTerrain/PF_HybridTerrain");
					}
				}
			}
			return null;
		}

		private bool Immersed(Vector3 world, out float bottom, out float level)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: 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)
			Vector3 val = root.InverseTransformPoint(world);
			return field.Query(val.x, val.z, out bottom, out level) && val.y >= bottom - 0.25f && val.y < level;
		}

		private static Bodypart Part(Character c, BodypartType type)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			Bodypart value;
			return (Object.op_Implicit((Object)(object)c.refs.ragdoll) && c.refs.ragdoll.partDict.TryGetValue(type, out value)) ? value : null;
		}

		private void Sample()
		{
			//IL_009d: 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_012f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0134: Unknown result type (might be due to invalid IL or missing references)
			//IL_0139: Unknown result type (might be due to invalid IL or missing references)
			//IL_0141: Unknown result type (might be due to invalid IL or missing references)
			//IL_0148: Unknown result type (might be due to invalid IL or missing references)
			//IL_0101: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0207: Unknown result type (might be due to invalid IL or missing references)
			//IL_0209: Unknown result type (might be due to invalid IL or missing references)
			state = 0;
			if (RunData.Pending || !Active || !Object.op_Implicit((Object)(object)Character.localCharacter) || !Object.op_Implicit((Object)(object)Character.localCharacter.data))
			{
				return;
			}
			Character localCharacter = Character.localCharacter;
			if (!Object.op_Implicit((Object)(object)localCharacter.refs.ragdoll))
			{
				return;
			}
			Bodypart val = Part(localCharacter, (BodypartType)2);
			Bodypart val2 = Part(localCharacter, (BodypartType)4);
			if (!Object.op_Implicit((Object)(object)val) || !Object.op_Implicit((Object)(object)val2))
			{
				return;
			}
			if (Immersed(val.transform.position, out var bottom, out var level))
			{
				state = 2;
			}
			else
			{
				Bodypart val3 = Part(localCharacter, (BodypartType)13);
				Bodypart val4 = Part(localCharacter, (BodypartType)16);
				if ((Object.op_Implicit((Object)(object)val3) && Immersed(val3.transform.position, out bottom, out level)) || (Object.op_Implicit((Object)(object)val4) && Immersed(val4.transform.position, out bottom, out level)))
				{
					state = 1;
				}
			}
			Vector3 val5 = root.InverseTransformPoint(val.transform.position);
			if (field.Query(val5.x, val5.z, out bottom, out level))
			{
				report.waterLevel = level;
				report.bedLevel = bottom;
				report.poolDepth = level - bottom;
			}
			else
			{
				report.waterLevel = (report.bedLevel = (report.poolDepth = 0f));
			}
			Bodypart val6 = Part(localCharacter, (BodypartType)13);
			report.headToFootHeight = (Object.op_Implicit((Object)(object)val6) ? (val2.transform.position.y - val6.transform.position.y) : 0f);
			report.character = val5;
		}

		private void Update()
		{
			if (!ready)
			{
				return;
			}
			try
			{
				if (RunData.Pending)
				{
					root = null;
					state = 0;
					waterVisuals.Update(null, 0);
					return;
				}
				if (dataRevision != RunData.Revision)
				{
					byte[] array = GeneratedData.Read("pool-catalog.bin");
					field = PoolField.Read(array);
					using (SHA256 sHA = SHA256.Create())
					{
						catalogSha = BitConverter.ToString(sHA.ComputeHash(array)).Replace("-", "");
					}
					if (field == null || !field.Valid)
					{
						throw new Exception("Fresh pool catalog invalid");
					}
					dataRevision = RunData.Revision;
					waterVisuals.Dispose();
					nextScan = 0f;
				}
				if (Time.unscaledTime >= nextScan)
				{
					nextScan = Time.unscaledTime + 1f;
					root = FindRoot();
					waterRenderers = (Object.op_Implicit((Object)(object)root) ? ((Component)root).GetComponentsInChildren<MeshRenderer>(true).Count((MeshRenderer r) => ((Renderer)r).enabled && ((Component)r).gameObject.activeSelf && ((Object)r).name.StartsWith("PF_PoolWater", StringComparison.Ordinal)) : 0);
					if (Object.op_Implicit((Object)(object)root) && waterRenderers != field.regions)
					{
						root = null;
					}
					waterVisuals.Update(root, field.regions);
					if (lastWaterMessage != waterVisuals.Message)
					{
						lastWaterMessage = waterVisuals.Message;
						((BaseUnityPlugin)this).Logger.LogInfo((object)lastWaterMessage);
					}
				}
				if (Time.unscaledTime >= nextReport)
				{
					nextReport = Time.unscaledTime + 2f;
					Sample();
					WriteReport();
				}
			}
			catch (Exception e)
			{
				Fail(e);
			}
		}

		private void LateUpdate()
		{
			if (!ready || RunData.Pending)
			{
				return;
			}
			try
			{
				Sample();
				if (state > 0 && Object.op_Implicit((Object)(object)Character.localCharacter) && Object.op_Implicit((Object)(object)Character.localCharacter.data))
				{
					Character.localCharacter.data.inWater = Mathf.Max(Character.localCharacter.data.inWater, (state == 2) ? 0.25f : 0.3f);
				}
			}
			catch (Exception e)
			{
				Fail(e);
			}
		}

		internal void AfterWaterReset(CharacterMovement movement)
		{
			if (RunData.Pending || !Active || !Object.op_Implicit((Object)(object)Character.localCharacter) || (Object)(object)Character.localCharacter.refs.movement != (Object)(object)movement)
			{
				return;
			}
			try
			{
				Sample();
				if (state > 0)
				{
					movement.SetWaterMovementModifier(0.5f, Mathf.Sqrt(0.5f), false);
				}
			}
			catch (Exception e)
			{
				Fail(e);
			}
		}

		private void Fail(Exception e)
		{
			ready = false;
			error = e.ToString();
			((BaseUnityPlugin)this).Logger.LogError((object)error);
			WriteReport();
		}

		private void WriteReport()
		{
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			if (!RuntimeDiagnostics.PeriodicSnapshots)
			{
				return;
			}
			try
			{
				Directory.CreateDirectory(Folder);
				report.utc = DateTime.UtcNow.ToString("O");
				report.error = error;
				report.ready = ready;
				report.waterFoamDepth = waterVisuals.FoamDepth;
				report.waterFinalTint = waterVisuals.FinalTint;
				report.waterPreFoamTint = waterVisuals.PreFoamTint;
				report.nativeWaterReady = waterVisuals.Ready;
				report.nativeWaterRenderers = waterVisuals.Applied;
				report.waterMaterialSource = waterVisuals.Source;
				report.waterShader = waterVisuals.ShaderName;
				report.waterVisualMessage = waterVisuals.Message;
				report.root = (Object.op_Implicit((Object)(object)root) ? ((Object)root).name : null);
				report.floorActive = Active;
				report.immersion = state;
				report.waterRenderers = waterRenderers;
				report.catalogSha256 = catalogSha;
				report.movementMultiplier = ((state > 0) ? 0.5f : 1f);
				report.jumpVelocityMultiplier = ((state > 0) ? Mathf.Sqrt(0.5f) : 1f);
				report.jumpHeightTargetMultiplier = ((state > 0) ? 0.5f : 1f);
				File.WriteAllText(Path.Combine(Folder, "pool-runtime-state.json"), JsonUtility.ToJson((object)report, true));
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)ex.Message);
			}
		}

		private void OnDestroy()
		{
			ready = false;
			waterVisuals.Dispose();
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
			if ((Object)(object)Instance == (Object)(object)this)
			{
				Instance = null;
			}
		}
	}
	[HarmonyPatch(typeof(CharacterMovement), "ResetFixedVars", new Type[] { })]
	internal static class WaterResetPatch
	{
		[HarmonyPostfix]
		private static void After(CharacterMovement __instance)
		{
			if (Object.op_Implicit((Object)(object)PoolsPlugin.Instance))
			{
				PoolsPlugin.Instance.AfterWaterReset(__instance);
			}
		}
	}
	[Serializable]
	public class PoolPatch
	{
		public int schema;

		public int seed;

		public int nx;

		public int nz;

		public int regions;

		public float x0;

		public float z0;

		public float dx;

		public float dz;

		public float[] bed;

		public float[] water;

		public bool ShapeValid => nx > 1 && nz > 1 && dx > 0f && dz > 0f && bed != null && water != null && bed.Length == nx * nz && water.Length == (nx - 1) * (nz - 1) * 2;

		public bool Query(float x, float z, out float bottom, out float level)
		{
			bottom = (level = 0f);
			float num = (x - x0) / dx;
			float num2 = (z - z0) / dz;
			if (float.IsNaN(num) || float.IsNaN(num2) || num < 0f || num2 < 0f || num >= (float)(nx - 1) || num2 >= (float)(nz - 1))
			{
				return false;
			}
			int num3 = (int)Math.Floor(num);
			int num4 = (int)Math.Floor(num2);
			int num5 = num4 * nx + num3;
			float num6 = num - (float)num3;
			float num7 = num2 - (float)num4;
			bool flag = num6 + num7 > 1f;
			int num8 = (num4 * (nx - 1) + num3) * 2 + (flag ? 1 : 0);
			level = water[num8];
			if (level < -90000f)
			{
				return false;
			}
			bottom = (flag ? (bed[num5 + 1] * (1f - num7) + bed[num5 + nx] * (1f - num6) + bed[num5 + nx + 1] * (num6 + num7 - 1f)) : (bed[num5] * (1f - num6 - num7) + bed[num5 + nx] * num7 + bed[num5 + 1] * num6));
			return level - bottom > 0.015f;
		}
	}
	[Serializable]
	public sealed class PoolField : PoolPatch
	{
		public PoolPatch[] patches;

		public bool Valid => base.ShapeValid && (schema == 1 || (schema == 2 && patches != null && patches.Length >= 1 && patches.Length <= 4 && Array.TrueForAll(patches, (PoolPatch p) => p != null && p.schema == 1 && p.ShapeValid)));

		public static PoolField Read(byte[] bytes)
		{
			if (bytes == null || bytes.Length > 16000000)
			{
				throw new InvalidDataException("Pool catalog length");
			}
			using BinaryReader binaryReader = new BinaryReader(new MemoryStream(bytes));
			if (binaryReader.ReadUInt32() != 844121680)
			{
				throw new InvalidDataException("Pool catalog signature");
			}
			int num = binaryReader.ReadInt32();
			int num2 = binaryReader.ReadInt32();
			int num3 = binaryReader.ReadInt32();
			if (num < 1 || num > 5 || num2 < 1 || num2 > 64 || num3 < 0)
			{
				throw new InvalidDataException("Pool catalog header");
			}
			PoolPatch[] array = new PoolPatch[num];
			int num4 = 0;
			for (int i = 0; i < num; i++)
			{
				PoolPatch poolPatch = new PoolPatch
				{
					schema = 1,
					nx = binaryReader.ReadInt32(),
					nz = binaryReader.ReadInt32(),
					x0 = binaryReader.ReadSingle(),
					z0 = binaryReader.ReadSingle(),
					dx = binaryReader.ReadSingle(),
					dz = binaryReader.ReadSingle(),
					regions = binaryReader.ReadInt32(),
					seed = binaryReader.ReadInt32()
				};
				if (poolPatch.nx < 2 || poolPatch.nx > 512 || poolPatch.nz < 2 || poolPatch.nz > 512 || !Finite(poolPatch.x0) || !Finite(poolPatch.z0) || !Finite(poolPatch.dx) || !Finite(poolPatch.dz) || poolPatch.dx <= 0f || poolPatch.dz <= 0f || poolPatch.regions < 1 || poolPatch.regions > 64 || poolPatch.seed < 0)
				{
					throw new InvalidDataException("Pool field dimensions");
				}
				int num5 = poolPatch.nx * poolPatch.nz;
				int num6 = (poolPatch.nx - 1) * (poolPatch.nz - 1) * 2;
				if ((long)(num5 + num6) * 4L > binaryReader.BaseStream.Length - binaryReader.BaseStream.Position)
				{
					throw new EndOfStreamException();
				}
				poolPatch.bed = new float[num5];
				poolPatch.water = new float[num6];
				for (int j = 0; j < num5; j++)
				{
					poolPatch.bed[j] = binaryReader.ReadSingle();
					if (!Finite(poolPatch.bed[j]) || Math.Abs(poolPatch.bed[j]) > 10000f)
					{
						throw new InvalidDataException("Pool bed coordinate");
					}
				}
				for (int k = 0; k < num6; k++)
				{
					poolPatch.water[k] = binaryReader.ReadSingle();
					if (!Finite(poolPatch.water[k]) || Math.Abs(poolPatch.water[k]) > 100000f)
					{
						throw new InvalidDataException("Pool water coordinate");
					}
				}
				array[i] = poolPatch;
				num4 += poolPatch.regions;
			}
			if (num4 != num2 || binaryReader.BaseStream.Position != binaryReader.BaseStream.Length)
			{
				throw new InvalidDataException("Pool catalog totals/trailing data");
			}
			PoolPatch poolPatch2 = array[0];
			PoolField poolField = new PoolField();
			poolField.schema = ((num == 1) ? 1 : 2);
			poolField.regions = num2;
			poolField.seed = num3;
			poolField.nx = poolPatch2.nx;
			poolField.nz = poolPatch2.nz;
			poolField.x0 = poolPatch2.x0;
			poolField.z0 = poolPatch2.z0;
			poolField.dx = poolPatch2.dx;
			poolField.dz = poolPatch2.dz;
			poolField.bed = poolPatch2.bed;
			poolField.water = poolPatch2.water;
			poolField.patches = new PoolPatch[num - 1];
			PoolField poolField2 = poolField;
			for (int l = 1; l < num; l++)
			{
				poolField2.patches[l - 1] = array[l];
			}
			return poolField2;
		}

		private static bool Finite(float f)
		{
			return !float.IsNaN(f) && !float.IsInfinity(f);
		}

		public new bool Query(float x, float z, out float bottom, out float level)
		{
			if (patches != null)
			{
				PoolPatch[] array = patches;
				foreach (PoolPatch poolPatch in array)
				{
					if (poolPatch.Query(x, z, out bottom, out level))
					{
						return true;
					}
				}
			}
			return base.Query(x, z, out bottom, out level);
		}
	}
	public sealed class PoolWaterVisuals : IDisposable
	{
		private sealed class Binding
		{
			public MeshRenderer renderer;

			public Material[] original;
		}

		private readonly List<Binding> bindings = new List<Binding>();

		private Transform root;

		private Material copy;

		private int retries;

		private static readonly string[] Sources = new string[3] { "M_Water_Onsen", "M_Water_forest 1", "M_WaterTest" };

		private static readonly string[] Required = new string[11]
		{
			"_WaterColorPrimary", "_WaterColorSecodary", "_WaterColorShallow", "_FoamTint", "_WaterTint", "_WaterTintPreFoam", "_UseRadialMask", "_VertexOffset", "_CloudIntensity", "_SpecularIntensity",
			"_FoamDepth"
		};

		public string Source { get; private set; }

		public string ShaderName { get; private set; }

		public string Message { get; private set; } = "Waiting for custom pools";

		public Color FinalTint => Object.op_Implicit((Object)(object)copy) ? copy.GetColor("_WaterTint") : Color.white;

		public Color PreFoamTint => Object.op_Implicit((Object)(object)copy) ? copy.GetColor("_WaterTintPreFoam") : Color.white;

		public float FoamDepth => Object.op_Implicit((Object)(object)copy) ? copy.GetFloat("_FoamDepth") : 0f;

		public int Applied => bindings.Count;

		public bool Ready => Object.op_Implicit((Object)(object)copy) && bindings.Count > 0;

		private static string BaseName(Material m)
		{
			return ((Object)m).name.Replace(" (Instance)", "");
		}

		private static bool Suitable(Material m)
		{
			return Object.op_Implicit((Object)(object)m) && Object.op_Implicit((Object)(object)m.shader) && ((Object)m.shader).name == "GD/Water-GD" && m.shader.isSupported && Required.All((string p) => m.HasProperty(p)) && m.HasProperty("_Foam") && Object.op_Implicit((Object)(object)m.GetTexture("_Foam")) && m.HasProperty("_SeaNoise") && Object.op_Implicit((Object)(object)m.GetTexture("_SeaNoise"));
		}

		private static void Tint(Material material, string key, Color color)
		{
			//IL_0005: 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)
			color.a = material.GetColor(key).a;
			material.SetColor(key, color);
		}

		public void Update(Transform value, int regions)
		{
			//IL_0196: Unknown result type (might be due to invalid IL or missing references)
			//IL_019b: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ac: Expected O, but got Unknown
			//IL_01c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0210: Unknown result type (might be due to invalid IL or missing references)
			//IL_0235: Unknown result type (might be due to invalid IL or missing references)
			//IL_025a: Unknown result type (might be due to invalid IL or missing references)
			//IL_027f: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)root != (Object)(object)value)
			{
				Dispose();
				root = value;
				retries = 0;
			}
			if (!Object.op_Implicit((Object)(object)root) || !((Component)root).gameObject.activeInHierarchy)
			{
				Message = "Waiting for active custom pools";
				return;
			}
			MeshRenderer[] array = (from r in ((Component)root).GetComponentsInChildren<MeshRenderer>(true)
				where ((Renderer)r).enabled && ((Component)r).gameObject.activeSelf && ((Object)r).name.StartsWith("PF_PoolWater_", StringComparison.Ordinal)
				select r).ToArray();
			if (array.Length != regions)
			{
				Message = "Waiting for complete pool geometry";
				return;
			}
			if (!Object.op_Implicit((Object)(object)copy))
			{
				Material[] source = Resources.FindObjectsOfTypeAll<Material>();
				Material val = null;
				string[] sources = Sources;
				foreach (string name in sources)
				{
					val = ((IEnumerable<Material>)source).FirstOrDefault((Func<Material, bool>)((Material m) => Suitable(m) && BaseName(m) == name));
					if (Object.op_Implicit((Object)(object)val))
					{
						break;
					}
				}
				if (!Object.op_Implicit((Object)(object)val))
				{
					retries++;
					Message = "Native water material not loaded (attempt " + retries + ")";
					return;
				}
				Source = ((Object)val).name;
				ShaderName = ((Object)val.shader).name;
				copy = new Material(val)
				{
					name = "PF_PrivateNativePoolWater"
				};
				Tint(copy, "_WaterColorPrimary", new Color(0.12f, 0.25f, 0.21f));
				Tint(copy, "_WaterColorSecodary", new Color(0.33f, 0.5f, 0.42f));
				Tint(copy, "_WaterColorShallow", new Color(0.48f, 0.64f, 0.54f));
				Tint(copy, "_FoamTint", new Color(0.96f, 0.99f, 0.96f));
				Tint(copy, "_WaterTintPreFoam", new Color(0.95f, 1f, 0.9f));
				Tint(copy, "_WaterTint", new Color(0.86f, 1f, 0.79f));
				copy.SetFloat("_UseRadialMask", 0f);
				copy.DisableKeyword("_USERADIALMASK_ON");
				copy.SetFloat("_VertexOffset", 0f);
				copy.SetFloat("_FoamDepth", val.GetFloat("_FoamDepth") * 3f);
				copy.SetFloat("_CloudIntensity", 0.18f);
				copy.SetFloat("_SpecularIntensity", 0.75f);
			}
			MeshRenderer[] array2 = array;
			foreach (MeshRenderer renderer in array2)
			{
				if (bindings.Any((Binding b) => (Object)(object)b.renderer == (Object)(object)renderer))
				{
					if (((Renderer)renderer).sharedMaterials.All((Material m) => (Object)(object)m == (Object)(object)copy))
					{
						continue;
					}
				}
				else
				{
					bindings.Add(new Binding
					{
						renderer = renderer,
						original = ((Renderer)renderer).sharedMaterials
					});
				}
				((Renderer)renderer).sharedMaterials = Enumerable.Repeat<Material>(copy, ((Renderer)renderer).sharedMaterials.Length).ToArray();
			}
			Message = "Native animated water: " + Source;
		}

		public void Dispose()
		{
			foreach (Binding binding in bindings)
			{
				if (!Object.op_Implicit((Object)(object)binding.renderer))
				{
					continue;
				}
				Material[] sharedMaterials = ((Renderer)binding.renderer).sharedMaterials;
				bool flag = false;
				for (int i = 0; i < sharedMaterials.Length && i < binding.original.Length; i++)
				{
					if ((Object)(object)sharedMaterials[i] == (Object)(object)copy)
					{
						sharedMaterials[i] = binding.original[i];
						flag = true;
					}
				}
				if (flag)
				{
					((Renderer)binding.renderer).sharedMaterials = sharedMaterials;
				}
			}
			bindings.Clear();
			if (Object.op_Implicit((Object)(object)copy))
			{
				Object.Destroy((Object)(object)copy);
			}
			copy = null;
			Source = null;
			ShaderName = null;
			root = null;
		}
	}
}

plugins/ThunderfenRain/PoisonForestRain.dll

Decompiled a week ago
using System;
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.Security.Cryptography;
using System.Text;
using BepInEx;
using ExitGames.Client.Photon;
using Microsoft.CodeAnalysis;
using Photon.Pun;
using Photon.Realtime;
using PoisonForestSolo;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.SceneManagement;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyVersion("0.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace PoisonForestRain
{
	public struct V3
	{
		public double x;

		public double y;

		public double z;

		public V3(double a, double b, double c)
		{
			x = a;
			y = b;
			z = c;
		}

		public static V3 operator -(V3 a, V3 b)
		{
			return new V3(a.x - b.x, a.y - b.y, a.z - b.z);
		}

		public static V3 Cross(V3 a, V3 b)
		{
			return new V3(a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x);
		}

		public static double Dot(V3 a, V3 b)
		{
			return a.x * b.x + a.y * b.y + a.z * b.z;
		}
	}
	public static class RainMath
	{
		public const double PoisonExposureDelay = 2.0;

		public static bool Triangle(V3 origin, V3 direction, V3 a, V3 b, V3 c, double max, out double distance)
		{
			distance = 0.0;
			V3 v = b - a;
			V3 v2 = c - a;
			V3 b2 = V3.Cross(direction, v2);
			double num = V3.Dot(v, b2);
			if (Math.Abs(num) < 1E-10)
			{
				return false;
			}
			double num2 = 1.0 / num;
			V3 a2 = origin - a;
			double num3 = V3.Dot(a2, b2) * num2;
			if (num3 < -1E-06 || num3 > 1.000001)
			{
				return false;
			}
			V3 b3 = V3.Cross(a2, v);
			double num4 = V3.Dot(direction, b3) * num2;
			if (num4 < -1E-06 || num3 + num4 > 1.000001)
			{
				return false;
			}
			distance = V3.Dot(v2, b3) * num2;
			return distance >= 0.0 && distance <= max;
		}

		public static double SkyLuminance(double r, double g, double b)
		{
			return 0.2126 * r + 0.7152 * g + 0.0722 * b;
		}

		public static double SkyChannel(double channel, double luminance, double brightness, double saturation, double grayTint)
		{
			return Math.Max(0.0, (luminance * grayTint * (1.0 - saturation) + channel * saturation) * brightness);
		}

		public static double Haze(double current, bool inBiome, bool raining, double dt, double fadeSeconds)
		{
			if (!inBiome)
			{
				return 0.0;
			}
			double num = (raining ? 1 : 0);
			if (fadeSeconds <= 0.0)
			{
				return num;
			}
			double num2 = Math.Max(0.0, dt) / fadeSeconds;
			return (num > current) ? Math.Min(num, current + num2) : Math.Max(num, current - num2);
		}

		public static int NextMode(int current)
		{
			return (current + 1) % 3;
		}

		public static double OverrideEnd(double now, int mode, double wet, double clear)
		{
			return (mode == 0) ? 0.0 : (now + ((mode == 1) ? wet : clear));
		}

		public static bool OverrideExpired(double now, int mode, double until)
		{
			return mode != 0 && (until <= 0.0 || now >= until);
		}

		public static double Remaining(double now, double epoch, double wet, double clear, int mode, double until)
		{
			if (mode != 0)
			{
				return Math.Max(0.0, until - now);
			}
			if (epoch <= 0.0)
			{
				return 0.0;
			}
			if (now < epoch)
			{
				return epoch - now;
			}
			double num = (now - epoch) % (wet + clear);
			return (num < wet) ? (wet - num) : (wet + clear - num);
		}

		public static bool Wet(double now, double epoch, double wet, double clear, int mode)
		{
			switch (mode)
			{
			case 1:
				return true;
			case 2:
				return false;
			default:
				if (epoch <= 0.0 || now < epoch)
				{
					return false;
				}
				return (now - epoch) % (wet + clear) < wet;
			}
		}

		public static bool SummitProtected(double bodyY, double summitY, double clearance = 40.0)
		{
			return bodyY >= summitY - clearance;
		}

		public static double EnvironmentDose(double rate, double seconds, bool insideBiome, bool raining, double exposed)
		{
			return (insideBiome && raining) ? Dose(rate, seconds, exposed, requireContact: false, contactRecent: false) : 0.0;
		}

		public static double ContinuousExposureDose(double rate, double seconds, bool exposed, double exposure, ref double? elapsed)
		{
			if (!exposed || exposure <= 0.0)
			{
				elapsed = null;
				return 0.0;
			}
			if (!elapsed.HasValue)
			{
				elapsed = 0.0;
				return 0.0;
			}
			double value = elapsed.Value;
			elapsed = Math.Min(2.0, value + seconds);
			return Dose(rate, Math.Max(0.0, seconds - (2.0 - value)), exposure, requireContact: false, contactRecent: false);
		}

		public static double Dose(double rate, double seconds, double exposed, bool requireContact, bool contactRecent)
		{
			if (requireContact && !contactRecent)
			{
				return 0.0;
			}
			return rate * Math.Max(0.0, seconds) * Math.Max(0.0, Math.Min(1.0, exposed));
		}
	}
	public sealed class RainGeometry
	{
		private sealed class MeshData
		{
			public V3[] vertices;

			public int[] triangles;
		}

		private sealed class Roof
		{
			public Bounds bounds;

			public Matrix4x4 inverse;

			public Matrix4x4 forward;

			public MeshData data;
		}

		private readonly Dictionary<Mesh, MeshData> meshes = new Dictionary<Mesh, MeshData>();

		private readonly List<Roof> roofs = new List<Roof>();

		private readonly RaycastHit[] scratch = (RaycastHit[])(object)new RaycastHit[64];

		public readonly RainColumnCache VisualColumns = new RainColumnCache();

		private float highestRoof;

		private float nextEmptyRetry;

		private Transform root;

		private Vector3 previousPosition;

		private Vector3 previousScale;

		private Quaternion previousRotation;

		private static readonly Vector3[] ExposureOffsets = (Vector3[])(object)new Vector3[5]
		{
			Vector3.zero,
			Vector3.right * 0.28f,
			Vector3.left * 0.28f,
			Vector3.forward * 0.28f,
			Vector3.back * 0.28f
		};

		public long WorldQueries { get; private set; }

		public long TriangleTests { get; private set; }

		public int PreciseCanopies { get; private set; }

		public int ApproximateCanopies { get; private set; }

		public void SetRoot(Transform value)
		{
			//IL_0033: 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_0395: Unknown result type (might be due to invalid IL or missing references)
			//IL_039a: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_03b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_03be: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_0112: Unknown result type (might be due to invalid IL or missing references)
			//IL_0117: Unknown result type (might be due to invalid IL or missing references)
			//IL_0123: Unknown result type (might be due to invalid IL or missing references)
			//IL_0128: Unknown result type (might be due to invalid IL or missing references)
			//IL_0134: Unknown result type (might be due to invalid IL or missing references)
			//IL_0139: Unknown result type (might be due to invalid IL or missing references)
			//IL_0229: Unknown result type (might be due to invalid IL or missing references)
			//IL_022e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0232: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)root == (Object)(object)value && Object.op_Implicit((Object)(object)value) && (roofs.Count > 0 || Time.unscaledTime < nextEmptyRetry) && Vector3.Distance(value.position, previousPosition) < 0.001f && Quaternion.Angle(value.rotation, previousRotation) < 0.01f && value.lossyScale == previousScale)
			{
				return;
			}
			VisualColumns.Clear();
			if ((Object)(object)root != (Object)(object)value || !Object.op_Implicit((Object)(object)value))
			{
				meshes.Clear();
			}
			root = value;
			roofs.Clear();
			PreciseCanopies = 0;
			ApproximateCanopies = 0;
			highestRoof = 0f;
			if (!Object.op_Implicit((Object)(object)root))
			{
				return;
			}
			nextEmptyRetry = Time.unscaledTime + 5f;
			previousPosition = root.position;
			previousRotation = root.rotation;
			previousScale = root.lossyScale;
			HashSet<Renderer> hashSet = new HashSet<Renderer>();
			LODGroup[] componentsInChildren = ((Component)root).GetComponentsInChildren<LODGroup>(true);
			foreach (LODGroup val in componentsInChildren)
			{
				LOD[] lODs = val.GetLODs();
				if (lODs.Length == 0)
				{
					continue;
				}
				Renderer[] renderers = lODs[0].renderers;
				foreach (Renderer val2 in renderers)
				{
					if (Object.op_Implicit((Object)(object)val2))
					{
						hashSet.Add(val2);
					}
				}
			}
			MeshRenderer[] componentsInChildren2 = ((Component)root).GetComponentsInChildren<MeshRenderer>(true);
			foreach (MeshRenderer val3 in componentsInChildren2)
			{
				if (!((Component)val3).gameObject.activeInHierarchy || ((Object)val3).name.IndexOf("collider", StringComparison.OrdinalIgnoreCase) >= 0)
				{
					continue;
				}
				float num = highestRoof;
				Bounds bounds = ((Renderer)val3).bounds;
				highestRoof = Mathf.Max(num, ((Bounds)(ref bounds)).max.y);
				if ((!NamedCanopy(((Component)val3).transform, root) && !((Renderer)val3).sharedMaterials.Any((Material m) => Object.op_Implicit((Object)(object)m) && ((Object)m).name.IndexOf("M_Foliage Pine colony", StringComparison.OrdinalIgnoreCase) >= 0)) || (Object.op_Implicit((Object)(object)((Component)val3).GetComponentInParent<LODGroup>()) && !hashSet.Contains((Renderer)(object)val3)))
				{
					continue;
				}
				MeshFilter component = ((Component)val3).GetComponent<MeshFilter>();
				if (!Object.op_Implicit((Object)(object)component) || !Object.op_Implicit((Object)(object)component.sharedMesh))
				{
					continue;
				}
				Mesh sharedMesh = component.sharedMesh;
				if (!meshes.TryGetValue(sharedMesh, out var value2))
				{
					value2 = null;
					if (sharedMesh.isReadable)
					{
						try
						{
							value2 = new MeshData
							{
								vertices = sharedMesh.vertices.Select((Vector3 v) => new V3(v.x, v.y, v.z)).ToArray(),
								triangles = sharedMesh.triangles
							};
						}
						catch
						{
							value2 = null;
						}
					}
					meshes.Add(sharedMesh, value2);
				}
				roofs.Add(new Roof
				{
					bounds = ((Renderer)val3).bounds,
					inverse = ((Component)val3).transform.worldToLocalMatrix,
					forward = ((Component)val3).transform.localToWorldMatrix,
					data = value2
				});
				if (value2 != null)
				{
					PreciseCanopies++;
				}
				else
				{
					ApproximateCanopies++;
				}
			}
		}

		private static bool NamedCanopy(Transform node, Transform stop)
		{
			while (Object.op_Implicit((Object)(object)node) && (Object)(object)node != (Object)(object)stop)
			{
				string name = ((Object)node).name;
				if (name.IndexOf("foliage", StringComparison.OrdinalIgnoreCase) >= 0 || name.IndexOf("canopy", StringComparison.OrdinalIgnoreCase) >= 0)
				{
					return true;
				}
				node = node.parent;
			}
			return false;
		}

		private static bool Ignore(Collider collider)
		{
			return !Object.op_Implicit((Object)(object)collider) || collider.isTrigger || Object.op_Implicit((Object)(object)((Component)collider).GetComponentInParent<Bodypart>()) || Object.op_Implicit((Object)(object)((Component)collider).GetComponentInParent<Character>()) || Object.op_Implicit((Object)(object)((Component)collider).GetComponentInParent<Item>());
		}

		public bool WorldHit(Vector3 origin, Vector3 direction, float max, out RaycastHit nearest)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			WorldQueries++;
			nearest = default(RaycastHit);
			int num = Physics.RaycastNonAlloc(origin, direction, scratch, max, -1, (QueryTriggerInteraction)1);
			RaycastHit[] array = scratch;
			if (num == scratch.Length)
			{
				array = Physics.RaycastAll(origin, direction, max, -1, (QueryTriggerInteraction)1);
				num = array.Length;
			}
			bool result = false;
			float num2 = max;
			for (int i = 0; i < num; i++)
			{
				if (!Ignore(((RaycastHit)(ref array[i])).collider) && ((RaycastHit)(ref array[i])).distance <= num2)
				{
					nearest = array[i];
					num2 = ((RaycastHit)(ref array[i])).distance;
					result = true;
				}
			}
			return result;
		}

		public bool FirstRoof(Vector3 origin, float max, out float distance)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: 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_0057: 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_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_011b: Unknown result type (might be due to invalid IL or missing references)
			//IL_011c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0121: Unknown result type (might be due to invalid IL or missing references)
			//IL_0129: Unknown result type (might be due to invalid IL or missing references)
			//IL_012e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0133: Unknown result type (might be due to invalid IL or missing references)
			//IL_0137: Unknown result type (might be due to invalid IL or missing references)
			//IL_013f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0147: Unknown result type (might be due to invalid IL or missing references)
			//IL_0156: Unknown result type (might be due to invalid IL or missing references)
			//IL_015e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0166: Unknown result type (might be due to invalid IL or missing references)
			//IL_00db: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			RaycastHit nearest;
			bool flag = WorldHit(origin, Vector3.down, max, out nearest);
			distance = (flag ? ((RaycastHit)(ref nearest)).distance : max);
			foreach (Roof roof in roofs)
			{
				Bounds bounds = roof.bounds;
				if (origin.x < ((Bounds)(ref bounds)).min.x || origin.x > ((Bounds)(ref bounds)).max.x || origin.z < ((Bounds)(ref bounds)).min.z || origin.z > ((Bounds)(ref bounds)).max.z || origin.y - max > ((Bounds)(ref bounds)).max.y || origin.y < ((Bounds)(ref bounds)).min.y)
				{
					continue;
				}
				if (roof.data == null)
				{
					float num = origin.y - ((Bounds)(ref bounds)).max.y;
					if (num >= 0f && num < distance)
					{
						distance = num;
						flag = true;
					}
					continue;
				}
				Vector3 val = ((Matrix4x4)(ref roof.inverse)).MultiplyPoint3x4(origin);
				Vector3 val2 = ((Matrix4x4)(ref roof.inverse)).MultiplyVector(Vector3.down);
				V3 origin2 = new V3(val.x, val.y, val.z);
				V3 direction = new V3(val2.x, val2.y, val2.z);
				V3[] vertices = roof.data.vertices;
				int[] triangles = roof.data.triangles;
				for (int i = 0; i + 2 < triangles.Length; i += 3)
				{
					TriangleTests++;
					if (RainMath.Triangle(origin2, direction, vertices[triangles[i]], vertices[triangles[i + 1]], vertices[triangles[i + 2]], distance, out var distance2))
					{
						distance = (float)distance2;
						flag = true;
					}
				}
			}
			return flag;
		}

		public bool VisualLifetime(Vector3 point, float travel, float speed, out float lifetime)
		{
			//IL_0023: 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_002f: 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_0077: Unknown result type (might be due to invalid IL or missing references)
			lifetime = 0f;
			if (!VisualColumns.Get(point.x, point.z, point.y, delegate(float x, float z, float bandY)
			{
				//IL_0028: Unknown result type (might be due to invalid IL or missing references)
				float num = Mathf.Max(highestRoof + 2f, bandY + 544f);
				float distance;
				return FirstRoof(new Vector3(x, num, z), num - bandY + travel + 1f, out distance) ? (num - distance) : float.NegativeInfinity;
			}, out var height))
			{
				return false;
			}
			if (height >= point.y - 0.025f)
			{
				return false;
			}
			lifetime = Mathf.Min(travel, point.y - height - 0.025f) / speed;
			return lifetime >= 0.025f;
		}

		public bool SkyOpen(Vector3 point)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			float num = Mathf.Max(512f, highestRoof - point.y + 2f);
			float distance;
			return !FirstRoof(point + Vector3.up * num, num - 0.04f, out distance);
		}

		public bool OnBiome(Character c, Transform segment)
		{
			//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_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			RaycastHit nearest;
			return Object.op_Implicit((Object)(object)segment) && WorldHit(c.Center + Vector3.up * 0.1f, Vector3.down, 700f, out nearest) && ((Component)((RaycastHit)(ref nearest)).collider).transform.IsChildOf(segment);
		}

		public float Exposure(Character c)
		{
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: 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_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: 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)
			Bodypart val = ((IEnumerable<Bodypart>)c.refs.ragdoll.partList).FirstOrDefault((Func<Bodypart, bool>)((Bodypart p) => Object.op_Implicit((Object)(object)p) && (int)p.partType == 4));
			Rigidbody val2 = (Object.op_Implicit((Object)(object)val) ? val.Rig : null);
			Vector3 point = (Object.op_Implicit((Object)(object)val2) ? val2.worldCenterOfMass : (c.Center + Vector3.up * 0.65f)) + Vector3.up * 0.12f;
			return ExposureAt(point);
		}

		public float ExposureAt(Vector3 point)
		{
			//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_0017: 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_0019: Unknown result type (might be due to invalid IL or missing references)
			int num = 0;
			Vector3[] exposureOffsets = ExposureOffsets;
			foreach (Vector3 val in exposureOffsets)
			{
				if (SkyOpen(point + val))
				{
					num++;
				}
			}
			return (float)num / 5f;
		}
	}
	[BepInDependency("local.peak.poisonforest.solo", "0.5.2")]
	[BepInPlugin("local.peak.poisonforest.rain", "Thunderfen Poison Rain", "1.0.0")]
	public sealed class RainTrial : BaseUnityPlugin
	{
		[Serializable]
		public sealed class Settings
		{
			public float poisonPerSecond = 0.01f;

			public float wetSeconds = 45f;

			public float clearSeconds = 30f;

			public float warningSeconds = 8f;

			public float contactGraceSeconds = 1.5f;

			public float dropsPerSecond = 1200f;

			public float rainRadius = 8f;

			public float dropSpeed = 22f;

			public float emissionHeight = 14f;

			public float dropTravel = 36f;

			public float streakWidth = 0.04f;

			public float hazeStrength = 0.75f;

			public float hazeFadeSeconds = 4f;

			public float hazeGreenMix = 0.3f;

			public float hazeDensityMultiplier = 1f;

			public bool hazeEnabled = true;

			public bool skyEnabled = true;

			public float skyBrightness = 0.55f;

			public float skySaturation = 0.18f;

			public float skyCloudDensity = 0.85f;

			public float skySunDiskMultiplier = 0.1f;

			public float skyFadeSeconds = 4f;

			public float skyCloudScale = 0.38f;

			public float skyCloudTightness = 0.46f;

			public float cloudLightningMinSeconds = 3f;

			public float cloudLightningMaxSeconds = 6f;

			public bool cloudLightningEnabled = true;

			public bool reducedCloudFlashes = false;
		}

		[Serializable]
		private sealed class State
		{
			public double visualCpuMs;

			public double maxVisualCpuMs;

			public double weatherClock;

			public double weatherEpoch;

			public double weatherSecondsRemaining;

			public double overrideEndsAt;

			public long worldQueries;

			public long canopyTriangleTests;

			public long visualCacheHits;

			public long visualCacheQueries;

			public long visualCacheDeferred;

			public int visualCacheColumns;

			public string exposurePolicy;

			public bool stormCloudAssetsReady;

			public string stormCloudAssetsError;

			public string cloudLightningMessage;

			public bool cloudLightningReady;

			public int cloudLightningEvents;

			public float cloudLightningNextIn;

			public string utc;

			public string version;

			public string message;

			public string error;

			public string nativeRainSource;

			public string weatherMode;

			public string visibleShader;

			public string hazeSource;

			public string hazeError;

			public string skyShader;

			public bool summitProtected;

			public bool ready;

			public bool failed;

			public bool inRun;

			public bool insideCustomBiome;

			public bool raining;

			public bool visualsReady;

			public bool roomCompatible;

			public bool particleRendererEnabled;

			public bool visibleShaderSupported;

			public bool hazeNativeSource;

			public bool hazeFailed;

			public bool overcastSkyApplied;

			public bool overcastSkyMaterialApplied;

			public bool diffuseOvercastApplied;

			public Color diffuseOvercast;

			public float skyWeight;

			public float skyBrightness;

			public float skyCloudDensity;

			public Color skyTop;

			public Color skyMid;

			public Color skyBottom;

			public float exposure;

			public float poison;

			public float poisonPerSecond;

			public float lastDose;

			public float requestedPoison;

			public float hazeWeight;

			public float hazeWeatherBlend;

			public float hazeDensity;

			public Color hazeTint;

			public int preciseCanopies;

			public int approximateCanopies;

			public int emittedParticles;

			public int liveParticleCount;
		}

		public const string Id = "local.peak.poisonforest.rain";

		public const string Version = "1.0.0";

		private const string ProtocolVersion = "0.2.4";

		private const string RootId = "prototype/first-ridge";

		private const string ProtocolKey = "PF_RainTrial";

		private const string InsideKey = "PF_RainInside";

		private const string EpochKey = "PF_RainEpoch";

		private const string ModeKey = "PF_RainMode";

		private const string ModeUntilKey = "PF_RainModeUntil";

		public static RainTrial Instance;

		private readonly RainGeometry geometry = new RainGeometry();

		private readonly Random random = new Random();

		private Settings settings;

		private RainHaze haze;

		private CloudLightning clouds;

		private StormSkyAssets stormSky;

		private string folder;

		private string protocol;

		private string message = "Initializing";

		private string sourcePath;

		private string error;

		private Transform segment;

		private Transform floor;

		private Transform summit;

		private GameObject effects;

		private ParticleSystem rain;

		private AudioSource audio;

		private Material rainMaterial;

		private bool summitProtected;

		private bool ready;

		private bool failed;

		private bool inside;

		private bool wet;

		private bool active;

		private bool compatible;

		private bool lastPublishedInside;

		private int lastSegmentId;

		private int mode;

		private int emitted;

		private float nextPoll;

		private float nextSample;

		private float nextReport;

		private float lastSample;

		private float exposure;

		private float requestedPoison;

		private float emitBudget;

		private float lastDose;

		private double lastVisualCpuMs;

		private double maxVisualCpuMs;

		private double epoch;

		private double modeUntil;

		private int reportedPhase = -1;

		private Character exposureOwner;

		private double? continuousExposure;

		private bool RootActive => Object.op_Implicit((Object)(object)segment) && Object.op_Implicit((Object)(object)floor) && ((Component)floor).gameObject.activeInHierarchy;

		private void Awake()
		{
			Instance = this;
			folder = Path.Combine(Application.persistentDataPath, "PoisonForestRainTrial");
			Directory.CreateDirectory(folder);
			try
			{
				string path = Path.Combine(Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location), "PoisonForestRain.settings.json");
				byte[] bytes = File.ReadAllBytes(path);
				settings = JsonUtility.FromJson<Settings>(Encoding.UTF8.GetString(bytes));
				if (settings == null || !Valid(settings.poisonPerSecond, 0f, 0.1f) || !Valid(settings.wetSeconds, 1f, 600f) || !Valid(settings.clearSeconds, 1f, 600f) || !Valid(settings.warningSeconds, 0f, 120f) || !Valid(settings.contactGraceSeconds, 0.1f, 5f) || !Valid(settings.dropsPerSecond, 1f, 3000f) || !Valid(settings.rainRadius, 2f, 20f) || !Valid(settings.dropSpeed, 1f, 60f) || !Valid(settings.emissionHeight, 2f, 40f) || !Valid(settings.dropTravel, 5f, 100f) || !Valid(settings.streakWidth, 0.005f, 0.2f) || !Valid(settings.hazeStrength, 0f, 1f) || !Valid(settings.hazeFadeSeconds, 0.1f, 30f) || !Valid(settings.hazeGreenMix, 0f, 1f) || !Valid(settings.hazeDensityMultiplier, 0.1f, 3f) || !Valid(settings.skyBrightness, 0.2f, 1f) || !Valid(settings.skySaturation, 0f, 1f) || !Valid(settings.skyCloudDensity, 0f, 1f) || !Valid(settings.skySunDiskMultiplier, 0f, 1f) || !Valid(settings.skyFadeSeconds, 0.1f, 30f) || !Valid(settings.skyCloudScale, 0.05f, 2f) || !Valid(settings.skyCloudTightness, 0.05f, 1f) || !Valid(settings.cloudLightningMinSeconds, 3f, 120f) || !Valid(settings.cloudLightningMaxSeconds, settings.cloudLightningMinSeconds, 180f))
				{
					throw new InvalidOperationException("Invalid poison rain settings.");
				}
				protocol = "0.2.4:" + Sha(Encoding.UTF8.GetBytes(JsonUtility.ToJson((object)settings))).Substring(0, 12);
				haze = new RainHaze(settings, delegate(Exception e)
				{
					Log("haze-disabled", e.Message);
				});
				stormSky = new StormSkyAssets();
				if (stormSky.Ready)
				{
					haze.SetStormTemplate(stormSky.Template);
				}
				else
				{
					Log("storm-sky-assets", stormSky.Error);
				}
				clouds = new CloudLightning(settings);
				ready = true;
				lastSample = Time.time;
				Log("started", "version=1.0.0 poisonPerSecond=" + settings.poisonPerSecond.ToString("F4", CultureInfo.InvariantCulture) + " exposurePolicy=current-position-geometry; native rain gameplay scripts and global wind untouched.");
			}
			catch (Exception exception)
			{
				Fail(exception);
			}
		}

		private static string Sha(byte[] bytes)
		{
			using SHA256 sHA = SHA256.Create();
			return BitConverter.ToString(sHA.ComputeHash(bytes)).Replace("-", "");
		}

		private static bool Valid(float n, float low, float high)
		{
			return !float.IsNaN(n) && !float.IsInfinity(n) && n >= low && n <= high;
		}

		private static bool InRun()
		{
			//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)
			Scene sceneByName = SceneManager.GetSceneByName("WilIsland");
			return ((Scene)(ref sceneByName)).isLoaded;
		}

		private static string PathOf(Transform t)
		{
			string text = ((Object)t).name;
			while (Object.op_Implicit((Object)(object)t.parent))
			{
				t = t.parent;
				text = ((Object)t).name + "/" + text;
			}
			return text;
		}

		private void Update()
		{
			//IL_01e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_0203: Unknown result type (might be due to invalid IL or missing references)
			if (!ready || failed)
			{
				return;
			}
			try
			{
				Advertise();
				compatible = SharedWorld.Ready && CompatibleRoom();
				if (Time.unscaledTime >= nextPoll)
				{
					nextPoll = Time.unscaledTime + 1f;
					FindRoot();
					if (!Object.op_Implicit((Object)(object)rain) && RootActive)
					{
						BuildVisuals();
					}
				}
				Character localCharacter = Character.localCharacter;
				if (Time.time >= nextSample)
				{
					nextSample = Time.time + 0.2f;
					float num = Mathf.Min(0.3f, Mathf.Max(0f, Time.time - lastSample));
					lastSample = Time.time;
					inside = compatible && Object.op_Implicit((Object)(object)localCharacter) && (Object)(object)localCharacter.data != (Object)null && localCharacter.refs != null && Object.op_Implicit((Object)(object)localCharacter.refs.ragdoll) && Object.op_Implicit((Object)(object)localCharacter.refs.afflictions) && localCharacter.refs.ragdoll.partList.Count > 0 && !localCharacter.data.dead && RootActive && geometry.OnBiome(localCharacter, segment);
					PublishInside();
					UpdateHostClock();
					ReadWeather();
					wet = RainMath.Wet(PhotonNetwork.Time, epoch, settings.wetSeconds, settings.clearSeconds, mode);
					summitProtected = inside && Object.op_Implicit((Object)(object)summit) && RainMath.SummitProtected(segment.InverseTransformPoint(localCharacter.Center).y, segment.InverseTransformPoint(summit.position).y);
					active = inside && wet && !summitProtected;
					int num2 = ((!inside) ? (-1) : (wet ? 1 : 0));
					if (num2 != reportedPhase)
					{
						reportedPhase = num2;
						Log("weather-phase", "inside=" + inside + " raining=" + wet + " mode=" + ModeName(mode) + " clock=" + PhotonNetwork.Time.ToString("F3", CultureInfo.InvariantCulture) + " epoch=" + epoch.ToString("F3", CultureInfo.InvariantCulture) + " remaining=" + WeatherRemaining().ToString("F1", CultureInfo.InvariantCulture));
					}
					exposure = ((inside && !summitProtected) ? geometry.Exposure(localCharacter) : 0f);
					if ((Object)(object)exposureOwner != (Object)(object)localCharacter)
					{
						exposureOwner = localCharacter;
						continuousExposure = null;
					}
					lastDose = (float)RainMath.ContinuousExposureDose(settings.poisonPerSecond, num, active, exposure, ref continuousExposure);
					if (lastDose > 0f && localCharacter.refs != null && Object.op_Implicit((Object)(object)localCharacter.refs.afflictions) && localCharacter.refs.afflictions.AddStatus((STATUSTYPE)3, lastDose, false, false, true, false, false))
					{
						requestedPoison += lastDose;
					}
					message = ((!InRun()) ? "Waiting for a run" : ((!compatible) ? "Waiting for matching rain trial on every player" : ((!RootActive) ? "Waiting for Poison Forest" : ((!inside) ? "Rain applies inside Poison Forest" : (summitProtected ? "Summit - sheltered from poison weather" : (wet ? ((exposure <= 0f) ? "Sheltered from rain" : ((continuousExposure < 2.0) ? "Exposed to poison rain - grace period" : "Exposed to poison rain - gaining poison")) : (settings.skyEnabled ? "Overcast - no rain" : "Clear weather")))))));
				}
				Report();
			}
			catch (Exception exception)
			{
				Fail(exception);
			}
		}

		private void LateUpdate()
		{
			//IL_0188: Unknown result type (might be due to invalid IL or missing references)
			//IL_018d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0195: Unknown result type (might be due to invalid IL or missing references)
			//IL_019c: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01af: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_027a: Unknown result type (might be due to invalid IL or missing references)
			//IL_035b: Unknown result type (might be due to invalid IL or missing references)
			//IL_03b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_03b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_03bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0408: Unknown result type (might be due to invalid IL or missing references)
			//IL_0410: Unknown result type (might be due to invalid IL or missing references)
			//IL_041a: Unknown result type (might be due to invalid IL or missing references)
			//IL_042a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0468: Unknown result type (might be due to invalid IL or missing references)
			//IL_046d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0478: Unknown result type (might be due to invalid IL or missing references)
			//IL_047a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0482: Unknown result type (might be due to invalid IL or missing references)
			if (!ready || failed)
			{
				return;
			}
			Stopwatch stopwatch = Stopwatch.StartNew();
			try
			{
				Character localCharacter = Character.localCharacter;
				bool inBiome = RootActive && Object.op_Implicit((Object)(object)localCharacter) && InRun() && (inside || Object.op_Implicit((Object)(object)ThunderfenMist.CurrentRoot));
				DayNightManager instance = DayNightManager.instance;
				if (haze != null)
				{
					haze.ConfigureLighting(Object.op_Implicit((Object)(object)instance) ? instance.sun : null, Object.op_Implicit((Object)(object)instance) ? instance.moon : null, Object.op_Implicit((Object)(object)instance) ? ThunderfenDayNight.Daylight(instance.timeOfDay) : 1f);
					haze.Tick(inBiome, inside && wet && !summitProtected, Time.deltaTime);
				}
				if (clouds != null)
				{
					clouds.Tick(inside && RootActive && compatible && Object.op_Implicit((Object)(object)localCharacter) && InRun() && settings.skyEnabled, Time.unscaledTime);
				}
				if (haze != null && clouds != null)
				{
					haze.StormCloudTime = Time.unscaledTime;
					haze.StormFlashStrength = clouds.Glow;
					Vector3 glowDirection = clouds.GlowDirection;
					haze.StormFlash = new Vector4(glowDirection.x, glowDirection.y, glowDirection.z, 0f);
				}
				if (!active || !Object.op_Implicit((Object)(object)localCharacter) || !Object.op_Implicit((Object)(object)rain))
				{
					if (Object.op_Implicit((Object)(object)rain) && rain.isPlaying)
					{
						rain.Stop(true, (ParticleSystemStopBehavior)0);
					}
					if (Object.op_Implicit((Object)(object)audio) && audio.isPlaying)
					{
						audio.Stop();
					}
					emitBudget = 0f;
					return;
				}
				if (!rain.isPlaying)
				{
					rain.Play();
				}
				effects.transform.position = localCharacter.Center;
				geometry.VisualColumns.BeginFrame();
				if (Object.op_Implicit((Object)(object)audio))
				{
					if (!audio.isPlaying)
					{
						audio.Play();
					}
					audio.volume = Mathf.Lerp(audio.volume, (exposure > 0f) ? 0.4f : 0.12f, Time.deltaTime * 3f);
				}
				emitBudget += settings.dropsPerSecond * Time.deltaTime;
				int num = Mathf.Min(96, (int)emitBudget);
				emitBudget = Mathf.Min(96f, emitBudget - (float)num);
				for (int i = 0; i < num; i++)
				{
					Vector3 val = localCharacter.Center + new Vector3(((float)random.NextDouble() * 2f - 1f) * settings.rainRadius, settings.emissionHeight, ((float)random.NextDouble() * 2f - 1f) * settings.rainRadius);
					if (geometry.VisualLifetime(val, settings.dropTravel, settings.dropSpeed, out var lifetime) && !(lifetime < 0.025f))
					{
						EmitParams val2 = default(EmitParams);
						((EmitParams)(ref val2)).position = val;
						((EmitParams)(ref val2)).velocity = Vector3.down * settings.dropSpeed;
						((EmitParams)(ref val2)).startLifetime = lifetime;
						((EmitParams)(ref val2)).startSize = settings.streakWidth;
						((EmitParams)(ref val2)).startColor = Color32.op_Implicit(new Color(0.78f, 0.94f, 0.8f, 0.85f));
						EmitParams val3 = val2;
						rain.Emit(val3, 1);
						emitted++;
					}
				}
			}
			catch (Exception exception)
			{
				Fail(exception);
			}
			finally
			{
				stopwatch.Stop();
				lastVisualCpuMs = stopwatch.Elapsed.TotalMilliseconds;
				maxVisualCpuMs = Math.Max(maxVisualCpuMs, lastVisualCpuMs);
			}
		}

		private void FindRoot()
		{
			//IL_00aa: 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_012a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0131: Expected O, but got Unknown
			//IL_025f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0264: Unknown result type (might be due to invalid IL or missing references)
			//IL_027d: Expected O, but got Unknown
			//IL_027e: Unknown result type (might be due to invalid IL or missing references)
			//IL_028f: Expected O, but got Unknown
			//IL_0290: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a9: Expected O, but got Unknown
			//IL_02b1: Expected O, but got Unknown
			if (!InRun())
			{
				segment = null;
				floor = null;
				summit = null;
				summitProtected = false;
				geometry.SetRoot(null);
				inside = false;
				active = false;
				return;
			}
			if (Object.op_Implicit((Object)(object)segment) && Object.op_Implicit((Object)(object)floor))
			{
				geometry.SetRoot((Object.op_Implicit((Object)(object)floor) && ((Component)floor).gameObject.activeInHierarchy) ? segment : null);
				return;
			}
			Scene sceneByName = SceneManager.GetSceneByName("WilIsland");
			GameObject val = ((IEnumerable<GameObject>)((Scene)(ref sceneByName)).GetRootGameObjects()).FirstOrDefault((Func<GameObject, bool>)((GameObject g) => ((Object)g).name == "Map"));
			if (!Object.op_Implicit((Object)(object)val))
			{
				return;
			}
			Transform val2 = val.transform.Find("Global");
			if (!Object.op_Implicit((Object)(object)val2))
			{
				return;
			}
			foreach (Transform item in val2)
			{
				Transform val3 = item;
				if (((Object)val3).name.IndexOf("prototype/first-ridge", StringComparison.Ordinal) < 0)
				{
					continue;
				}
				Transform val4 = (Transform)(Object.op_Implicit((Object)(object)val3.Find("FloorRoot/RootsTerrain")) ? ((object)val3) : ((object)((IEnumerable<Transform>)((Component)val3).GetComponentsInChildren<Transform>(true)).FirstOrDefault((Func<Transform, bool>)((Transform x) => Object.op_Implicit((Object)(object)x.Find("FloorRoot/RootsTerrain"))))));
				if (!Object.op_Implicit((Object)(object)val4))
				{
					continue;
				}
				segment = val4;
				floor = segment.Find("FloorRoot");
				summit = segment.Find("CampfireRoot");
				geometry.SetRoot((Object.op_Implicit((Object)(object)floor) && ((Component)floor).gameObject.activeInHierarchy) ? segment : null);
				if (lastSegmentId != ((Object)segment).GetInstanceID())
				{
					lastSegmentId = ((Object)segment).GetInstanceID();
					if (PhotonNetwork.InRoom && PhotonNetwork.IsMasterClient)
					{
						Room currentRoom = PhotonNetwork.CurrentRoom;
						Hashtable val5 = new Hashtable();
						((Dictionary<object, object>)val5).Add((object)"PF_RainEpoch", (object)0.0);
						((Dictionary<object, object>)val5).Add((object)"PF_RainMode", (object)0);
						((Dictionary<object, object>)val5).Add((object)"PF_RainModeUntil", (object)0.0);
						currentRoom.SetCustomProperties(val5, (Hashtable)null, (WebFlags)null);
					}
					Log("biome-found", "Canopies precise=" + geometry.PreciseCanopies + " approximate=" + geometry.ApproximateCanopies + " root=" + PathOf(segment));
				}
				break;
			}
		}

		private void Advertise()
		{
			//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_005b: Expected O, but got Unknown
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Expected O, but got Unknown
			//IL_0075: Expected O, but got Unknown
			if (PhotonNetwork.LocalPlayer != null && (!(PhotonNetwork.LocalPlayer.CustomProperties[(object)"PF_RainTrial"] is string text) || text != protocol))
			{
				Player localPlayer = PhotonNetwork.LocalPlayer;
				Hashtable val = new Hashtable();
				((Dictionary<object, object>)val).Add((object)"PF_RainTrial", (object)protocol);
				((Dictionary<object, object>)val).Add((object)"PF_RainInside", (object)false);
				localPlayer.SetCustomProperties(val, (Hashtable)null, (WebFlags)null);
				lastPublishedInside = false;
			}
		}

		private bool CompatibleRoom()
		{
			if (!PhotonNetwork.InRoom)
			{
				return false;
			}
			foreach (Player item in PhotonNetwork.PlayerList.Where((Player p) => !p.IsInactive))
			{
				if (!(item.CustomProperties[(object)"PF_RainTrial"] is string text) || text != protocol)
				{
					return false;
				}
			}
			return true;
		}

		private void PublishInside()
		{
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Expected O, but got Unknown
			//IL_005c: Expected O, but got Unknown
			if (PhotonNetwork.InRoom && PhotonNetwork.LocalPlayer != null && inside != lastPublishedInside)
			{
				lastPublishedInside = inside;
				Player localPlayer = PhotonNetwork.LocalPlayer;
				Hashtable val = new Hashtable();
				((Dictionary<object, object>)val).Add((object)"PF_RainInside", (object)inside);
				localPlayer.SetCustomProperties(val, (Hashtable)null, (WebFlags)null);
			}
		}

		private int ReadMode()
		{
			if (!PhotonNetwork.InRoom)
			{
				return 0;
			}
			return (((RoomInfo)PhotonNetwork.CurrentRoom).CustomProperties[(object)"PF_RainMode"] is int num) ? num : 0;
		}

		private void UpdateHostClock()
		{
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Expected O, but got Unknown
			//IL_0092: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Expected O, but got Unknown
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Expected O, but got Unknown
			//IL_00d6: Expected O, but got Unknown
			//IL_014b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0150: Unknown result type (might be due to invalid IL or missing references)
			//IL_0169: Expected O, but got Unknown
			//IL_0171: Expected O, but got Unknown
			//IL_01cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f2: Expected O, but got Unknown
			//IL_01fa: Expected O, but got Unknown
			if (!PhotonNetwork.InRoom || !PhotonNetwork.IsMasterClient || !compatible)
			{
				return;
			}
			int num = ReadMode();
			double until = ((((RoomInfo)PhotonNetwork.CurrentRoom).CustomProperties[(object)"PF_RainModeUntil"] is double num2) ? num2 : 0.0);
			if (RainMath.OverrideExpired(PhotonNetwork.Time, num, until))
			{
				Room currentRoom = PhotonNetwork.CurrentRoom;
				Hashtable val = new Hashtable();
				((Dictionary<object, object>)val).Add((object)"PF_RainMode", (object)0);
				((Dictionary<object, object>)val).Add((object)"PF_RainModeUntil", (object)0.0);
				((Dictionary<object, object>)val).Add((object)"PF_RainEpoch", (object)(PhotonNetwork.Time + (double)settings.clearSeconds));
				currentRoom.SetCustomProperties(val, (Hashtable)null, (WebFlags)null);
				Log("weather-mode", "Timed test override ended; automatic weather resumes after clear interval");
			}
			double num3 = ((((RoomInfo)PhotonNetwork.CurrentRoom).CustomProperties[(object)"PF_RainEpoch"] is double num4) ? num4 : 0.0);
			if (!RootActive)
			{
				if (num3 != 0.0)
				{
					Room currentRoom2 = PhotonNetwork.CurrentRoom;
					Hashtable val2 = new Hashtable();
					((Dictionary<object, object>)val2).Add((object)"PF_RainEpoch", (object)0.0);
					currentRoom2.SetCustomProperties(val2, (Hashtable)null, (WebFlags)null);
				}
				return;
			}
			bool flag = inside || PhotonNetwork.PlayerList.Any(delegate(Player p)
			{
				object obj = p.CustomProperties[(object)"PF_RainInside"];
				bool flag2 = default(bool);
				int num5;
				if (obj is bool)
				{
					flag2 = (bool)obj;
					num5 = 1;
				}
				else
				{
					num5 = 0;
				}
				return (byte)((uint)num5 & (flag2 ? 1u : 0u)) != 0;
			});
			if (num3 == 0.0 && flag)
			{
				Room currentRoom3 = PhotonNetwork.CurrentRoom;
				Hashtable val3 = new Hashtable();
				((Dictionary<object, object>)val3).Add((object)"PF_RainEpoch", (object)(PhotonNetwork.Time + (double)settings.warningSeconds));
				currentRoom3.SetCustomProperties(val3, (Hashtable)null, (WebFlags)null);
				Log("weather-start", "Automatic rain begins after " + settings.warningSeconds + " seconds, then " + settings.wetSeconds + " wet / " + settings.clearSeconds + " clear.");
			}
		}

		private void ReadWeather()
		{
			mode = ReadMode();
			modeUntil = ((PhotonNetwork.InRoom && ((RoomInfo)PhotonNetwork.CurrentRoom).CustomProperties[(object)"PF_RainModeUntil"] is double num) ? num : 0.0);
			epoch = ((PhotonNetwork.InRoom && ((RoomInfo)PhotonNetwork.CurrentRoom).CustomProperties[(object)"PF_RainEpoch"] is double num2) ? num2 : 0.0);
		}

		private double WeatherRemaining()
		{
			return RainMath.Remaining(PhotonNetwork.Time, epoch, settings.wetSeconds, settings.clearSeconds, mode, modeUntil);
		}

		private static string ModeName(int value)
		{
			return value switch
			{
				2 => "Timed test clear", 
				1 => "Timed test rain", 
				_ => "Automatic", 
			};
		}

		private void BuildVisuals()
		{
			//IL_023b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0245: Expected O, but got Unknown
			//IL_026b: 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_02f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_030a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0363: Unknown result type (might be due to invalid IL or missing references)
			//IL_0368: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_03b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_03d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_03f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_040e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0413: Unknown result type (might be due to invalid IL or missing references)
			//IL_0424: Unknown result type (might be due to invalid IL or missing references)
			//IL_0429: Unknown result type (might be due to invalid IL or missing references)
			//IL_043a: Unknown result type (might be due to invalid IL or missing references)
			//IL_043f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0450: Unknown result type (might be due to invalid IL or missing references)
			//IL_0455: Unknown result type (might be due to invalid IL or missing references)
			//IL_0466: Unknown result type (might be due to invalid IL or missing references)
			//IL_046b: Unknown result type (might be due to invalid IL or missing references)
			//IL_047c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0481: Unknown result type (might be due to invalid IL or missing references)
			//IL_0492: Unknown result type (might be due to invalid IL or missing references)
			//IL_0497: Unknown result type (might be due to invalid IL or missing references)
			//IL_04a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_04ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_04be: Unknown result type (might be due to invalid IL or missing references)
			//IL_04c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_04d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_04d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_04ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_04ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_0518: Unknown result type (might be due to invalid IL or missing references)
			//IL_0533: Unknown result type (might be due to invalid IL or missing references)
			//IL_05ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_05f6: Expected O, but got Unknown
			//IL_0626: Unknown result type (might be due to invalid IL or missing references)
			ParticleSystem val = ((IEnumerable<ParticleSystem>)Resources.FindObjectsOfTypeAll<ParticleSystem>()).FirstOrDefault((Func<ParticleSystem, bool>)((ParticleSystem p) => Object.op_Implicit((Object)(object)p) && PathOf(((Component)p).transform).Contains("RainStorm/") && PathOf(((Component)p).transform).IndexOf("Tropics", StringComparison.OrdinalIgnoreCase) >= 0));
			Material val2 = (Material)(Object.op_Implicit((Object)(object)val) ? ((object)((Renderer)((Component)val).GetComponent<ParticleSystemRenderer>()).sharedMaterial) : ((object)((IEnumerable<Material>)Resources.FindObjectsOfTypeAll<Material>()).FirstOrDefault((Func<Material, bool>)((Material m) => Object.op_Implicit((Object)(object)m) && ((Object)m).name.StartsWith("M_VFX_Rain", StringComparison.OrdinalIgnoreCase)))));
			Shader val3 = Shader.Find("FirstRidge/CampfireParticle") ?? ((IEnumerable<Shader>)Resources.FindObjectsOfTypeAll<Shader>()).FirstOrDefault((Func<Shader, bool>)((Shader s) => Object.op_Implicit((Object)(object)s) && ((Object)s).name == "FirstRidge/CampfireParticle"));
			if (Object.op_Implicit((Object)(object)val3) && val3.isSupported && Object.op_Implicit((Object)(object)val2))
			{
				FogConfig source = (FogConfig)(Object.op_Implicit((Object)(object)val) ? ((object)((Component)val).GetComponentInParent<FogConfig>(true)) : ((object)((IEnumerable<FogConfig>)Resources.FindObjectsOfTypeAll<FogConfig>()).FirstOrDefault((Func<FogConfig, bool>)((FogConfig f) => Object.op_Implicit((Object)(object)f) && PathOf(((Component)f).transform).Contains("RainStorm") && PathOf(((Component)f).transform).Contains("Tropics")))));
				if (haze != null)
				{
					haze.Configure(source);
				}
				Log("haze-configured", "source=" + ((haze != null) ? haze.Source : "none") + " native=" + (haze != null && haze.NativeSource) + " strength=" + settings.hazeStrength + " fade=" + settings.hazeFadeSeconds + " greenMix=" + settings.hazeGreenMix + " density=" + ((haze != null) ? haze.TargetDensity : 0f));
				sourcePath = (Object.op_Implicit((Object)(object)val) ? PathOf(((Component)val).transform) : "Native M_VFX_Rain material (particle-template fallback)");
				effects = new GameObject("PF_PoisonRain_Visuals");
				effects.SetActive(false);
				Object.DontDestroyOnLoad((Object)(object)effects);
				GameObject val4 = (GameObject)(Object.op_Implicit((Object)(object)val) ? ((object)Object.Instantiate<GameObject>(((Component)val).gameObject, effects.transform)) : ((object)new GameObject("PF_PoisonRain_Drops")));
				if (!Object.op_Implicit((Object)(object)val))
				{
					val4.transform.SetParent(effects.transform, false);
					val4.AddComponent<ParticleSystem>();
				}
				((Object)val4).name = "PF_PoisonRain_Drops";
				val4.layer = 0;
				val4.tag = "Untagged";
				val4.transform.localPosition = Vector3.zero;
				val4.transform.localRotation = Quaternion.identity;
				val4.transform.localScale = Vector3.one;
				MonoBehaviour[] componentsInChildren = val4.GetComponentsInChildren<MonoBehaviour>(true);
				foreach (MonoBehaviour val5 in componentsInChildren)
				{
					Object.DestroyImmediate((Object)(object)val5);
				}
				rain = val4.GetComponent<ParticleSystem>();
				rain.Stop(true, (ParticleSystemStopBehavior)0);
				MainModule main = rain.main;
				((MainModule)(ref main)).playOnAwake = false;
				((MainModule)(ref main)).stopAction = (ParticleSystemStopAction)0;
				((MainModule)(ref main)).cullingMode = (ParticleSystemCullingMode)3;
				((MainModule)(ref main)).loop = true;
				((MainModule)(ref main)).simulationSpace = (ParticleSystemSimulationSpace)1;
				((MainModule)(ref main)).scalingMode = (ParticleSystemScalingMode)1;
				((MainModule)(ref main)).startSpeed = MinMaxCurve.op_Implicit(0f);
				((MainModule)(ref main)).startLifetime = MinMaxCurve.op_Implicit(2f);
				((MainModule)(ref main)).startSize = MinMaxCurve.op_Implicit(settings.streakWidth);
				((MainModule)(ref main)).maxParticles = 5000;
				((MainModule)(ref main)).gravityModifier = MinMaxCurve.op_Implicit(0f);
				((MainModule)(ref main)).simulationSpeed = 1f;
				EmissionModule emission = rain.emission;
				((EmissionModule)(ref emission)).enabled = false;
				ShapeModule shape = rain.shape;
				((ShapeModule)(ref shape)).enabled = false;
				ColorOverLifetimeModule colorOverLifetime = rain.colorOverLifetime;
				((ColorOverLifetimeModule)(ref colorOverLifetime)).enabled = false;
				SizeOverLifetimeModule sizeOverLifetime = rain.sizeOverLifetime;
				((SizeOverLifetimeModule)(ref sizeOverLifetime)).enabled = false;
				VelocityOverLifetimeModule velocityOverLifetime = rain.velocityOverLifetime;
				((VelocityOverLifetimeModule)(ref velocityOverLifetime)).enabled = false;
				ForceOverLifetimeModule forceOverLifetime = rain.forceOverLifetime;
				((ForceOverLifetimeModule)(ref forceOverLifetime)).enabled = false;
				ExternalForcesModule externalForces = rain.externalForces;
				((ExternalForcesModule)(ref externalForces)).enabled = false;
				NoiseModule noise = rain.noise;
				((NoiseModule)(ref noise)).enabled = false;
				LimitVelocityOverLifetimeModule limitVelocityOverLifetime = rain.limitVelocityOverLifetime;
				((LimitVelocityOverLifetimeModule)(ref limitVelocityOverLifetime)).enabled = false;
				InheritVelocityModule inheritVelocity = rain.inheritVelocity;
				((InheritVelocityModule)(ref inheritVelocity)).enabled = false;
				CollisionModule collision = rain.collision;
				((CollisionModule)(ref collision)).enabled = false;
				((CollisionModule)(ref collision)).type = (ParticleSystemCollisionType)1;
				((CollisionModule)(ref collision)).mode = (ParticleSystemCollisionMode)0;
				((CollisionModule)(ref collision)).quality = (ParticleSystemCollisionQuality)0;
				((CollisionModule)(ref collision)).collidesWith = LayerMask.op_Implicit(-1);
				((CollisionModule)(ref collision)).enableDynamicColliders = true;
				((CollisionModule)(ref collision)).lifetimeLoss = MinMaxCurve.op_Implicit(1f);
				((CollisionModule)(ref collision)).sendCollisionMessages = true;
				((CollisionModule)(ref collision)).colliderForce = 0f;
				((CollisionModule)(ref collision)).radiusScale = 0.025f / settings.streakWidth;
				ParticleSystemRenderer component = ((Component)rain).GetComponent<ParticleSystemRenderer>();
				((Renderer)component).enabled = true;
				((Renderer)component).forceRenderingOff = false;
				component.renderMode = (ParticleSystemRenderMode)1;
				component.lengthScale = 3f;
				component.velocityScale = 0.025f;
				component.cameraVelocityScale = 0f;
				component.enableGPUInstancing = false;
				component.SetActiveVertexStreams(new List<ParticleSystemVertexStream>
				{
					(ParticleSystemVertexStream)0,
					(ParticleSystemVertexStream)3,
					(ParticleSystemVertexStream)4
				});
				rainMaterial = new Material(val3);
				((Object)rainMaterial).name = "PF_PoisonRain_VisibleStreaks";
				rainMaterial.SetColor("_BaseColor", new Color(0.85f, 0.96f, 0.9f, 0.85f));
				rainMaterial.renderQueue = 3000;
				((Renderer)component).sharedMaterial = rainMaterial;
				val4.SetActive(true);
				AudioClip val6 = ((IEnumerable<AudioClip>)Resources.FindObjectsOfTypeAll<AudioClip>()).FirstOrDefault((Func<AudioClip, bool>)((AudioClip a) => Object.op_Implicit((Object)(object)a) && ((Object)a).name == "Au_Ambience_Rain_Heavy"));
				if (Object.op_Implicit((Object)(object)val6))
				{
					audio = effects.AddComponent<AudioSource>();
					audio.clip = val6;
					audio.loop = true;
					audio.playOnAwake = false;
					audio.spatialBlend = 0f;
					audio.volume = 0f;
				}
				effects.SetActive(true);
				Log("visuals-ready", "Cloned particle-only source " + sourcePath + "; visibleShader=" + ((Object)val3).name + "; streakWidth=" + settings.streakWidth + "; native audio=" + (Object.op_Implicit((Object)(object)val6) ? ((Object)val6).name : "not loaded") + "; visual-only particles; exact sky exposure drives poison.");
			}
		}

		private void Report()
		{
			//IL_0328: Unknown result type (might be due to invalid IL or missing references)
			//IL_031b: Unknown result type (might be due to invalid IL or missing references)
			//IL_032d: Unknown result type (might be due to invalid IL or missing references)
			//IL_03e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_03d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_03e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0439: Unknown result type (might be due to invalid IL or missing references)
			//IL_042c: Unknown result type (might be due to invalid IL or missing references)
			//IL_043e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0459: Unknown result type (might be due to invalid IL or missing references)
			//IL_044c: Unknown result type (might be due to invalid IL or missing references)
			//IL_045e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0479: Unknown result type (might be due to invalid IL or missing references)
			//IL_046c: Unknown result type (might be due to invalid IL or missing references)
			//IL_047e: Unknown result type (might be due to invalid IL or missing references)
			if (RuntimeDiagnostics.PeriodicSnapshots && !(Time.unscaledTime < nextReport))
			{
				nextReport = Time.unscaledTime + 1f;
				Character localCharacter = Character.localCharacter;
				float poison = ((Object.op_Implicit((Object)(object)localCharacter) && localCharacter.refs != null && Object.op_Implicit((Object)(object)localCharacter.refs.afflictions)) ? localCharacter.refs.afflictions.GetCurrentStatus((STATUSTYPE)3) : 0f);
				string contents = JsonUtility.ToJson((object)new State
				{
					weatherClock = PhotonNetwork.Time,
					weatherEpoch = epoch,
					weatherSecondsRemaining = WeatherRemaining(),
					overrideEndsAt = modeUntil,
					visualCpuMs = lastVisualCpuMs,
					maxVisualCpuMs = maxVisualCpuMs,
					worldQueries = geometry.WorldQueries,
					canopyTriangleTests = geometry.TriangleTests,
					visualCacheHits = geometry.VisualColumns.Hits,
					visualCacheQueries = geometry.VisualColumns.Queries,
					visualCacheDeferred = geometry.VisualColumns.Deferred,
					visualCacheColumns = geometry.VisualColumns.Count,
					exposurePolicy = "current-position-geometry",
					utc = DateTime.UtcNow.ToString("O"),
					version = "1.0.0",
					stormCloudAssetsReady = (stormSky != null && stormSky.Ready),
					stormCloudAssetsError = ((stormSky != null) ? stormSky.Error : null),
					cloudLightningMessage = ((clouds != null) ? clouds.Message : null),
					cloudLightningReady = (clouds != null && clouds.Ready),
					cloudLightningEvents = ((clouds != null) ? clouds.Events : 0),
					cloudLightningNextIn = ((clouds != null) ? clouds.NextIn : 0f),
					message = message,
					error = error,
					nativeRainSource = sourcePath,
					hazeSource = ((haze != null) ? haze.Source : null),
					hazeError = ((haze != null) ? haze.Error : null),
					hazeNativeSource = (haze != null && haze.NativeSource),
					hazeFailed = (haze != null && haze.Failed),
					hazeWeight = ((haze != null) ? ((float)haze.Weight) : 0f),
					hazeWeatherBlend = ((haze != null) ? haze.LastAppliedBlend : 0f),
					hazeDensity = ((haze != null) ? haze.TargetDensity : 0f),
					hazeTint = ((haze != null) ? haze.TargetTint : Color.clear),
					skyShader = ((haze != null) ? haze.SkyShader : null),
					skyWeight = ((haze != null) ? ((float)haze.SkyWeight) : 0f),
					skyBrightness = ((settings != null) ? settings.skyBrightness : 0f),
					skyCloudDensity = ((haze != null) ? haze.LastCloudDensity : 0f),
					diffuseOvercastApplied = (haze != null && haze.LastDiffuseApplied),
					diffuseOvercast = ((haze != null) ? haze.LastDiffuse : Color.clear),
					overcastSkyApplied = (haze != null && haze.LastSkyApplied),
					overcastSkyMaterialApplied = (haze != null && haze.LastSkyMaterialApplied),
					skyTop = ((haze != null) ? haze.LastSkyTop : Color.clear),
					skyMid = ((haze != null) ? haze.LastSkyMid : Color.clear),
					skyBottom = ((haze != null) ? haze.LastSkyBottom : Color.clear),
					weatherMode = ModeName(mode),
					visibleShader = ((Object.op_Implicit((Object)(object)rainMaterial) && Object.op_Implicit((Object)(object)rainMaterial.shader)) ? ((Object)rainMaterial.shader).name : null),
					visibleShaderSupported = (Object.op_Implicit((Object)(object)rainMaterial) && Object.op_Implicit((Object)(object)rainMaterial.shader) && rainMaterial.shader.isSupported),
					particleRendererEnabled = (Object.op_Implicit((Object)(object)rain) && ((Renderer)((Component)rain).GetComponent<ParticleSystemRenderer>()).enabled),
					liveParticleCount = (Object.op_Implicit((Object)(object)rain) ? rain.particleCount : 0),
					ready = ready,
					failed = failed,
					inRun = InRun(),
					insideCustomBiome = inside,
					summitProtected = summitProtected,
					raining = wet,
					visualsReady = Object.op_Implicit((Object)(object)rain),
					roomCompatible = compatible,
					exposure = exposure,
					poison = poison,
					poisonPerSecond = ((settings != null) ? settings.poisonPerSecond : 0f),
					lastDose = lastDose,
					requestedPoison = requestedPoison,
					preciseCanopies = geometry.PreciseCanopies,
					approximateCanopies = geometry.ApproximateCanopies,
					emittedParticles = emitted
				}, true);
				File.WriteAllText(Path.Combine(folder, "rain-state.json"), contents);
				if (RootActive && (inside || Object.op_Implicit((Object)(object)ThunderfenMist.CurrentRoot)))
				{
					File.WriteAllText(Path.Combine(folder, "rain-last-active.json"), contents);
				}
			}
		}

		private void Log(string kind, string text)
		{
			((BaseUnityPlugin)this).Logger.LogInfo((object)(kind + ": " + text));
			if (RuntimeDiagnostics.PeriodicSnapshots)
			{
				File.AppendAllText(Path.Combine(folder, "events.tsv"), DateTime.UtcNow.ToString("O") + "\t" + kind + "\t" + text.Replace('\t', ' ').Replace('\n', ' ') + "\n");
			}
		}

		private void Fail(Exception exception)
		{
			failed = true;
			ready = false;
			active = false;
			error = exception.ToString();
			message = "Rain trial stopped; see rain-state.json";
			((BaseUnityPlugin)this).Logger.LogError((object)error);
			if (haze != null)
			{
				haze.Dispose();
			}
			if (clouds != null)
			{
				clouds.Dispose();
			}
			if (stormSky != null)
			{
				stormSky.Dispose();
			}
			if (Object.op_Implicit((Object)(object)rain))
			{
				rain.Stop(true, (ParticleSystemStopBehavior)0);
			}
			if (Object.op_Implicit((Object)(object)audio))
			{
				audio.Stop();
			}
			nextReport = 0f;
			try
			{
				Report();
			}
			catch
			{
			}
		}

		private void OnDestroy()
		{
			//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_00bb: Expected O, but got Unknown
			//IL_00c3: Expected O, but got Unknown
			if (clouds != null)
			{
				clouds.Dispose();
			}
			if (haze != null)
			{
				haze.Dispose();
			}
			if (stormSky != null)
			{
				stormSky.Dispose();
			}
			ready = false;
			active = false;
			if (Object.op_Implicit((Object)(object)effects))
			{
				Object.Destroy((Object)(object)effects);
			}
			if (Object.op_Implicit((Object)(object)rainMaterial))
			{
				Object.Destroy((Object)(object)rainMaterial);
			}
			if (PhotonNetwork.LocalPlayer != null)
			{
				Player localPlayer = PhotonNetwork.LocalPlayer;
				Hashtable val = new Hashtable();
				((Dictionary<object, object>)val).Add((object)"PF_RainInside", (object)false);
				localPlayer.SetCustomProperties(val, (Hashtable)null, (WebFlags)null);
			}
			if ((Object)(object)Instance == (Object)(object)this)
			{
				Instance = null;
			}
		}
	}
	public sealed class RainHaze : IDisposable
	{
		private sealed class Snapshot
		{
			public readonly float[] values = new float[FloatNames.Length];

			public readonly Color[] sky = (Color[])(object)new Color[SkyNames.Length];

			public Color tint;

			public Texture texture;

			public Vector4 speed;

			public Vector4 axis;

			public float cloudDensity;

			public Material skybox;

			public Snapshot()
			{
				//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_00a7: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
				//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
				//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
				//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
				//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
				for (int i = 0; i < values.Length; i++)
				{
					values[i] = Shader.GetGlobalFloat(FloatNames[i]);
				}
				for (int j = 0; j < sky.Length; j++)
				{
					sky[j] = Shader.GetGlobalColor(SkyNames[j]);
				}
				cloudDensity = Shader.GetGlobalFloat("GlobalCloudDensity");
				skybox = RenderSettings.skybox;
				tint = Shader.GetGlobalColor("WindTint");
				texture = Shader.GetGlobalTexture("_WindTexture");
				speed = Shader.GetGlobalVector("WindSpeed");
				axis = Shader.GetGlobalVector("WindRotationAxis");
			}

			public void Restore(Material applied)
			{
				//IL_003f: Unknown result type (might be due to invalid IL or missing references)
				//IL_009c: Unknown result type (might be due to invalid IL or missing references)
				//IL_00be: Unknown result type (might be due to invalid IL or missing references)
				//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
				for (int i = 0; i < values.Length; i++)
				{
					Shader.SetGlobalFloat(FloatNames[i], values[i]);
				}
				for (int j = 0; j < sky.Length; j++)
				{
					Shader.SetGlobalColor(SkyNames[j], sky[j]);
				}
				Shader.SetGlobalFloat("GlobalCloudDensity", cloudDensity);
				if (Object.op_Implicit((Object)(object)applied) && (Object)(object)RenderSettings.skybox == (Object)(object)applied)
				{
					RenderSettings.skybox = skybox;
				}
				Shader.SetGlobalColor("WindTint", tint);
				Shader.SetGlobalTexture("_WindTexture", texture);
				Shader.SetGlobalVector("WindSpeed", speed);
				Shader.SetGlobalVector("WindRotationAxis", axis);
			}
		}

		private static readonly string[] FloatNames = new string[8] { "_WeatherBlend", "WindSkyBrightnessValue", "WindTextureInfluence", "WindSphereScale", "WindFogDensity", "WindFogTextureDensity", "WindMixInfluence", "WindRotationAngle" };

		private static readonly string[] SkyNames = new string[3] { "SkyTopColor", "SkyMidColor", "SkyBottomColor" };

		private readonly RainTrial.Settings settings;

		private readonly Action<Exception> onError;

		private readonly float[] target = new float[8] { 0f, 0.2f, 0.2f, 5f, 50f, 15f, 0f, 180f };

		private Color targetTint = Color.white;

		private Texture targetTexture;

		private Vector4 targetSpeed;

		private Vector4 targetAxis = new Vector4(0f, 0f, 1f, 0f);

		private Snapshot snapshot;

		private Material skyMaterial;

		private Material stormTemplate;

		public float StormCloudTime;

		public float StormFlashStrength;

		public Vector4 StormFlash = new Vector4(0f, 0.7f, 0.7f, 0f);

		private bool scope;

		private bool subscribed;

		private readonly DiffuseOvercastLighting lighting = new DiffuseOvercastLighting();

		private Light sun;

		private Light moon;

		private float daylight = 1f;

		public double Weight { get; private set; }

		public double SkyWeight { get; private set; }

		public bool Failed { get; private set; }

		public string Error { get; private set; }

		public string Source { get; private set; } = "Native fog defaults";

		public bool NativeSource { get; private set; }

		public float LastAppliedBlend { get; private set; }

		public float TargetDensity => target[4] * settings.hazeDensityMultiplier;

		public Color TargetTint { get; private set; }

		public bool LastSkyApplied { get; private set; }

		public bool LastSkyMaterialApplied { get; private set; }

		public string SkyShader { get; private set; }

		public float LastCloudDensity { get; private set; }

		public Color LastSkyTop { get; private set; }

		public Color LastSkyMid { get; private set; }

		public Color LastSkyBottom { get; private set; }

		public bool LastDiffuseApplied { get; private set; }

		public Color LastDiffuse => lighting.Diffuse;

		public void SetStormTemplate(Material value)
		{
			stormTemplate = value;
		}

		public void ConfigureLighting(Light a, Light b, float day)
		{
			sun = a;
			moon = b;
			daylight = day;
		}

		public RainHaze(RainTrial.Settings values, Action<Exception> error)
		{
			//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)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			settings = values;
			onError = error;
			RenderPipelineManager.beginFrameRendering += Begin;
			RenderPipelineManager.endFrameRendering += End;
			subscribed = true;
		}

		public void Configure(FogConfig source)
		{
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: 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_00ca: 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_00d0: 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_00d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00db: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0103: Unknown result type (might be due to invalid IL or missing references)
			//IL_0109: Unknown result type (might be due to invalid IL or missing references)
			//IL_010f: Unknown result type (might be due to invalid IL or missing references)
			//IL_011a: Unknown result type (might be due to invalid IL or missing references)
			//IL_011f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fa: Unknown result type (might be due to invalid IL or missing references)
			if (Object.op_Implicit((Object)(object)source))
			{
				NativeSource = true;
				Source = ((Object)source).name;
				target[1] = source.windSkyBrightnessValue;
				target[2] = source.windTextureInfluence;
				target[3] = source.windSphereScale;
				target[4] = source.windFogDensity;
				target[5] = source.WindFogTextureDensity;
				target[6] = source.windMixInfluence;
				targetTint = source.windTint;
				targetTexture = source.windTexture;
				targetSpeed = new Vector4(source.windSpeed.x, source.windSpeed.y, 0f, 0f);
				Vector3 forward = ((Component)source).transform.forward;
				Vector3 val = -Vector3.Cross(Vector3.up, forward);
				float num = Vector3.Angle(Vector3.up, forward);
				if (source.straightDown)
				{
					val = Vector3.forward;
					num = 180f;
				}
				targetAxis = new Vector4(val.x, val.y, val.z, 0f);
				target[7] = num;
			}
		}

		public void Tick(bool inBiome, bool raining, float dt)
		{
			scope = inBiome && (settings.hazeEnabled || settings.skyEnabled) && !Failed;
			Weight = RainMath.Haze(Weight, inBiome && settings.hazeEnabled && !Failed, raining, dt, settings.hazeFadeSeconds);
			SkyWeight = RainMath.Haze(SkyWeight, inBiome && settings.skyEnabled && !Failed, raining: true, dt, settings.skyFadeSeconds);
			if (!scope)
			{
				LastSkyApplied = false;
				LastSkyMaterialApplied = false;
				LastDiffuseApplied = false;
				LastAppliedBlend = 0f;
				Restore();
			}
		}

		private Color Grade(Color color, float weight)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: 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_004d: 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_00ab: 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_00b7: 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_00be: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			double luminance = RainMath.SkyLuminance(color.r, color.g, color.b);
			Color val = default(Color);
			((Color)(ref val))..ctor((float)RainMath.SkyChannel(color.r, luminance, settings.skyBrightness, settings.skySaturation, 0.94), (float)RainMath.SkyChannel(color.g, luminance, settings.skyBrightness, settings.skySaturation, 0.98), (float)RainMath.SkyChannel(color.b, luminance, settings.skyBrightness, settings.skySaturation, 1.03), color.a);
			return Color.Lerp(color, val, weight);
		}

		private void ApplySky()
		{
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: 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_02ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0309: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01de: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ec: Expected O, but got Unknown
			//IL_03fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_040b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0419: Expected O, but got Unknown
			float num = (float)SkyWeight;
			LastSkyApplied = num > 0f;
			LastSkyMaterialApplied = false;
			if (num <= 0f)
			{
				return;
			}
			LastSkyTop = Grade(snapshot.sky[0], num);
			LastSkyMid = Grade(snapshot.sky[1], num);
			LastSkyBottom = Grade(snapshot.sky[2], num);
			Shader.SetGlobalColor(SkyNames[0], LastSkyTop);
			Shader.SetGlobalColor(SkyNames[1], LastSkyMid);
			Shader.SetGlobalColor(SkyNames[2], LastSkyBottom);
			LastCloudDensity = Mathf.Lerp(snapshot.cloudDensity, Mathf.Max(snapshot.cloudDensity, settings.skyCloudDensity), num);
			Shader.SetGlobalFloat("GlobalCloudDensity", LastCloudDensity);
			Material skybox = snapshot.skybox;
			SkyShader = ((Object.op_Implicit((Object)(object)skybox) && Object.op_Implicit((Object)(object)skybox.shader)) ? ((Object)skybox.shader).name : null);
			if (Object.op_Implicit((Object)(object)stormTemplate) && Object.op_Implicit((Object)(object)stormTemplate.shader))
			{
				if (Object.op_Implicit((Object)(object)skyMaterial) && (Object)(object)skyMaterial.shader != (Object)(object)stormTemplate.shader)
				{
					Object.Destroy((Object)(object)skyMaterial);
					skyMaterial = null;
				}
				if (!Object.op_Implicit((Object)(object)skyMaterial))
				{
					skyMaterial = new Material(stormTemplate)
					{
						name = "PF_StormCloudSky_RuntimeCopy",
						hideFlags = (HideFlags)61
					};
				}
				skyMaterial.SetFloat("_SkyBlend", num);
				skyMaterial.SetFloat("_CloudTime", StormCloudTime);
				skyMaterial.SetFloat("_Daylight", (float)Math.Max(0.08, Math.Min(1.0, RainMath.SkyLuminance(snapshot.sky[0].r, snapshot.sky[0].g, snapshot.sky[0].b) * 2.0)));
				skyMaterial.SetColor("_NativeTop", snapshot.sky[0]);
				skyMaterial.SetColor("_NativeMid", snapshot.sky[1]);
				skyMaterial.SetColor("_NativeBottom", snapshot.sky[2]);
				skyMaterial.SetVector("_FlashDirection", StormFlash);
				skyMaterial.SetFloat("_FlashStrength", StormFlashStrength);
				SkyShader = ((Object)skyMaterial.shader).name;
				RenderSettings.skybox = skyMaterial;
				LastSkyMaterialApplied = true;
			}
			else if (Object.op_Implicit((Object)(object)skybox) && Object.op_Implicit((Object)(object)skybox.shader) && !(((Object)skybox.shader).name != "GD/Lit Clouds Sky") && skybox.HasProperty("_SunIntensity"))
			{
				if (Object.op_Implicit((Object)(object)skyMaterial) && (Object)(object)skyMaterial.shader != (Object)(object)skybox.shader)
				{
					Object.Destroy((Object)(object)skyMaterial);
					skyMaterial = null;
				}
				if (!Object.op_Implicit((Object)(object)skyMaterial))
				{
					skyMaterial = new Material(skybox)
					{
						name = "PF_OvercastSky_RuntimeCopy",
						hideFlags = (HideFlags)61
					};
				}
				else
				{
					skyMaterial.CopyPropertiesFromMaterial(skybox);
				}
				skyMaterial.SetFloat("_SunIntensity", 0f);
				if (skyMaterial.HasProperty("_cloudscale"))
				{
					skyMaterial.SetFloat("_cloudscale", Mathf.Lerp(skybox.GetFloat("_cloudscale"), settings.skyCloudScale, num));
				}
				if (skyMaterial.HasProperty("_CloudTightness"))
				{
					skyMaterial.SetFloat("_CloudTightness", Mathf.Lerp(skybox.GetFloat("_CloudTightness"), settings.skyCloudTightness, num));
				}
				RenderSettings.skybox = skyMaterial;
				LastSkyMaterialApplied = true;
			}
		}

		private void Begin(ScriptableRenderContext context, Camera[] cameras)
		{
			//IL_00da: 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_00eb: 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)
			//IL_01b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01db: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fd: Unknown result type (might be due to invalid IL or missing references)
			if (!scope || (Weight <= 0.0 && SkyWeight <= 0.0) || Failed)
			{
				return;
			}
			try
			{
				Restore();
				snapshot = new Snapshot();
				lighting.Apply(sun, moon, daylight);
				LastDiffuseApplied = true;
				ApplySky();
				LastAppliedBlend = snapshot.values[0];
				if (Weight <= 0.0)
				{
					return;
				}
				float num = (float)Weight;
				Color val = default(Color);
				((Color)(ref val))..ctor(0.55f, 0.72f, 0.6f, targetTint.a);
				TargetTint = Color.Lerp(targetTint, val, settings.hazeGreenMix);
				for (int i = 1; i < FloatNames.Length; i++)
				{
					float num2 = target[i];
					if (i == 4)
					{
						num2 *= settings.hazeDensityMultiplier;
					}
					Shader.SetGlobalFloat(FloatNames[i], Mathf.Lerp(snapshot.values[i], num2, num));
				}
				Shader.SetGlobalTexture("_WindTexture", (Texture)(Object.op_Implicit((Object)(object)targetTexture) ? targetTexture : (Object.op_Implicit((Object)(object)snapshot.texture) ? ((object)snapshot.texture) : ((object)Texture2D.whiteTexture))));
				Shader.SetGlobalColor("WindTint", Color.Lerp(snapshot.tint, TargetTint, num));
				Shader.SetGlobalVector("WindSpeed", Vector4.Lerp(snapshot.speed, targetSpeed, num));
				Shader.SetGlobalVector("WindRotationAxis", Vector4.Lerp(snapshot.axis, targetAxis, num));
				LastAppliedBlend = Mathf.Lerp(snapshot.values[0], Mathf.Max(snapshot.values[0], settings.hazeStrength), num);
				Shader.SetGlobalFloat("_WeatherBlend", LastAppliedBlend);
			}
			catch (Exception error)
			{
				Disable(error);
			}
		}

		private void End(ScriptableRenderContext context, Camera[] cameras)
		{
			try
			{
				Restore();
			}
			catch (Exception error)
			{
				Disable(error);
			}
		}

		private void Restore()
		{
			lighting.Restore();
			Snapshot snapshot = this.snapshot;
			this.snapshot = null;
			snapshot?.Restore(skyMaterial);
		}

		private void Disable(Exception error)
		{
			Failed = true;
			Error = error.ToString();
			Weight = 0.0;
			SkyWeight = 0.0;
			scope = false;
			LastSkyApplied = false;
			LastSkyMaterialApplied = false;
			LastDiffuseApplied = false;
			try
			{
				Restore();
			}
			catch
			{
			}
			if (onError != null)
			{
				onError(error);
			}
		}

		public void Dispose()
		{
			Restore();
			if (subscribed)
			{
				RenderPipelineManager.beginFrameRendering -= Begin;
				RenderPipelineManager.endFrameRendering -= End;
				subscribed = false;
			}
			if (Object.op_Implicit((Object)(object)skyMaterial))
			{
				Object.Destroy((Object)(object)skyMaterial);
			}
			skyMaterial = null;
			scope = false;
			Weight = 0.0;
			SkyWeight = 0.0;
		}
	}
	public sealed class CloudClock
	{
		public double Next { get; private set; }

		public int Events { get; private set; }

		public bool Step(bool active, double now, double unit, double min, double max)
		{
			if (!active)
			{
				Next = 0.0;
				return false;
			}
			if (Next == 0.0)
			{
				Next = now + 2.5;
			}
			if (now < Next)
			{
				return false;
			}
			Next = now + min + (max - min) * Math.Max(0.0, Math.Min(1.0, unit));
			Events++;
			return true;
		}
	}
	public static class CloudLightningModel
	{
		public struct Point
		{
			public float x;

			public float y;

			public float z;

			public Point(float x, float y, float z)
			{
				this.x = x;
				this.y = y;
				this.z = z;
			}
		}

		public const double Duration = 2.0;

		public static Point[] Path(int seed)
		{
			Random random = new Random(seed);
			Point[] array = new Point[35];
			for (int i = 0; i < array.Length; i++)
			{
				double num = (double)i / (double)(array.Length - 1);
				array[i] = new Point((float)(-105.0 + 210.0 * num), (float)(150.0 + Math.Sin(num * 5.5) * 15.0 + (random.NextDouble() - 0.5) * 9.0), (float)(155.0 + Math.Sin(num * 4.0) * 26.0 + (random.NextDouble() - 0.5) * 13.0));
			}
			return array;
		}

		public static float Reveal(double age)
		{
			return (float)Math.Max(0.0, Math.Min(1.0, age / 0.7));
		}

		public static float Envelope(double age, bool reduced)
		{
			if (age < 0.0 || age >= 2.0)
			{
				return 0f;
			}
			double num = Math.Min(1.0, age / 0.1) * Math.Min(1.0, (2.0 - age) / 0.5);
			if (reduced)
			{
				return (float)(num * 0.3);
			}
			double num2 = 0.38 + 0.62 * Math.Exp(0.0 - Math.Pow((age - 0.25) / 0.12, 2.0)) + 0.48 * Math.Exp(0.0 - Math.Pow((age - 1.05) / 0.2, 2.0));
			return (float)Math.Max(0.0, Math.Min(1.0, num * num2));
		}
	}
	public sealed class CloudLightning : IDisposable
	{
		private sealed class Stroke
		{
			public CloudRibbon[] layers;

			public Vector3[] path;

			public float delay;
		}

		private sealed class Flash
		{
			public GameObject root;

			public Vector3 direction;

			public float at;

			public List<Stroke> strokes = new List<Stroke>();
		}

		private readonly RainTrial.Settings settings;

		private readonly CloudClock clock = new CloudClock();

		private readonly Random random = new Random();

		private readonly List<Flash> flashes = new List<Flash>();

		private Material material;

		private float nextFind;

		public float Glow { get; private set; }

		public Vector3 GlowDirection { get; private set; } = Vector3.up;

		public bool Ready => Object.op_Implicit((Object)(object)material);

		public int Events => clock.Events;

		public float NextIn { get; private set; }

		public string Message { get; private set; } = "Waiting for custom storm sky";

		public CloudLightning(RainTrial.Settings s)
		{
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			settings = s;
		}

		private bool Ensure(float now)
		{
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00af: Expected O, but got Unknown
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			if (Object.op_Implicit((Object)(object)material))
			{
				return true;
			}
			if (now < nextFind)
			{
				return false;
			}
			nextFind = now + 1f;
			Shader val = Shader.Find("FirstRidge/CampfireParticle") ?? ((IEnumerable<Shader>)Resources.FindObjectsOfTypeAll<Shader>()).FirstOrDefault((Func<Shader, bool>)((Shader s) => Object.op_Implicit((Object)(object)s) && ((Object)s).name == "FirstRidge/CampfireParticle"));
			if (!Object.op_Implicit((Object)(object)val) || !val.isSupported)
			{
				return false;
			}
			material = new Material(val)
			{
				name = "PF_CloudLightning_Private",
				hideFlags = (HideFlags)61
			};
			material.SetColor("_BaseColor", Color.white);
			material.renderQueue = 3100;
			return true;
		}

		public void Tick(bool active, float now)
		{
			//IL_0172: Unknown result type (might be due to invalid IL or missing references)
			//IL_028b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0270: Unknown result type (might be due to invalid IL or missing references)
			//IL_0290: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_02af: Unknown result type (might be due to invalid IL or missing references)
			Glow = 0f;
			active = active && settings.cloudLightningEnabled;
			if (!active)
			{
				clock.Step(active: false, now, 0.0, settings.cloudLightningMinSeconds, settings.cloudLightningMaxSeconds);
				Clear();
				NextIn = 0f;
				Message = "Outside Poison Forest storm sky";
				return;
			}
			Camera main = Camera.main;
			if (!Object.op_Implicit((Object)(object)main) || !Ensure(now))
			{
				Message = "Waiting for camera and cloud arc shader";
				return;
			}
			if (clock.Step(active: true, now, random.NextDouble(), settings.cloudLightningMinSeconds, settings.cloudLightningMaxSeconds))
			{
				Spawn(main, now);
			}
			NextIn = Mathf.Max(0f, (float)clock.Next - now);
			Message = "Cloud lightning ready; automatic overhead flashes";
			Flash[] array = flashes.ToArray();
			foreach (Flash flash in array)
			{
				float num = now - flash.at;
				float num2 = CloudLightningModel.Envelope(num, settings.reducedCloudFlashes);
				if (num2 > Glow)
				{
					Glow = num2;
					GlowDirection = flash.direction;
				}
				if ((double)num >= 2.0)
				{
					Object.Destroy((Object)(object)flash.root);
					flashes.Remove(flash);
					continue;
				}
				foreach (Stroke stroke in flash.strokes)
				{
					float num3 = num - stroke.delay;
					float num4 = CloudLightningModel.Reveal(num3);
					float num5 = CloudLightningModel.Envelope(num3, settings.reducedCloudFlashes);
					int count = Math.Max(2, Math.Min(stroke.path.Length, (int)(num4 * (float)(stroke.path.Length - 1)) + 2));
					Vector3[] positions = stroke.path.Take(count).ToArray();
					for (int j = 0; j < stroke.layers.Length; j++)
					{
						CloudRibbon cloudRibbon = stroke.layers[j];
						cloudRibbon.SetPositions(positions);
						Color endColor = ((j == 0) ? new Color(0.67f, 0.58f, 1f, 0.55f) : new Color(0.92f, 0.95f, 1f, 0.95f));
						endColor.a *= num5;
						cloudRibbon.startColor = (cloudRibbon.endColor = endColor);
					}
				}
			}
		}

		private void Spawn(Camera camera, float now)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_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)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_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)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: 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_00d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00da: Expected O, but got Unknown
			//IL_00e3: 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_00f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0101: Unknown result type (might be due to invalid IL or missing references)
			//IL_0106: 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)
			//IL_010f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_0165: Unknown result type (might be due to invalid IL or missing references)
			//IL_016a: Unknown result type (might be due to invalid IL or missing references)
			//IL_016c: Unknown result type (might be due to invalid IL or missing references)
			//IL_016f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0194: Unknown result type (might be due to invalid IL or missing references)
			//IL_0199: Unknown result type (might be due to invalid IL or missing references)
			//IL_019f: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_01fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0222: Unknown result type (might be due to invalid IL or missing references)
			//IL_0224: Unknown result type (might be due to invalid IL or missing references)
			//IL_0228: Unknown result type (might be due to invalid IL or missing references)
			//IL_022e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0253: Unknown result type (might be due to invalid IL or missing references)
			//IL_0265: Unknown result type (might be due to invalid IL or missing references)
			//IL_026a: Unknown result type (might be due to invalid IL or missing references)
			//IL_026f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0294: Unknown result type (might be due to invalid IL or missing references)
			//IL_0299: Unknown result type (might be due to invalid IL or missing references)
			//IL_029e: Unknown result type (might be due to invalid IL or missing references)
			Vector3 val = Vector3.ProjectOnPlane(((Component)camera).transform.forward, Vector3.up);
			Vector3 direction = ((Vector3)(ref val)).normalized;
			if (((Vector3)(ref direction)).sqrMagnitude < 0.1f)
			{
				direction = Vector3.forward;
			}
			direction = Quaternion.AngleAxis((float)(random.NextDouble() - 0.5) * 75f, Vector3.up) * direction;
			Vector3 side = Vector3.Cross(Vector3.up, direction);
			Vector3 center = ((Component)camera).transform.position;
			Flash obj = new Flash
			{
				root = new GameObject("PF_CloudLightning_" + clock.Events),
				at = now
			};
			val = direction * 155f + Vector3.up * 150f;
			obj.direction = ((Vector3)(ref val)).normalized;
			Flash flash = obj;
			CloudLightningModel.Point[] source = CloudLightningModel.Path(random.Next());
			Vector3[] array = source.Select((CloudLightningModel.Point p) => center + side * p.x + Vector3.up * p.y + direction * p.z).ToArray();
			Add(flash, array, 0f, 1f);
			for (int num = 0; num < 4; num++)
			{
				int num2 = 6 + num * 6;
				Vector3 val2 = array[num2];
				Vector3 val3 = val2 + side * (float)((random.NextDouble() - 0.5) * 105.0) + direction * (float)((random.NextDouble() - 0.5) * 90.0) + Vector3.up * (float)(random.NextDouble() * 18.0 - 9.0);
				Vector3[] array2 = (Vector3[])(object)new Vector3[12];
				for (int num3 = 0; num3 < array2.Length; num3++)
				{
					float num4 = (float)num3 / (float)(array2.Length - 1);
					array2[num3] = Vector3.Lerp(val2, val3, num4) + side * (float)((random.NextDouble() - 0.5) * 8.0) * Mathf.Sin(num4 * MathF.PI) + Vector3.up * (float)((random.NextDouble() - 0.5) * 4.0);
				}
				Add(flash, array2, (float)num2 / (float)(array.Length - 1) * 0.7f, 0.65f);
			}
			flashes.Add(flash);
		}

		private void Add(Flash flash, Vector3[] path, float delay, float scale)
		{
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Expected O, but got Unknown
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: 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)
			Stroke stroke = new Stroke();
			stroke.path = path;
			stroke.delay = delay;
			stroke.layers = new CloudRibbon[2];
			Stroke stroke2 = stroke;
			for (int i = 0; i < 2; i++)
			{
				GameObject val = new GameObject((i == 0) ? "VioletArc" : "WhiteCore");
				val.transform.SetParent(flash.root.transform, false);
				CloudRibbon cloudRibbon = val.AddComponent<CloudRibbon>();
				cloudRibbon.sharedMaterial = material;
				cloudRibbon.widthMultiplier = ((i == 0) ? 3.4f : 0.85f) * scale;
				cloudRibbon.startColor = (cloudRibbon.endColor = Color.clear);
				cloudRibbon.sortingOrder = i;
				cloudRib

plugins/ThunderfenSession/ThunderfenSteamSessionBridge.dll

Decompiled a week ago
using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using BepInEx;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Peak;
using Peak.Network;
using Photon.Pun;
using Photon.Realtime;
using PoisonForestSolo;
using Portningsbolaget;
using Portningsbolaget.Platforms;
using Portningsbolaget.Utilities;
using Steamworks;
using UnityEngine;
using UnityEngine.SceneManagement;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyVersion("0.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace ThunderfenSteamSession
{
	[BepInPlugin("local.peak.thunderfen.steamsession", "Thunderfen Steam Session Bridge", "1.0.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency("local.peak.poisonforest.solo", "0.6.0")]
	public sealed class SteamSessionBridge : BaseUnityPlugin
	{
		public const string Version = "1.0.0";

		private Harmony harmony;

		private float next;

		private float nextJoin;

		private float nextPublish;

		private string folder;

		private string boundRoom = "";

		private string sessionRoom = "";

		private string lastMessage = "";

		private ulong cachedLobby;

		private int attempts;

		private bool enabledForBuild;

		private static string Quote(string s)
		{
			return "\"" + (s ?? "").Replace("\\", "\\\\").Replace("\"", "\\\"").Replace("\r", "\\r")
				.Replace("\n", "\\n") + "\"";
		}

		private void Awake()
		{
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Expected O, but got Unknown
			folder = Path.Combine(Application.persistentDataPath, "Thunderfen");
			Directory.CreateDirectory(folder);
			try
			{
				NativeCompatibility.CheckPatches(typeof(SteamSessionBridge).Assembly);
				harmony = new Harmony("local.peak.thunderfen.steamsession.resume");
				harmony.PatchAll(typeof(SteamSessionBridge).Assembly);
				SceneManager.sceneLoaded += ResetCodeOnTitle;
				enabledForBuild = true;
				((BaseUnityPlugin)this).Logger.LogInfo((object)"Native airport/gameplay Steam-session handoff enabled. PLL admission checks remain unchanged.");
			}
			catch (Exception ex)
			{
				SceneManager.sceneLoaded -= ResetCodeOnTitle;
				Harmony obj = harmony;
				if (obj != null)
				{
					obj.UnpatchSelf();
				}
				harmony = null;
				enabledForBuild = false;
				((BaseUnityPlugin)this).Logger.LogError((object)("Steam-session bridge disabled: " + ex));
			}
		}

		private static bool IsMember(ulong id)
		{
			//IL_0017: 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_0023: 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_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			if (id == 0)
			{
				return false;
			}
			CSteamID val = default(CSteamID);
			((CSteamID)(ref val))..ctor(id);
			int numLobbyMembers = SteamMatchmaking.GetNumLobbyMembers(val);
			CSteamID steamID = SteamUser.GetSteamID();
			for (int i = 0; i < numLobbyMembers; i++)
			{
				if (SteamMatchmaking.GetLobbyMemberByIndex(val, i) == steamID)
				{
					return true;
				}
			}
			return false;
		}

		private static bool OwnedMember(ulong id)
		{
			//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)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			return id != 0L && SteamMatchmaking.GetLobbyOwner(new CSteamID(id)) == SteamUser.GetSteamID() && IsMember(id);
		}

		private static ulong ParseLobby(string text)
		{
			//IL_000c: 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)
			long result2;
			if (ulong.TryParse(text, out var result))
			{
				CSteamID val = new CSteamID(result);
				if (((CSteamID)(ref val)).IsLobby())
				{
					result2 = (long)result;
					goto IL_0020;
				}
			}
			result2 = 0L;
			goto IL_0020;
			IL_0020:
			return (ulong)result2;
		}

		private static ulong PublishedLobby()
		{
			string text = default(string);
			return NetCode.Session.TryGetCustomProperty("csid", ref text) ? ParseLobby(text) : 0;
		}

		private void Message(string value)
		{
			if (!(value == lastMessage))
			{
				lastMessage = value;
				((BaseUnityPlugin)this).Logger.LogInfo((object)value);
				if (RuntimeDiagnostics.PeriodicSnapshots)
				{
					File.AppendAllText(Path.Combine(folder, "steam-session-bridge-events.jsonl"), "{\"utc\":" + Quote(DateTime.UtcNow.ToString("O")) + ",\"message\":" + Quote(value) + "}" + Environment.NewLine);
				}
			}
		}

		private void Update()
		{
			//IL_0109: Unknown result type (might be due to invalid IL or missing references)
			//IL_015e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0163: Unknown result type (might be due to invalid IL or missing references)
			//IL_017c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0181: Unknown result type (might be due to invalid IL or missing references)
			//IL_0277: Unknown result type (might be due to invalid IL or missing references)
			//IL_0355: Unknown result type (might be due to invalid IL or missing references)
			//IL_035a: Unknown result type (might be due to invalid IL or missing references)
			if (!enabledForBuild || Time.unscaledTime < next)
			{
				return;
			}
			next = Time.unscaledTime + 1f;
			try
			{
				if (!SteamManager.Initialized || !Object.op_Implicit((Object)(object)GameHandler.Instance) || !GameHandler.Initialized)
				{
					return;
				}
				bool flag = PhotonNetwork.InRoom && !PhotonNetwork.OfflineMode;
				string text = (flag ? PhotonNetwork.CurrentRoom.Name : "");
				if (sessionRoom != text)
				{
					sessionRoom = text;
					attempts = 0;
					nextJoin = 0f;
					nextPublish = 0f;
					if (boundRoom != text)
					{
						cachedLobby = 0uL;
						boundRoom = "";
					}
				}
				if (!flag)
				{
					return;
				}
				SteamLobbyHandler service = GameHandler.GetService<SteamLobbyHandler>();
				if (service == null)
				{
					return;
				}
				ulong steamID = service.LobbySteamId.m_SteamID;
				bool flag2 = OwnedMember(steamID);
				bool isMasterClient = PhotonNetwork.IsMasterClient;
				if (isMasterClient && flag2)
				{
					cachedLobby = steamID;
					boundRoom = text;
				}
				ulong num = PublishedLobby();
				bool targetMember = IsMember(num);
				SessionInput obj = new SessionInput
				{
					online = flag
				};
				Scene activeScene = SceneManager.GetActiveScene();
				obj.airport = ((Scene)(ref activeScene)).name == "Airport";
				activeScene = SceneManager.GetActiveScene();
				obj.gameplay = ((Scene)(ref activeScene)).name == "WilIsland";
				obj.host = isMasterClient;
				obj.room = text;
				obj.boundRoom = boundRoom;
				obj.nativeLobby = steamID;
				obj.cachedLobby = cachedLobby;
				obj.publishedLobby = num;
				obj.nativeOwnedMember = flag2;
				obj.cachedOwnedMember = OwnedMember(cachedLobby);
				obj.targetMember = targetMember;
				SessionPlan sessionPlan = SteamSessionPolicy.Plan(obj);
				if (sessionPlan.action == "publish" && Time.unscaledTime >= nextPublish)
				{
					nextPublish = Time.unscaledTime + 5f;
					if (num != sessionPlan.lobby)
					{
						NetCode.Session.SetCustomProperty("csid", sessionPlan.lobby.ToString());
					}
					service.SetLobbyData();
					Message("Host native session advertised; native csid and actual PhotonRoom published=" + SteamMatchmaking.SetLobbyData(new CSteamID(sessionPlan.lobby), "PhotonRoom", text));
				}
				else if ((sessionPlan.action == "restore-host" || sessionPlan.action == "join-session-lobby") && Time.unscaledTime >= nextJoin && attempts < 3)
				{
					nextJoin = Time.unscaledTime + 12f;
					attempts++;
					if (steamID != 0L && steamID != sessionPlan.lobby)
					{
						service.LeaveLobby();
					}
					if (service.TryJoinLobbyDuringSession(sessionPlan.lobby.ToString()))
					{
						SteamMatchmaking.JoinLobby(new CSteamID(sessionPlan.lobby));
						Message("Requested native in-session Steam membership; attempt " + attempts);
					}
					else
					{
						Message("Native in-session lobby request was rejected; no forced state changes.");
					}
				}
				WriteState(text, isMasterClient, steamID, num, sessionPlan, attempts);
			}
			catch (Exception ex)
			{
				Message("Steam session handoff: " + ex.GetType().Name + ": " + ex.Message);
			}
		}

		private void ResetCodeOnTitle(Scene scene, LoadSceneMode mode)
		{
			if (((Scene)(ref scene)).name == "Title")
			{
				ResumeRoomCode.Reset();
			}
		}

		private void OnDestroy()
		{
			SceneManager.sceneLoaded -= ResetCodeOnTitle;
			Harmony obj = harmony;
			if (obj != null)
			{
				obj.UnpatchSelf();
			}
		}

		private void WriteState(string room, bool host, ulong nativeLobby, ulong published, SessionPlan plan, int tries)
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			if (RuntimeDiagnostics.PeriodicSnapshots)
			{
				CSteamID val = default(CSteamID);
				((CSteamID)(ref val))..ctor(plan.lobby);
				int num = ((plan.lobby != 0L) ? SteamMatchmaking.GetNumLobbyMembers(val) : 0);
				string s = ((plan.lobby == 0L) ? "" : SteamMatchmaking.GetLobbyData(val, "af.pll.library/admission"));
				string contents = "{\"version\":" + Quote("1.0.0") + ",\"utc\":" + Quote(DateTime.UtcNow.ToString("O")) + ",\"room\":" + Quote(room) + ",\"host\":" + (host ? "true" : "false") + ",\"nativeLobby\":" + Quote(nativeLobby.ToString()) + ",\"publishedLobby\":" + Quote(published.ToString()) + ",\"targetLobby\":" + Quote(plan.lobby.ToString()) + ",\"action\":" + Quote(plan.action) + ",\"roomCodeStatus\":" + Quote(ResumeRoomCode.Last) + ",\"attempts\":" + tries + ",\"steamMembers\":" + num + ",\"photonPlayers\":" + PhotonNetwork.CurrentRoom.PlayerCount + ",\"admission\":" + Quote(s) + ",\"localIsMember\":" + (IsMember(plan.lobby) ? "true" : "false") + "}";
				File.WriteAllText(Path.Combine(folder, "steam-session-bridge.json"), contents);
			}
		}
	}
	public sealed class SessionInput
	{
		public bool online;

		public bool airport;

		public bool gameplay;

		public bool host;

		public bool nativeOwnedMember;

		public bool cachedOwnedMember;

		public bool targetMember;

		public ulong nativeLobby;

		public ulong cachedLobby;

		public ulong publishedLobby;

		public string room;

		public string boundRoom;
	}
	public sealed class SessionPlan
	{
		public string action;

		public ulong lobby;

		public SessionPlan(string action, ulong lobby)
		{
			this.action = action;
			this.lobby = lobby;
		}
	}
	public static class SteamSessionPolicy
	{
		public static SessionPlan Plan(SessionInput x)
		{
			if (!x.online || (!x.airport && !x.gameplay) || string.IsNullOrEmpty(x.room))
			{
				return new SessionPlan("inactive", 0uL);
			}
			if (x.host)
			{
				if (x.nativeLobby != 0L && x.nativeOwnedMember)
				{
					return new SessionPlan("publish", x.nativeLobby);
				}
				if (x.cachedLobby != 0L && x.cachedOwnedMember && x.boundRoom == x.room)
				{
					return new SessionPlan("restore-host", x.cachedLobby);
				}
				return new SessionPlan("wait-host-lobby", 0uL);
			}
			if (x.publishedLobby == 0)
			{
				return new SessionPlan("wait-host-advertisement", 0uL);
			}
			if (x.nativeLobby == x.publishedLobby && x.targetMember)
			{
				return new SessionPlan("ready", x.publishedLobby);
			}
			return new SessionPlan("join-session-lobby", x.publishedLobby);
		}
	}
	public static class ResumeRoomCode
	{
		public static bool Pending;

		public static string AttemptedRoom;

		public static string Last = "not used";

		public static bool NeedsCode(bool pending, bool offline, string room, string region)
		{
			Guid result;
			return pending && !offline && !string.IsNullOrEmpty(region) && Guid.TryParse(room, out result);
		}

		public static void Reset()
		{
			Pending = false;
			AttemptedRoom = null;
		}

		public static string NewCode()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			AttemptedRoom = Utilities.CreateRandomName(PhotonNetwork.CloudRegion, PlatformUtility.CurrentPlatform, ModUtility.UsingMods, false);
			Last = "requested native-format resumed room";
			return AttemptedRoom;
		}
	}
	[HarmonyPatch(typeof(Quicksave), "LoadSavedGameScene", new Type[] { })]
	internal static class ResumeCodeIntent
	{
		private static void Prefix()
		{
			ResumeRoomCode.Pending = Quicksave.ShouldUseSaveData;
			ResumeRoomCode.AttemptedRoom = null;
		}
	}
	[HarmonyPatch(typeof(PhotonNetwork), "CreateRoom", new Type[]
	{
		typeof(string),
		typeof(RoomOptions),
		typeof(TypedLobby),
		typeof(string[])
	})]
	internal static class NativeResumeRoomName
	{
		private static void Prefix(ref string __0)
		{
			if (ResumeRoomCode.NeedsCode(ResumeRoomCode.Pending, PhotonNetwork.OfflineMode, __0, PhotonNetwork.CloudRegion))
			{
				__0 = ResumeRoomCode.NewCode();
			}
		}
	}
	[HarmonyPatch(typeof(PhotonNetwork), "JoinOrCreateRoom", new Type[]
	{
		typeof(string),
		typeof(RoomOptions),
		typeof(TypedLobby),
		typeof(string[])
	})]
	internal static class NativeResumeJoinOrCreate
	{
		private static bool Prefix(string __0, RoomOptions __1, TypedLobby __2, string[] __3, ref bool __result)
		{
			if (!ResumeRoomCode.NeedsCode(ResumeRoomCode.Pending, PhotonNetwork.OfflineMode, __0, PhotonNetwork.CloudRegion))
			{
				return true;
			}
			__result = PhotonNetwork.CreateRoom(ResumeRoomCode.NewCode(), __1, __2, __3);
			return false;
		}
	}
	[HarmonyPatch(typeof(NetworkConnector), "OnCreatedRoom", new Type[] { })]
	internal static class ResumeCodeCreated
	{
		private static void Postfix()
		{
			if (PhotonNetwork.CurrentRoom != null && PhotonNetwork.CurrentRoom.Name == ResumeRoomCode.AttemptedRoom)
			{
				ResumeRoomCode.Pending = false;
				ResumeRoomCode.Last = "native-format resumed room created";
			}
		}
	}
}

plugins/ThunderfenSolo/PoisonForestSolo.dll

Decompiled a week ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using ExitGames.Client.Photon;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using PLL.Library;
using Peak;
using Peak.Network;
using Photon.Pun;
using Photon.Realtime;
using PoisonForestGeneration;
using PoisonForestSolo;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using Zorro.Core;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyVersion("0.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace PoisonForestGeneration
{
	public static class GeneratedData
	{
		[Serializable]
		public sealed class Entry
		{
			public string name;

			public string sha256;
		}

		[Serializable]
		public sealed class Manifest
		{
			public int schema;

			public int seed;

			public int attempt;

			public int treeCount;

			public string biomeId;

			public string gameSha256;

			public string bundleSha256;

			public Entry[] files;
		}

		private sealed class FileIdentity
		{
			public long length;

			public DateTime written;

			public string sha256;
		}

		private const string OriginalTemplate = "DD87D13B07623BE404C890619ABF65D7DB0A6D679B5C771110362F673A490518";

		private const string TextureReferenceTemplate = "2D0E0B6FD6D57EB649A4731AFA5AA39F5A1749DFF9E88A877ACDC30C12333A5E";

		private static Manifest manifest;

		private static string folder;

		private static string overrideFolder;

		private static string contentHash;

		private static readonly Dictionary<string, FileIdentity> fileHashes = new Dictionary<string, FileIdentity>(StringComparer.OrdinalIgnoreCase);

		internal static int Seed
		{
			get
			{
				Ensure();
				return manifest.seed;
			}
		}

		internal static string ContentHash
		{
			get
			{
				Ensure();
				return contentHash;
			}
		}

		public static void UseFolder(string value)
		{
			if (!(overrideFolder == value))
			{
				overrideFolder = value;
				manifest = null;
			}
		}

		private static string Hash(byte[] bytes)
		{
			using SHA256 sHA = SHA256.Create();
			return BitConverter.ToString(sHA.ComputeHash(bytes)).Replace("-", "");
		}

		private static string FileHash(string path)
		{
			FileInfo fileInfo = new FileInfo(path);
			if (!fileInfo.Exists)
			{
				throw new FileNotFoundException("Thunderfen data file missing", path);
			}
			lock (fileHashes)
			{
				if (fileHashes.TryGetValue(fileInfo.FullName, out var value) && value.length == fileInfo.Length && value.written == fileInfo.LastWriteTimeUtc)
				{
					return value.sha256;
				}
			}
			string text;
			using (FileStream inputStream = File.OpenRead(fileInfo.FullName))
			{
				using SHA256 sHA = SHA256.Create();
				text = BitConverter.ToString(sHA.ComputeHash(inputStream)).Replace("-", "");
			}
			lock (fileHashes)
			{
				fileHashes[fileInfo.FullName] = new FileIdentity
				{
					length = fileInfo.Length,
					written = fileInfo.LastWriteTimeUtc,
					sha256 = text
				};
			}
			return text;
		}

		public static byte[] Read(string name)
		{
			Ensure();
			Entry entry = manifest.files.SingleOrDefault((Entry e) => e.name == name);
			if (entry == null)
			{
				throw new InvalidDataException("Generated data not declared: " + name);
			}
			byte[] array = File.ReadAllBytes(Path.Combine(folder, entry.name));
			if (Hash(array) != entry.sha256)
			{
				throw new InvalidDataException("Generated data mismatch: " + name);
			}
			return array;
		}

		private static void Ensure()
		{
			if (manifest == null)
			{
				folder = overrideFolder ?? ContentPaths.Baseline;
				manifest = Inspect(folder, out contentHash);
			}
		}

		internal static Manifest Inspect(string dataFolder, out string identity)
		{
			string bundle = ContentPaths.Bundle;
			byte[] bytes = File.ReadAllBytes(Path.Combine(dataFolder, "manifest.pfm"));
			Manifest manifest = ManifestCodec.Read(bytes);
			Validate(manifest, dataFolder, bundle);
			identity = Hash(bytes);
			return manifest;
		}

		private static void Validate(Manifest candidate, string dataFolder, string bundle)
		{
			if (candidate.schema != 1 || candidate.biomeId != "prototype/first-ridge" || candidate.treeCount < 1 || candidate.treeCount > 512)
			{
				throw new InvalidDataException("Invalid Thunderfen generation manifest: schema=" + candidate.schema + ", biome=" + candidate.biomeId + ", trees=" + candidate.treeCount);
			}
			HashSet<string> hashSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
			Entry[] files = candidate.files;
			foreach (Entry entry in files)
			{
				if (string.IsNullOrEmpty(entry.name) || Path.GetFileName(entry.name) != entry.name || !hashSet.Add(entry.name) || entry.sha256.Length != 64)
				{
					throw new InvalidDataException("Unsafe or duplicate catalog name");
				}
				if (FileHash(Path.Combine(dataFolder, entry.name)) != entry.sha256)
				{
					throw new InvalidDataException("Mixed generated biome data: " + entry.name);
				}
			}
			if (string.IsNullOrEmpty(candidate.gameSha256) || candidate.gameSha256.Length != 64)
			{
				throw new InvalidDataException("Generated biome has no PEAK provenance hash");
			}
			string text = FileHash(bundle);
			if (text != candidate.bundleSha256 && (!(text == "2D0E0B6FD6D57EB649A4731AFA5AA39F5A1749DFF9E88A877ACDC30C12333A5E") || !(candidate.bundleSha256 == "DD87D13B07623BE404C890619ABF65D7DB0A6D679B5C771110362F673A490518")))
			{
				throw new InvalidDataException("Terrain bundle does not match generated catalogs");
			}
		}
	}
	public static class ManifestCodec
	{
		private static string Text(BinaryReader r)
		{
			int num = r.ReadInt32();
			if (num < 1 || num > 512 || num > r.BaseStream.Length - r.BaseStream.Position)
			{
				throw new InvalidDataException("Generated manifest string length");
			}
			return new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true).GetString(r.ReadBytes(num));
		}

		public static GeneratedData.Manifest Read(byte[] bytes)
		{
			if (bytes == null || bytes.Length < 32 || bytes.Length > 65536)
			{
				throw new InvalidDataException("Generated manifest length");
			}
			using BinaryReader binaryReader = new BinaryReader(new MemoryStream(bytes), Encoding.UTF8);
			if (binaryReader.ReadUInt32() != 827147856)
			{
				throw new InvalidDataException("Generated manifest signature");
			}
			GeneratedData.Manifest manifest = new GeneratedData.Manifest
			{
				schema = binaryReader.ReadInt32(),
				seed = binaryReader.ReadInt32(),
				attempt = binaryReader.ReadInt32(),
				treeCount = binaryReader.ReadInt32(),
				biomeId = Text(binaryReader),
				gameSha256 = Text(binaryReader),
				bundleSha256 = Text(binaryReader)
			};
			int num = binaryReader.ReadInt32();
			if (num < 4 || num > 20)
			{
				throw new InvalidDataException("Generated manifest file count");
			}
			manifest.files = new GeneratedData.Entry[num];
			for (int i = 0; i < num; i++)
			{
				manifest.files[i] = new GeneratedData.Entry
				{
					name = Text(binaryReader),
					sha256 = Text(binaryReader)
				};
			}
			if (binaryReader.BaseStream.Position != binaryReader.BaseStream.Length)
			{
				throw new InvalidDataException("Trailing generated manifest data");
			}
			return manifest;
		}
	}
}
namespace PoisonForestSolo
{
	public static class RunData
	{
		public static bool Pending;

		public static int Revision;

		public static int Seed;

		public static string Folder;

		public static bool Dynamic;
	}
	[BepInPlugin("local.peak.poisonforest.solo", "Thunderfen Prepared Maps and Multiplayer", "1.0.7")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[DefaultExecutionOrder(-10000)]
	public sealed class SoloGenerationPlugin : BaseUnityPlugin
	{
		[Serializable]
		private sealed class Report
		{
			public string utc;

			public string status;

			public string error;

			public string folder;

			public string nativeLightingProfile;

			public string mist;

			public string resumePlacement;

			public string resumeCosmetics;

			public float nativeHour;

			public int nativeDay;

			public bool offline;

			public bool pending;

			public bool dynamic;

			public bool applying;

			public bool localMapReady;

			public int seed;

			public int revision;

			public int resumeHolds;

			public int resumeCorrections;

			public float elapsed;
		}

		[HarmonyPatch(typeof(GUIManager), "SetHeroTitle", new Type[]
		{
			typeof(string),
			typeof(AudioClip),
			typeof(bool)
		})]
		private sealed class EntryTitleHook
		{
			[HarmonyPrefix]
			[HarmonyPriority(0)]
			private static bool Prefix(ref string __0)
			{
				if (!titleGate.Allow(__0))
				{
					return false;
				}
				if (__0 != "喵喵" && __0 != "Thunderfen" && __0 != "雷鸣瘴泽")
				{
					return true;
				}
				string formalBiomeName = FormalBiomeName;
				if (__0 != formalBiomeName && Object.op_Implicit((Object)(object)instance))
				{
					((BaseUnityPlugin)instance).Logger.LogInfo((object)("Biome-entry title: " + __0 + " -> " + formalBiomeName));
				}
				__0 = formalBiomeName;
				return true;
			}
		}

		[HarmonyPatch]
		private sealed class BiomeNameHook
		{
			private static MethodBase TargetMethod()
			{
				return NativeCompatibility.Require(typeof(PllBiomeDefinition), "get_DisplayTitle", typeof(string));
			}

			private static void Postfix(PllBiomeDefinition __instance, ref string __result)
			{
				//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)
				if (Object.op_Implicit((Object)(object)__instance))
				{
					BiomeId biomeId = __instance.BiomeId;
					if (((BiomeId)(ref biomeId)).Value == "prototype/first-ridge")
					{
						__result = FormalBiomeName;
					}
				}
			}
		}

		[HarmonyPatch(typeof(Quicksave), "LoadSavedGameScene", new Type[] { })]
		private sealed class ResumeHook
		{
			private static void Prefix()
			{
				if (Object.op_Implicit((Object)(object)instance))
				{
					instance.resumeRequested = true;
				}
			}
		}

		private static readonly EntryTitleGate titleGate = new EntryTitleGate();

		private static SoloGenerationPlugin instance;

		private Harmony harmony;

		private string readyFolder;

		private string status = "Waiting for a run";

		private string error;

		private string runRoot;

		private string mapIssue;

		private bool requested;

		private bool resumeRequested;

		private bool applying;

		private bool valid;

		private int stableReadyFrames;

		private Transform waitingFrame;

		private float began;

		private float nextReport;

		private LayoutPacket packet;

		private readonly List<Mesh> owned = new List<Mesh>();

		private Text loadNotice;

		private string failureNotice;

		private const string ShownVersion = "1.0.7";

		private Material[] pendingTreeTextures;

		private const float StallGrace = 20f;

		private float segmentSince = -1f;

		private float nextStallCheck;

		private Transform stallFrame;

		private string stallNotice;

		private string stallLogged;

		private bool noticeChinese;

		private string shownEnglish;

		public static bool LocalMapReady { get; private set; }

		private static string FormalBiomeName
		{
			get
			{
				//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)
				//IL_0007: Unknown result type (might be due to invalid IL or missing references)
				//IL_000a: Invalid comparison between Unknown and I4
				//IL_000c: Unknown result type (might be due to invalid IL or missing references)
				//IL_000f: Invalid comparison between Unknown and I4
				Language cURRENT_LANGUAGE = LocalizedText.CURRENT_LANGUAGE;
				return ((int)cURRENT_LANGUAGE == 9 || (int)cURRENT_LANGUAGE == 10) ? "雷鸣瘴泽" : "Thunderfen";
			}
		}

		private void Awake()
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Expected O, but got Unknown
			instance = this;
			runRoot = Path.Combine(Application.persistentDataPath, "Thunderfen");
			try
			{
				NativeCompatibility.CheckCore();
				harmony = new Harmony("local.peak.poisonforest.solo");
				harmony.PatchAll(typeof(SoloGenerationPlugin).Assembly);
				ProfileBiome.Verify(Paths.PluginPath);
				ReleaseRoute.Verify(FileManager.LayoutOrder, FileManager.DoOrder, FileManager.GenerativeMap, FileManager.InfiniteMap);
				((BaseUnityPlugin)this).Logger.LogInfo((object)"PLL loaded the Thunderfen route before startup.");
				SharedWorld.Install(((Component)this).gameObject);
				SceneManager.sceneLoaded += SceneLoaded;
				SceneManager.sceneUnloaded += SceneUnloaded;
				valid = true;
			}
			catch (Exception e)
			{
				SceneManager.sceneLoaded -= SceneLoaded;
				SceneManager.sceneUnloaded -= SceneUnloaded;
				SharedWorld.Uninstall(((Component)this).gameObject);
				Harmony obj = harmony;
				if (obj != null)
				{
					obj.UnpatchSelf();
				}
				harmony = null;
				Fail(e);
			}
		}

		private void SceneLoaded(Scene scene, LoadSceneMode mode)
		{
			if (((Scene)(ref scene)).name == "Title" || ((Scene)(ref scene)).name == "WilIsland")
			{
				titleGate.Reset();
				LocalMapReady = false;
				mapIssue = null;
			}
			if (((Scene)(ref scene)).name == "Title")
			{
				MapRotation.Reset();
				ContinueCosmetics.Clear();
				if (harmony != null)
				{
					valid = true;
					error = null;
				}
				resumeRequested = false;
				requested = false;
				LocalMapReady = false;
				RunData.Pending = false;
				RunData.Dynamic = false;
				RunData.Folder = null;
				GeneratedData.UseFolder(null);
				RunData.Revision++;
				status = "Waiting for a new solo run";
			}
			if (((Scene)(ref scene)).name == "WilIsland")
			{
				requested = false;
				RunData.Pending = true;
				began = Time.realtimeSinceStartup;
			}
		}

		private void SceneUnloaded(Scene scene)
		{
			if (((Scene)(ref scene)).name != "WilIsland")
			{
				return;
			}
			MapRotation.Reset(preserveLaunch: true);
			pendingTreeTextures = null;
			LocalMapReady = false;
			ThunderfenDayNight.Reset();
			((MonoBehaviour)this).StopAllCoroutines();
			stableReadyFrames = 0;
			waitingFrame = null;
			applying = false;
			packet = null;
			readyFolder = null;
			foreach (Mesh item in owned)
			{
				if (Object.op_Implicit((Object)(object)item))
				{
					Object.Destroy((Object)(object)item);
				}
			}
			owned.Clear();
			LocalMapReady = false;
			RunData.Pending = false;
			RunData.Dynamic = false;
			GeneratedData.UseFolder(null);
			RunData.Revision++;
		}

		private void Update()
		{
			//IL_001a: 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_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			if (!valid)
			{
				return;
			}
			try
			{
				Scene sceneByName = SceneManager.GetSceneByName("WilIsland");
				bool isLoaded = ((Scene)(ref sceneByName)).isLoaded;
				if (SharedWorld.Online)
				{
					status = SharedWorld.Status;
				}
				if (PhotonNetwork.InRoom)
				{
					if (!isLoaded)
					{
						sceneByName = SceneManager.GetSceneByName("Airport");
						if (!((Scene)(ref sceneByName)).isLoaded)
						{
							goto IL_00e1;
						}
					}
					if (MapRotation.PreparedBaseline)
					{
						mapIssue = ReleasePeers.Check(isLoaded);
						if (mapIssue != null)
						{
							status = mapIssue;
							return;
						}
						if (!MapRotation.Resolve(isLoaded, resumeRequested))
						{
							status = MapRotation.Status;
							mapIssue = (IsMapIssue(status) ? status : null);
							ReportNow();
							return;
						}
					}
				}
				goto IL_00e1;
				IL_00e1:
				mapIssue = null;
				BindTreeTextures();
				if (isLoaded && !requested && PhotonNetwork.InRoom)
				{
					requested = true;
					StartRun();
				}
				if (isLoaded && requested && !LocalMapReady && RunData.Pending && !applying && packet != null)
				{
					Transform val = FindFrame();
					Transform currentSegment = null;
					MapHandler val2 = Singleton<MapHandler>.Instance;
					if (Object.op_Implicit((Object)(object)val2) && MapHandler.CurrentMapSegment != null && Object.op_Implicit((Object)(object)MapHandler.CurrentMapSegment.segmentParent))
					{
						currentSegment = MapHandler.CurrentMapSegment.segmentParent.transform;
					}
					string reason;
					bool flag = AssemblyReadiness.CanApply(val, currentSegment, out reason);
					if ((Object)(object)val != (Object)(object)waitingFrame)
					{
						waitingFrame = val;
						stableReadyFrames = 0;
					}
					stableReadyFrames = (flag ? (stableReadyFrames + 1) : 0);
					status = "Prepared layout ready; " + reason;
					if (stableReadyFrames >= 3)
					{
						((BaseUnityPlugin)this).Logger.LogInfo((object)("Assembly gate passed after native activation/material enrollment; seed " + RunData.Seed));
						((MonoBehaviour)this).StartCoroutine(SafeApply(val, packet));
					}
				}
				ReportNow();
			}
			catch (Exception e)
			{
				Fail(e);
			}
		}

		private static bool IsMapIssue(string message)
		{
			return !string.IsNullOrEmpty(message) && (message.Contains("required") || message.Contains("Cannot read") || message.Contains("does not match") || message.Contains("Invalid") || message.Contains("no matching") || message.Contains("no verified") || message == "Waiting for the host to publish this Thunderfen run." || message.StartsWith("Thunderfen Continue map choice is unavailable", StringComparison.Ordinal));
		}

		private void TrackStall()
		{
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			if (Time.unscaledTime < nextStallCheck)
			{
				return;
			}
			nextStallCheck = Time.unscaledTime + 1f;
			string text = null;
			try
			{
				Scene sceneByName = SceneManager.GetSceneByName("WilIsland");
				if (((Scene)(ref sceneByName)).isLoaded)
				{
					if (!Object.op_Implicit((Object)(object)stallFrame))
					{
						stallFrame = FindFrame();
					}
					GameObject val = ((Object.op_Implicit((Object)(object)Singleton<MapHandler>.Instance) && MapHandler.CurrentMapSegment != null) ? MapHandler.CurrentMapSegment.segmentParent : null);
					if (Object.op_Implicit((Object)(object)stallFrame) && Object.op_Implicit((Object)(object)val) && stallFrame.IsChildOf(val.transform))
					{
						if (segmentSince < 0f)
						{
							segmentSince = Time.unscaledTime;
						}
						if (Time.unscaledTime - segmentSince >= 20f)
						{
							text = StallReason();
						}
					}
					else
					{
						segmentSince = -1f;
					}
				}
				else
				{
					segmentSince = -1f;
					stallFrame = null;
				}
			}
			catch (Exception ex)
			{
				text = "the load check failed (" + ex.Message + ")";
			}
			stallNotice = ((text == null) ? null : ("Thunderfen 1.0.7 did not finish loading this biome: " + text + ". The terrain here is incomplete. If this does not clear, return to the Airport, restart PEAK on every PC and try again. Details: BepInEx/LogOutput.log."));
			if (text != stallLogged)
			{
				if (text != null)
				{
					((BaseUnityPlugin)this).Logger.LogWarning((object)("Biome load stalled: " + text));
				}
				else if (stallLogged != null)
				{
					((BaseUnityPlugin)this).Logger.LogInfo((object)"Biome load stall cleared.");
				}
				stallLogged = text;
			}
		}

		private string StallReason()
		{
			if (!LocalMapReady)
			{
				return "the prepared map was not assembled (" + status + ")";
			}
			string text = SharedWorld.UnhealthyModule();
			if (text != null)
			{
				return text + " stopped working";
			}
			if (!SharedWorld.Ready || RunData.Pending)
			{
				return SharedWorld.WaitingFor ?? SharedWorld.Status;
			}
			return null;
		}

		private void LateUpdate()
		{
			//IL_0067: 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_007c: 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)
			TrackStall();
			string text = ((error == null) ? mapIssue : failureNotice);
			if (text == null && SharedWorld.StartupFailure != null)
			{
				text = SharedWorld.StartupFailure + " could not start. See BepInEx/LogOutput.log.";
			}
			if (text == null && SharedWorld.Status.Contains("mismatch"))
			{
				text = SharedWorld.Status;
			}
			Scene sceneByName = SceneManager.GetSceneByName("Airport");
			int num;
			if (!((Scene)(ref sceneByName)).isLoaded)
			{
				sceneByName = SceneManager.GetSceneByName("WilIsland");
				num = (((Scene)(ref sceneByName)).isLoaded ? 1 : 0);
			}
			else
			{
				num = 1;
			}
			bool flag = (byte)num != 0;
			if (text == null)
			{
				text = stallNotice;
			}
			if (text == null || !flag)
			{
				if (Object.op_Implicit((Object)(object)loadNotice))
				{
					Object.Destroy((Object)(object)((Component)((Component)loadNotice).transform.parent).gameObject);
					loadNotice = null;
				}
				return;
			}
			bool chinese = NoticeText.Chinese;
			if (Object.op_Implicit((Object)(object)loadNotice) && noticeChinese != chinese)
			{
				Object.Destroy((Object)(object)((Component)((Component)loadNotice).transform.parent).gameObject);
				loadNotice = null;
			}
			if (!Object.op_Implicit((Object)(object)loadNotice))
			{
				noticeChinese = chinese;
				loadNotice = CreateLoadNotice();
				shownEnglish = null;
			}
			if (shownEnglish != text)
			{
				shownEnglish = text;
				loadNotice.text = NoticeText.Localize(text);
			}
		}

		private Text CreateLoadNotice()
		{
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Expected O, but got Unknown
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Expected O, but got Unknown
			//IL_011d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0149: Unknown result type (might be due to invalid IL or missing references)
			//IL_014e: Unknown result type (might be due to invalid IL or missing references)
			//IL_014f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0157: Unknown result type (might be due to invalid IL or missing references)
			//IL_0159: Unknown result type (might be due to invalid IL or missing references)
			//IL_015a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0162: Unknown result type (might be due to invalid IL or missing references)
			//IL_0176: Unknown result type (might be due to invalid IL or missing references)
			//IL_018d: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c4: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject("Thunderfen Load Notice", new Type[3]
			{
				typeof(RectTransform),
				typeof(Canvas),
				typeof(CanvasScaler)
			});
			Canvas component = val.GetComponent<Canvas>();
			component.renderMode = (RenderMode)0;
			component.sortingOrder = 25000;
			CanvasScaler component2 = val.GetComponent<CanvasScaler>();
			component2.uiScaleMode = (ScaleMode)1;
			component2.referenceResolution = new Vector2(1920f, 1080f);
			component2.matchWidthOrHeight = 0.5f;
			GameObject val2 = new GameObject("Message", new Type[3]
			{
				typeof(RectTransform),
				typeof(Text),
				typeof(Shadow)
			});
			val2.transform.SetParent(val.transform, false);
			Text component3 = val2.GetComponent<Text>();
			component3.font = (noticeChinese ? NoticeText.ChineseFont() : Resources.GetBuiltinResource<Font>("LegacyRuntime.ttf"));
			component3.fontSize = 21;
			component3.alignment = (TextAnchor)2;
			((Graphic)component3).color = new Color(1f, 0.9f, 0.77f);
			((Graphic)component3).raycastTarget = false;
			component3.supportRichText = false;
			RectTransform rectTransform = ((Graphic)component3).rectTransform;
			Vector2 val3 = (rectTransform.pivot = Vector2.one);
			Vector2 anchorMin = (rectTransform.anchorMax = val3);
			rectTransform.anchorMin = anchorMin;
			rectTransform.anchoredPosition = new Vector2(-24f, -24f);
			rectTransform.sizeDelta = new Vector2(760f, 150f);
			component3.horizontalOverflow = (HorizontalWrapMode)0;
			component3.verticalOverflow = (VerticalWrapMode)1;
			val2.GetComponent<Shadow>().effectColor = new Color(0f, 0f, 0f, 0.95f);
			return component3;
		}

		private void StartRun()
		{
			LocalMapReady = false;
			stableReadyFrames = 0;
			waitingFrame = null;
			began = Time.realtimeSinceStartup;
			RunData.Pending = true;
			RunData.Dynamic = true;
			packet = null;
			readyFolder = null;
			applying = false;
			error = null;
			if (!MapRotation.PreparedBaseline)
			{
				throw new InvalidDataException("Thunderfen requires a prepared map. Reinstall its bundled map data.");
			}
			readyFolder = MapRotation.SelectedFolder ?? ContentPaths.Baseline;
			GeneratedData.UseFolder(readyFolder);
			packet = LayoutPacket.Read(GeneratedData.Read("runtime-layout.bin"));
			if (packet.seed != GeneratedData.Seed)
			{
				throw new InvalidDataException("Prepared map seed differs from selected manifest");
			}
			RunData.Seed = packet.seed;
			status = "Prepared Thunderfen ready; waiting for biome activation";
			((BaseUnityPlugin)this).Logger.LogInfo((object)(status + "; seed " + RunData.Seed));
			ReportNow(force: true);
		}

		private Transform FindFrame()
		{
			//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)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Expected O, but got Unknown
			Scene sceneByName = SceneManager.GetSceneByName("WilIsland");
			GameObject val = ((IEnumerable<GameObject>)((Scene)(ref sceneByName)).GetRootGameObjects()).FirstOrDefault((Func<GameObject, bool>)((GameObject g) => ((Object)g).name == "Map"));
			if (!Object.op_Implicit((Object)(object)val))
			{
				return null;
			}
			Transform val2 = val.transform.Find("Global");
			if (!Object.op_Implicit((Object)(object)val2))
			{
				return null;
			}
			foreach (Transform item in val2)
			{
				Transform val3 = item;
				if (((Object)val3).name.Contains("first-ridge"))
				{
					Transform val4 = ((IEnumerable<Transform>)((Component)val3).GetComponentsInChildren<Transform>(true)).FirstOrDefault((Func<Transform, bool>)((Transform x) => ((Object)x).name == "PF_HybridTerrain" && Object.op_Implicit((Object)(object)x.parent) && ((Object)x.parent).name == "RootsTerrain"));
					if (Object.op_Implicit((Object)(object)val4))
					{
						return val4;
					}
				}
			}
			return null;
		}

		private IEnumerator SafeApply(Transform frame, LayoutPacket data)
		{
			IEnumerator worker = Apply(frame, data);
			while (true)
			{
				bool more;
				try
				{
					more = worker.MoveNext();
				}
				catch (Exception ex)
				{
					Exception e = ex;
					Fail(e);
					break;
				}
				if (!more)
				{
					break;
				}
				yield return worker.Current;
			}
		}

		private IEnumerator Apply(Transform frame, LayoutPacket data)
		{
			applying = true;
			status = "Assembling Thunderfen";
			IEnumerator worker = RuntimeAssembler.BuildPrepared(frame, data, owned, GeneratedData.Read("native-props.bin"));
			while (worker.MoveNext())
			{
				yield return worker.Current;
			}
			if (Chainloader.PluginInfos.TryGetValue("local.peak.poisonforest.rain", out var rainInfo) && Object.op_Implicit((Object)(object)rainInfo.Instance))
			{
				FieldInfo geometryField = ((object)rainInfo.Instance).GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).FirstOrDefault((FieldInfo f) => f.FieldType.FullName == "PoisonForestRain.RainGeometry");
				if (geometryField == null)
				{
					throw new Exception("Rain shelter cache API changed");
				}
				object geometry = geometryField.GetValue(rainInfo.Instance);
				geometry.GetType().GetMethod("SetRoot").Invoke(geometry, new object[1]);
				if (((Component)frame).gameObject.activeInHierarchy)
				{
					geometry.GetType().GetMethod("SetRoot").Invoke(geometry, new object[1] { frame.parent.parent.parent });
				}
			}
			pendingTreeTextures = (from material in ((Component)frame.parent.parent.parent).GetComponentsInChildren<MeshRenderer>(true).SelectMany((MeshRenderer renderer) => ((Renderer)renderer).sharedMaterials)
				where Object.op_Implicit((Object)(object)material) && Object.op_Implicit((Object)(object)material.shader) && ((Object)material.shader).name == "PoisonForest/TwistedTreeLit"
				select material).Distinct().ToArray();
			BindTreeTextures();
			RunData.Folder = readyFolder;
			RunData.Revision++;
			LocalMapReady = true;
			RunData.Pending = SharedWorld.Online;
			RunData.Dynamic = true;
			status = "Thunderfen ready — seed " + RunData.Seed;
			applying = false;
			((BaseUnityPlugin)this).Logger.LogInfo((object)(status + "; " + data.trees.Length + " trees, " + data.water.Length + " pools, catalogs committed together."));
			ReportNow(force: true);
		}

		private void BindTreeTextures()
		{
			if (pendingTreeTextures == null)
			{
				return;
			}
			Material[] array = pendingTreeTextures;
			foreach (Material val in array)
			{
				if (Object.op_Implicit((Object)(object)val) && !NativeBarkTextures.Bind(val, ((Object)val).name.StartsWith("TwistedBark", StringComparison.Ordinal)))
				{
					return;
				}
			}
			pendingTreeTextures = null;
		}

		private static string Summary(Exception e)
		{
			Exception baseException = e.GetBaseException();
			string text = (string.IsNullOrEmpty(baseException.Message) ? baseException.GetType().Name : baseException.Message);
			text = text.Replace('\r', ' ').Replace('\n', ' ').Trim();
			return (text.Length > 260) ? (text.Substring(0, 257) + "...") : text;
		}

		private void Fail(Exception e)
		{
			//IL_0040: 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)
			LocalMapReady = false;
			error = e.ToString();
			failureNotice = "Thunderfen 1.0.7 failed to load: " + Summary(e) + " Details: BepInEx/LogOutput.log.";
			status = failureNotice;
			Scene sceneByName = SceneManager.GetSceneByName("WilIsland");
			RunData.Pending = ((Scene)(ref sceneByName)).isLoaded;
			valid = false;
			((BaseUnityPlugin)this).Logger.LogError((object)error);
			try
			{
				ReportNow(force: true);
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)ex.Message);
			}
		}

		private void ReportNow(bool force = false)
		{
			if (RuntimeDiagnostics.PeriodicSnapshots && (force || !(Time.unscaledTime < nextReport)))
			{
				nextReport = Time.unscaledTime + 2f;
				Directory.CreateDirectory(runRoot);
				string contents = JsonUtility.ToJson((object)new Report
				{
					utc = DateTime.UtcNow.ToString("O"),
					nativeHour = (Object.op_Implicit((Object)(object)DayNightManager.instance) ? DayNightManager.instance.timeOfDay : (-1f)),
					nativeDay = (Object.op_Implicit((Object)(object)DayNightManager.instance) ? DayNightManager.instance.dayCount : 0),
					nativeLightingProfile = ((Object.op_Implicit((Object)(object)DayNightManager.instance) && Object.op_Implicit((Object)(object)DayNightManager.instance.currentProfile)) ? ((Object)DayNightManager.instance.currentProfile).name : null),
					mist = ThunderfenMist.Describe(),
					resumePlacement = ResumePlacement.Last,
					resumeCosmetics = ContinueCosmetics.Describe(),
					resumeHolds = ResumePlacement.Holds,
					resumeCorrections = ResumePlacement.Corrections,
					status = status,
					error = error,
					folder = readyFolder,
					localMapReady = LocalMapReady,
					offline = PhotonNetwork.OfflineMode,
					pending = RunData.Pending,
					dynamic = RunData.Dynamic,
					applying = applying,
					seed = RunData.Seed,
					revision = RunData.Revision,
					elapsed = Time.realtimeSinceStartup - began
				}, true);
				File.WriteAllText(Path.Combine(runRoot, "solo-generation-state.json"), contents);
				if (ThunderfenMist.Active)
				{
					File.WriteAllText(Path.Combine(runRoot, "solo-generation-last-active.json"), contents);
				}
			}
		}

		private void OnDestroy()
		{
			if (Object.op_Implicit((Object)(object)loadNotice))
			{
				Object.Destroy((Object)(object)((Component)((Component)loadNotice).transform.parent).gameObject);
			}
			SceneManager.sceneLoaded -= SceneLoaded;
			SceneManager.sceneUnloaded -= SceneUnloaded;
			Harmony obj = harmony;
			if (obj != null)
			{
				obj.UnpatchSelf();
			}
		}

		internal static void ClearResumeRequest()
		{
			if (Object.op_Implicit((Object)(object)instance))
			{
				instance.resumeRequested = false;
			}
		}
	}
	[Serializable]
	public sealed class GeneratedRunHeader
	{
		public bool complete;

		public string run;

		public int seed;

		public int attempt;

		public int nests;

		public double generationSeconds;
	}
	public static class SeedSource
	{
		public static int Next()
		{
			byte[] array = new byte[4];
			using (RandomNumberGenerator randomNumberGenerator = RandomNumberGenerator.Create())
			{
				randomNumberGenerator.GetBytes(array);
			}
			return BitConverter.ToInt32(array, 0) & 0x7FFFFFFF;
		}
	}
	public sealed class LayoutPacket
	{
		public sealed class Geometry
		{
			public string name;

			public Vector3[] vertices;

			public Vector3[] normals;

			public int[] indices;
		}

		public sealed class Prop
		{
			public string name;

			public Matrix4x4 matrix;
		}

		public sealed class Tree
		{
			public string name;

			public int variant;

			public Vector3 position;

			public Vector3 scale;

			public Quaternion rotation;
		}

		public int seed;

		public int attempt;

		public Geometry ground;

		public Geometry[] mountain = new Geometry[0];

		public Geometry[] water;

		public Prop[] props;

		public Tree[] trees;

		private static int Count(BinaryReader r, int lo, int hi)
		{
			int num = r.ReadInt32();
			if (num < lo || num > hi)
			{
				throw new InvalidDataException("Runtime layout count");
			}
			return num;
		}

		private static float F(BinaryReader r)
		{
			float num = r.ReadSingle();
			if (float.IsNaN(num) || float.IsInfinity(num) || Math.Abs(num) > 10000f)
			{
				throw new InvalidDataException("Runtime layout coordinate");
			}
			return num;
		}

		private static string Text(BinaryReader r)
		{
			int num = Count(r, 1, 80);
			byte[] array = r.ReadBytes(num);
			if (array.Length != num)
			{
				throw new EndOfStreamException();
			}
			string text = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true).GetString(array);
			if (text.IndexOfAny(new char[3] { '/', '\\', ':' }) >= 0)
			{
				throw new InvalidDataException("Runtime object name");
			}
			return text;
		}

		private static Vector3 V(BinaryReader r)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			return new Vector3(F(r), F(r), F(r));
		}

		private static Geometry Mesh(BinaryReader r)
		{
			//IL_009a: 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_00c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
			Geometry geometry = new Geometry
			{
				name = Text(r)
			};
			int num = Count(r, 3, 300000);
			int num2 = Count(r, 3, 1800000);
			if (num2 % 3 != 0 || (long)num * 24L + num2 * 4 > r.BaseStream.Length - r.BaseStream.Position)
			{
				throw new InvalidDataException("Runtime mesh length");
			}
			geometry.vertices = (Vector3[])(object)new Vector3[num];
			geometry.normals = (Vector3[])(object)new Vector3[num];
			geometry.indices = new int[num2];
			for (int i = 0; i < num; i++)
			{
				geometry.vertices[i] = V(r);
			}
			for (int j = 0; j < num; j++)
			{
				geometry.normals[j] = V(r);
			}
			for (int k = 0; k < num2; k++)
			{
				int num3 = r.ReadInt32();
				if (num3 < 0 || num3 >= num)
				{
					throw new InvalidDataException("Runtime mesh index");
				}
				geometry.indices[k] = num3;
			}
			return geometry;
		}

		public static LayoutPacket Read(byte[] bytes)
		{
			//IL_031b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0320: Unknown result type (might be due to invalid IL or missing references)
			//IL_0341: 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_034e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0353: Unknown result type (might be due to invalid IL or missing references)
			//IL_024b: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ae: Unknown result type (might be due to invalid IL or missing references)
			if (bytes == null || bytes.Length > 32000000)
			{
				throw new InvalidDataException("Runtime layout length");
			}
			using BinaryReader binaryReader = new BinaryReader(new MemoryStream(bytes));
			uint num = binaryReader.ReadUInt32();
			if (num != 827475536 && num != 844252752)
			{
				throw new InvalidDataException("Runtime layout signature");
			}
			LayoutPacket layoutPacket = new LayoutPacket
			{
				seed = binaryReader.ReadInt32(),
				attempt = Count(binaryReader, 0, 16),
				ground = Mesh(binaryReader)
			};
			if (layoutPacket.ground.name != "PF_PoolRaisedGround")
			{
				throw new InvalidDataException("Runtime ground name");
			}
			if (num == 844252752)
			{
				int num2 = Count(binaryReader, 8, 8);
				layoutPacket.mountain = new Geometry[num2];
				for (int i = 0; i < num2; i++)
				{
					layoutPacket.mountain[i] = Mesh(binaryReader);
					if (layoutPacket.mountain[i].name != "PF_MountainV2_" + i.ToString("D2"))
					{
						throw new InvalidDataException("Mountain chunk identity");
					}
				}
			}
			int num3 = Count(binaryReader, 1, 64);
			layoutPacket.water = new Geometry[num3];
			HashSet<string> hashSet = new HashSet<string>();
			for (int j = 0; j < num3; j++)
			{
				layoutPacket.water[j] = Mesh(binaryReader);
				if (!layoutPacket.water[j].name.StartsWith("PF_PoolWater_", StringComparison.Ordinal) || !hashSet.Add(layoutPacket.water[j].name))
				{
					throw new InvalidDataException("Runtime water identity");
				}
			}
			num3 = Count(binaryReader, 1, 128);
			layoutPacket.props = new Prop[num3];
			for (int k = 0; k < num3; k++)
			{
				Prop prop = new Prop
				{
					name = Text(binaryReader)
				};
				if ((!prop.name.StartsWith("PF_PoolBankRock_", StringComparison.Ordinal) && !prop.name.StartsWith("PF_PoolDryOutcrop_", StringComparison.Ordinal)) || !hashSet.Add(prop.name))
				{
					throw new InvalidDataException("Runtime prop identity");
				}
				Matrix4x4 matrix = default(Matrix4x4);
				for (int l = 0; l < 16; l++)
				{
					((Matrix4x4)(ref matrix))[l / 4, l % 4] = F(binaryReader);
				}
				if (Math.Abs(((Matrix4x4)(ref matrix))[3, 3] - 1f) > 0.0001f)
				{
					throw new InvalidDataException("Runtime prop transform");
				}
				prop.matrix = matrix;
				layoutPacket.props[k] = prop;
			}
			num3 = Count(binaryReader, 12, 512);
			layoutPacket.trees = new Tree[num3];
			for (int m = 0; m < num3; m++)
			{
				Tree tree = new Tree
				{
					name = Text(binaryReader),
					variant = Count(binaryReader, 0, 11),
					position = V(binaryReader)
				};
				tree.rotation = new Quaternion(F(binaryReader), F(binaryReader), F(binaryReader), F(binaryReader));
				tree.scale = V(binaryReader);
				if (tree.name != "PF_TwistedFan_" + m.ToString("D3") || tree.variant != m % 12 || tree.scale.x <= 0f || tree.scale.y <= 0f || tree.scale.z <= 0f || ((Vector3)(ref tree.scale)).magnitude > 15f)
				{
					throw new InvalidDataException("Runtime tree identity");
				}
				layoutPacket.trees[m] = tree;
			}
			if (binaryReader.BaseStream.Position != binaryReader.BaseStream.Length)
			{
				throw new InvalidDataException("Trailing runtime layout bytes");
			}
			return layoutPacket;
		}
	}
	public static class RuntimeAssembler
	{
		public static IEnumerator BuildPrepared(Transform frame, LayoutPacket data, List<Mesh> owned, byte[] camp)
		{
			IEnumerator build = Build(frame, data, owned);
			while (build.MoveNext())
			{
				yield return build.Current;
			}
			PreparedCampTrees.Apply(frame, camp);
			Physics.SyncTransforms();
		}

		private static Mesh MakeMesh(LayoutPacket.Geometry g)
		{
			//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)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Expected O, but got Unknown
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a8: 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_00b4: Unknown result type (might be due to invalid IL or missing references)
			Mesh val = new Mesh
			{
				name = g.name + "_FreshSolo",
				indexFormat = (IndexFormat)(g.vertices.Length > 65535)
			};
			val.vertices = g.vertices;
			val.normals = g.normals;
			Vector2[] array = (Vector2[])(object)new Vector2[g.vertices.Length];
			Color[] array2 = (Color[])(object)new Color[g.vertices.Length];
			for (int i = 0; i < array.Length; i++)
			{
				array[i] = new Vector2(g.vertices[i].x * 0.12f, g.vertices[i].z * 0.12f);
				array2[i] = Color.white;
			}
			val.uv = array;
			val.colors = array2;
			val.triangles = g.indices;
			val.RecalculateTangents();
			val.RecalculateBounds();
			return val;
		}

		private static void Matrix(Transform t, Matrix4x4 m)
		{
			//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)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: 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_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			Vector4 column = ((Matrix4x4)(ref m)).GetColumn(0);
			float magnitude = ((Vector4)(ref column)).magnitude;
			column = ((Matrix4x4)(ref m)).GetColumn(1);
			float magnitude2 = ((Vector4)(ref column)).magnitude;
			column = ((Matrix4x4)(ref m)).GetColumn(2);
			Vector3 val = default(Vector3);
			((Vector3)(ref val))..ctor(magnitude, magnitude2, ((Vector4)(ref column)).magnitude);
			if (((Matrix4x4)(ref m)).determinant < 0f)
			{
				val.x = 0f - val.x;
			}
			t.localPosition = Vector4.op_Implicit(((Matrix4x4)(ref m)).GetColumn(3));
			t.localRotation = Quaternion.LookRotation(Vector4.op_Implicit(((Matrix4x4)(ref m)).GetColumn(2)), Vector4.op_Implicit(((Matrix4x4)(ref m)).GetColumn(1)));
			t.localScale = val;
		}

		public static IEnumerator Build(Transform frame, LayoutPacket data, List<Mesh> owned)
		{
			Dictionary<string, Transform> all = ((Component)frame).GetComponentsInChildren<Transform>(true).ToDictionary((Transform val) => ((Object)val).name, (Transform result) => result);
			Transform group = frame.parent.Find("PF_TwistedFanTrees");
			if (!Object.op_Implicit((Object)(object)group))
			{
				throw new Exception("Custom tree group missing");
			}
			Transform[] trees = ((IEnumerable)group).Cast<Transform>().OrderBy<Transform, string>((Transform val) => ((Object)val).name, StringComparer.Ordinal).ToArray();
			if (trees.Length != data.trees.Length)
			{
				throw new Exception("Custom tree library population differs");
			}
			LayoutPacket.Prop[] props = data.props;
			foreach (LayoutPacket.Prop p in props)
			{
				if (!all.ContainsKey(p.name))
				{
					throw new Exception("Reusable rock missing: " + p.name);
				}
			}
			Transform ground = all["PF_PoolRaisedGround"];
			MeshRenderer[] oldWater = (from r in ((Component)frame).GetComponentsInChildren<MeshRenderer>(true)
				where ((Object)r).name.StartsWith("PF_PoolWater_", StringComparison.Ordinal)
				select r).ToArray();
			if (oldWater.Length == 0)
			{
				throw new Exception("Reusable pool material missing");
			}
			LayoutPacket.Geometry[] mountain = data.mountain;
			foreach (LayoutPacket.Geometry g in mountain)
			{
				if (!all.ContainsKey(g.name) || !Object.op_Implicit((Object)(object)((Component)all[g.name]).GetComponent<MeshCollider>()))
				{
					throw new Exception("Seeded mountain slot missing: " + g.name);
				}
			}
			List<Mesh> mountainMeshes = new List<Mesh>();
			LayoutPacket.Geometry[] mountain2 = data.mountain;
			foreach (LayoutPacket.Geometry g2 in mountain2)
			{
				Mesh m = MakeMesh(g2);
				owned.Add(m);
				Physics.BakeMesh(((Object)m).GetInstanceID(), false);
				mountainMeshes.Add(m);
				yield return null;
			}
			List<MeshRenderer> waterTargets = new List<MeshRenderer>();
			List<Mesh> waterMeshes = new List<Mesh>();
			Mesh bed = MakeMesh(data.ground);
			owned.Add(bed);
			Physics.BakeMesh(((Object)bed).GetInstanceID(), false);
			yield return null;
			LayoutPacket.Geometry[] water = data.water;
			foreach (LayoutPacket.Geometry g3 in water)
			{
				Mesh m2 = MakeMesh(g3);
				owned.Add(m2);
				MeshRenderer renderer = ((IEnumerable<MeshRenderer>)oldWater).FirstOrDefault((Func<MeshRenderer, bool>)((MeshRenderer r) => ((Object)r).name == g3.name));
				if (!Object.op_Implicit((Object)(object)renderer))
				{
					GameObject go = new GameObject(g3.name);
					go.SetActive(false);
					go.layer = 0;
					go.transform.SetParent(frame, false);
					go.AddComponent<MeshFilter>();
					renderer = go.AddComponent<MeshRenderer>();
					((Renderer)renderer).sharedMaterial = ((Renderer)oldWater[0]).sharedMaterial;
					((Renderer)renderer).shadowCastingMode = (ShadowCastingMode)0;
					((Renderer)renderer).receiveShadows = false;
				}
				waterTargets.Add(renderer);
				waterMeshes.Add(m2);
				yield return null;
			}
			((Component)ground).GetComponent<MeshFilter>().sharedMesh = bed;
			((Component)ground).GetComponent<MeshCollider>().sharedMesh = bed;
			for (int i = 0; i < data.mountain.Length; i++)
			{
				Transform node = all[data.mountain[i].name];
				((Component)node).GetComponent<MeshFilter>().sharedMesh = mountainMeshes[i];
				((Component)node).GetComponent<MeshCollider>().sharedMesh = mountainMeshes[i];
			}
			LayoutPacket.Prop[] props2 = data.props;
			foreach (LayoutPacket.Prop p2 in props2)
			{
				Matrix(all[p2.name], p2.matrix);
			}
			for (int i2 = 0; i2 < trees.Length; i2++)
			{
				LayoutPacket.Tree t = data.trees[i2];
				if (((Object)trees[i2]).name != t.name)
				{
					throw new Exception("Runtime tree roster mismatch");
				}
				Matrix(trees[i2], group.worldToLocalMatrix * frame.localToWorldMatrix * Matrix4x4.TRS(t.position, t.rotation, t.scale));
			}
			MeshRenderer[] array = oldWater;
			foreach (MeshRenderer old in array)
			{
				((Renderer)old).enabled = false;
			}
			for (int i3 = 0; i3 < waterTargets.Count; i3++)
			{
				MeshRenderer renderer2 = waterTargets[i3];
				((Component)renderer2).GetComponent<MeshFilter>().sharedMesh = waterMeshes[i3];
				((Renderer)renderer2).enabled = true;
				((Component)renderer2).gameObject.SetActive(true);
			}
			Physics.SyncTransforms();
		}
	}
	public static class AssemblyReadiness
	{
		public static bool CanApply(Transform frame, Transform currentSegment, out string reason)
		{
			if (!Placed(frame, currentSegment, out reason, out var rocks))
			{
				return false;
			}
			int num = PendingMaterials(rocks);
			if (num > 0)
			{
				reason = "Waiting for native terrain materials (" + num + " renderers)";
				return false;
			}
			reason = "Native segment active and all terrain materials enrolled";
			return true;
		}

		public static bool CanAdmit(Transform frame, Transform currentSegment, out string reason, out int pendingMaterials)
		{
			pendingMaterials = 0;
			if (!Placed(frame, currentSegment, out reason, out var rocks))
			{
				return false;
			}
			pendingMaterials = PendingMaterials(rocks);
			reason = "Native segment active";
			return true;
		}

		private static bool Placed(Transform frame, Transform currentSegment, out string reason, out MeshRenderer[] rocks)
		{
			rocks = null;
			if (!Object.op_Implicit((Object)(object)frame) || !((Component)frame).gameObject.activeInHierarchy)
			{
				reason = "Waiting for the custom floor to activate";
				return false;
			}
			if (!Object.op_Implicit((Object)(object)currentSegment) || !frame.IsChildOf(currentSegment))
			{
				reason = "Waiting for the native segment transition";
				return false;
			}
			rocks = (from r in ((Component)frame).GetComponentsInChildren<MeshRenderer>(true)
				where !((Object)r).name.StartsWith("PF_PoolWater_", StringComparison.Ordinal)
				select r).ToArray();
			if (rocks.Length == 0)
			{
				reason = "Waiting for native terrain renderers";
				return false;
			}
			reason = "";
			return true;
		}

		private static int PendingMaterials(MeshRenderer[] rocks)
		{
			return rocks.Count((MeshRenderer r) => ((Renderer)r).sharedMaterials.Length == 0 || ((Renderer)r).sharedMaterials.Any((Material m) => !Object.op_Implicit((Object)(object)m) || !Object.op_Implicit((Object)(object)m.shader) || ((Object)m.shader).name != "W/Peak_Rock" || !m.HasProperty("_Texture1") || !Object.op_Implicit((Object)(object)m.GetTexture("_Texture1"))));
		}
	}
	public sealed class EntryTitleGate
	{
		private bool shown;

		public void Reset()
		{
			shown = false;
		}

		public bool Allow(string title)
		{
			if (title != "喵喵" && title != "雷鸣瘴泽" && title != "Thunderfen")
			{
				return true;
			}
			if (shown)
			{
				return false;
			}
			shown = true;
			return true;
		}
	}
	public static class ThunderfenMist
	{
		[HarmonyPatch(typeof(OrbFogHandler), "InitNewSphere", new Type[] { typeof(FogSphereOrigin) })]
		private static class InitHook
		{
			[HarmonyPostfix]
			private static void Postfix(OrbFogHandler __instance)
			{
				initCalls++;
				Ensure(__instance, "InitNewSphere");
			}
		}

		[HarmonyPatch(typeof(OrbFogHandler), "Update", new Type[] { })]
		private static class UpdateHook
		{
			[HarmonyPrefix]
			private static void Prefix(OrbFogHandler __instance)
			{
				updateCalls++;
				Ensure(__instance, "Update");
			}
		}

		[HarmonyPatch(typeof(OrbFogHandler), "PlayersHaveMovedOn", new Type[] { })]
		private static class ProgressHook
		{
			[HarmonyPrefix]
			private static void Prefix(OrbFogHandler __instance)
			{
				Ensure(__instance, "PlayersHaveMovedOn");
			}
		}

		[HarmonyPatch(typeof(OrbFogHandler), "TimeToMove", new Type[] { })]
		private static class TimeoutHook
		{
			[HarmonyPrefix]
			private static void Prefix(OrbFogHandler __instance)
			{
				Ensure(__instance, "TimeToMove");
			}
		}

		[HarmonyPatch(typeof(OrbFogHandler), "StartMovingRPC", new Type[] { })]
		private static class StartHook
		{
			[HarmonyPrefix]
			private static void Prefix(OrbFogHandler __instance)
			{
				if (Object.op_Implicit((Object)(object)Scope(__instance, out var _)))
				{
					handler = __instance;
					starts++;
					lastStart = (((float)Get(__instance, "currentWaitTime") > (float)Get(__instance, "maxWaitTime")) ? "native maximum wait" : "all living players crossed progress thresholds");
					Debug.Log((object)("Thunderfen mist native start: " + Describe()));
				}
			}
		}

		private const BindingFlags Flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;

		private static readonly FieldInfo originField = AccessTools.Field(typeof(OrbFogHandler), "origins");

		private static OrbFogHandler handler;

		private static Transform initializedRoot;

		private static Transform cachedParent;

		private static Transform cachedRoot;

		private static int initializedId = -1;

		private static int initCalls;

		private static int initializations;

		private static int updateCalls;

		private static int starts;

		private static string lastStart = "not started";

		private static string lastHook = "not initialized";

		private static float nextFind;

		public static Transform CurrentRoot
		{
			get
			{
				MapHandler instance = Singleton<MapHandler>.Instance;
				MapSegment val = (Object.op_Implicit((Object)(object)instance) ? MapHandler.CurrentMapSegment : null);
				Transform val2 = ((val != null && Object.op_Implicit((Object)(object)val.segmentParent)) ? val.segmentParent.transform : null);
				if ((Object)(object)val2 != (Object)(object)cachedParent || (!Object.op_Implicit((Object)(object)cachedRoot) && Time.unscaledTime >= nextFind))
				{
					cachedParent = val2;
					cachedRoot = ThunderfenSceneScope.Find(val2);
					nextFind = Time.unscaledTime + 0.25f;
				}
				return cachedRoot;
			}
		}

		public static bool Active => Object.op_Implicit((Object)(object)CurrentRoot) && Object.op_Implicit((Object)(object)CurrentRoot.Find("FloorRoot")) && ((Component)CurrentRoot.Find("FloorRoot")).gameObject.activeInHierarchy;

		private static object Get(OrbFogHandler h, string field)
		{
			return AccessTools.Field(typeof(OrbFogHandler), field).GetValue(h);
		}

		private static void Set(OrbFogHandler h, string field, object value)
		{
			AccessTools.Field(typeof(OrbFogHandler), field).SetValue(h, value);
		}

		private static Transform Scope(OrbFogHandler h, out FogSphereOrigin origin)
		{
			origin = null;
			MapHandler instance = Singleton<MapHandler>.Instance;
			if (!Object.op_Implicit((Object)(object)h) || !Object.op_Implicit((Object)(object)instance))
			{
				return null;
			}
			MapSegment currentMapSegment = MapHandler.CurrentMapSegment;
			Transform currentRoot = CurrentRoot;
			if (currentMapSegment == null || !Object.op_Implicit((Object)(object)currentRoot) || instance.segments == null)
			{
				return null;
			}
			int num = Array.IndexOf(instance.segments, currentMapSegment);
			if (num < 0 || h.currentID != num)
			{
				return null;
			}
			if (!(originField.GetValue(h) is FogSphereOrigin[] array) || h.currentID < 0 || h.currentID >= array.Length || !Object.op_Implicit((Object)(object)array[h.currentID]))
			{
				return null;
			}
			origin = array[h.currentID];
			return currentRoot;
		}

		public static void Ensure(OrbFogHandler h, string hook)
		{
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e2: Unknown result type (might be due to invalid IL or missing references)
			if (hook != "Update")
			{
				nextFind = 0f;
			}
			FogSphereOrigin origin;
			Transform val = Scope(h, out origin);
			if (!Object.op_Implicit((Object)(object)val))
			{
				return;
			}
			Transform val2 = val.Find("RuntimeMarkers/FogBeginAnchor");
			Transform val3 = val.Find("CampfireRoot");
			if (!Object.op_Implicit((Object)(object)val2) || !Object.op_Implicit((Object)(object)val3))
			{
				return;
			}
			bool flag = (Object)(object)handler != (Object)(object)h || (Object)(object)initializedRoot != (Object)(object)val || initializedId != h.currentID;
			handler = h;
			Set(h, "currentStartHeight", MistTiming.Threshold(val2.position.y, val3.position.y));
			Set(h, "currentStartForward", MistTiming.Threshold(val2.position.z, val3.position.z));
			if (!flag)
			{
				return;
			}
			initializedRoot = val;
			initializedId = h.currentID;
			initializations++;
			lastHook = hook;
			lastStart = "waiting for climb progress";
			bool flag2 = PhotonNetwork.IsMasterClient || PhotonNetwork.OfflineMode || hook == "InitNewSphere";
			if (flag2)
			{
				Set(h, "currentWaitTime", 0f);
				Set(h, "isMoving", false);
				Set(h, "hasArrived", false);
				Set(h, "currentSize", origin.size);
				object obj = Get(h, "sphere");
				FogSphere val4 = (FogSphere)((obj is FogSphere) ? obj : null);
				if (Object.op_Implicit((Object)(object)val4))
				{
					val4.fogPoint = ((Component)origin).transform.position;
					val4.currentSize = origin.size;
					val4.ENABLE = 0f;
					val4.REVEAL_AMOUNT = 0f;
				}
			}
			Debug.Log((object)("Thunderfen mist scope initialized: native origin=" + ((Object)origin).name + " index=" + h.currentID + " hook=" + hook + " stateReset=" + flag2 + " height=" + Get(h, "currentStartHeight")?.ToString() + " forward=" + Get(h, "currentStartForward")?.ToString() + " wait=" + Get(h, "currentWaitTime")));
		}

		public static string Describe()
		{
			OrbFogHandler h = (Object.op_Implicit((Object)(object)handler) ? handler : Singleton<OrbFogHandler>.Instance);
			if (!Object.op_Implicit((Object)(object)h))
			{
				return "No native fog handler; initCalls=" + initCalls + " initializations=" + initializations;
			}
			FogSphereOrigin origin;
			Transform val = Scope(h, out origin);
			return "nativeAscent=" + Ascents.currentAscent + " nativeFogEnabled=" + Ascents.fogEnabled + " customScope=" + Object.op_Implicit((Object)(object)val) + " origin=" + (Object.op_Implicit((Object)(object)origin) ? ((Object)origin).name : "other/unknown") + " index=" + h.currentID + " hook=" + lastHook + " initCalls=" + initCalls + " initialized=" + initializations + " updates=" + updateCalls + " starts=" + starts + " startReason=" + lastStart + "; " + string.Join("; ", new string[5] { "isMoving", "currentWaitTime", "maxWaitTime", "currentStartHeight", "currentStartForward" }.Select((string name) => name + "=" + Get(h, name)));
		}
	}
	public static class ThunderfenSceneScope
	{
		public static Transform Find(Transform parent)
		{
			if (!Object.op_Implicit((Object)(object)parent))
			{
				return null;
			}
			if (Object.op_Implicit((Object)(object)parent.Find("FloorRoot/RootsTerrain/PF_HybridTerrain")) && Object.op_Implicit((Object)(object)parent.Find("CampfireRoot")))
			{
				return parent;
			}
			Transform val = ((IEnumerable<Transform>)((Component)parent).GetComponentsInChildren<Transform>(true)).FirstOrDefault((Func<Transform, bool>)((Transform t) => ((Object)t).name == "PF_HybridTerrain" && Object.op_Implicit((Object)(object)t.parent) && ((Object)t.parent).name == "RootsTerrain"));
			Transform val2 = val;
			while (Object.op_Implicit((Object)(object)val2))
			{
				if (Object.op_Implicit((Object)(object)val2.Find("FloorRoot/RootsTerrain/PF_HybridTerrain")) && Object.op_Implicit((Object)(object)val2.Find("CampfireRoot")) && Object.op_Implicit((Object)(object)val2.Find("RuntimeMarkers/FogBeginAnchor")))
				{
					return val2;
				}
				val2 = val2.parent;
			}
			return null;
		}
	}
	[HarmonyPatch(typeof(DayNightManager), "BlendProfiles", new Type[] { typeof(DayNightProfile) })]
	public static class ThunderfenDayNightPatch
	{
		[HarmonyPrefix]
		private static void Prefix(DayNightManager __instance, ref DayNightProfile __0)
		{
			DayNightProfile val = ThunderfenDayNight.Select(__0, __instance.currentProfile);
			if ((Object)(object)val != (Object)(object)__0)
			{
				__0 = val;
				Debug.Log((object)("Thunderfen overcast day/night cycle selected: day=" + __instance.dayCount + " hour=" + __instance.timeOfDay + "; original neutral day palette, darker night sky, no clock write"));
			}
		}
	}
	public static class ThunderfenDayNight
	{
		private static DayNightProfile cycle;

		public static void Reset()
		{
			if (Object.op_Implicit((Object)(object)cycle))
			{
				if (Application.isPlaying)
				{
					Object.Destroy((Object)(object)cycle);
				}
				else
				{
					Object.DestroyImmediate((Object)(object)cycle);
				}
			}
			cycle = null;
		}

		public static float Daylight(float hour)
		{
			hour = Mathf.Repeat(hour, 24f);
			if (hour < 5f || hour >= 21f)
			{
				return 0f;
			}
			if (hour < 7f)
			{
				return Mathf.SmoothStep(0f, 1f, (hour - 5f) / 2f);
			}
			if (hour > 19f)
			{
				return Mathf.SmoothStep(1f, 0f, (hour - 19f) / 2f);
			}
			return 1f;
		}

		private static Gradient Sky(Gradient original, float night)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: 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_0017: 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_0027: 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_0038: Expected O, but got Unknown
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: 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_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: 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_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_00a6: 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_00be: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00da: Unknown result type (might be due to invalid IL or missing references)
			Color val = original.Evaluate(0.5f);
			Color val2 = default(Color);
			((Color)(ref val2))..ctor(val.r * night, val.g * night, val.b * night, val.a);
			Gradient val3 = new Gradient();
			val3.SetKeys((GradientColorKey[])(object)new GradientColorKey[6]
			{
				new GradientColorKey(val2, 0f),
				new GradientColorKey(val2, 5f / 24f),
				new GradientColorKey(val, 7f / 24f),
				new GradientColorKey(val, 19f / 24f),
				new GradientColorKey(val2, 0.875f),
				new GradientColorKey(val2, 1f)
			}, (GradientAlphaKey[])(object)new GradientAlphaKey[2]
			{
				new GradientAlphaKey(val.a, 0f),
				new GradientAlphaKey(val.a, 1f)
			});
			return val3;
		}

		public static DayNightProfile Select(DayNightProfile incoming, DayNightProfile previous)
		{
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: Expected O, but got Unknown
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00db: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_0101: Unknown result type (might be due to invalid IL or missing references)
			//IL_0106: Unknown result type (might be due to invalid IL or missing references)
			//IL_0117: Unknown result type (might be due to invalid IL or missing references)
			//IL_011c: Unknown result type (might be due to invalid IL or missing references)
			//IL_012d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0132: Unknown result type (might be due to invalid IL or missing references)
			//IL_0143: Unknown result type (might be due to invalid IL or missing references)
			//IL_0148: Unknown result type (might be due to invalid IL or missing references)
			//IL_0159: Unknown result type (might be due to invalid IL or missing references)
			//IL_015e: Unknown result type (might be due to invalid IL or missing references)
			//IL_016f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0174: Unknown result type (might be due to invalid IL or missing references)
			if (!Object.op_Implicit((Object)(object)incoming) || !((Object)incoming).name.StartsWith("first-ridgeDayNightProfile", StringComparison.Ordinal))
			{
				return incoming;
			}
			if (!Object.op_Implicit((Object)(object)cycle))
			{
				cycle = Object.Instantiate<DayNightProfile>(incoming);
				((Object)cycle).name = "Thunderfen_OvercastDayNightCycle";
				((Object)cycle).hideFlags = (HideFlags)61;
				cycle.skyTopGradient = Sky(incoming.skyTopGradient, 0.12f);
				cycle.skyMidGradient = Sky(incoming.skyMidGradient, 0.16f);
				cycle.skyBottomGradient = Sky(incoming.skyBottomGradient, 0.2f);
				Gradient val = new Gradient();
				val.SetKeys((GradientColorKey[])(object)new GradientColorKey[2]
				{
					new GradientColorKey(Color.white, 0f),
					new GradientColorKey(Color.white, 1f)
				}, (GradientAlphaKey[])(object)new GradientAlphaKey[6]
				{
					new GradientAlphaKey(0f, 0f),
					new GradientAlphaKey(0f, 5f / 24f),
					new GradientAlphaKey(1f, 7f / 24f),
					new GradientAlphaKey(1f, 19f / 24f),
					new GradientAlphaKey(0f, 0.875f),
					new GradientAlphaKey(0f, 1f)
				});
				cycle.sunGradient = val;
			}
			return cycle;
		}
	}
	public static class MistTiming
	{
		public const float ProgressFraction = 0.35f;

		public static float Threshold(float entry, float summit)
		{
			return entry + 0.35f * (summit - entry);
		}
	}
	public sealed class ReceiptWindow
	{
		private readonly HashSet<string> seen = new HashSet<string>();

		private readonly Queue<string> order = new Queue<string>();

		private readonly int capacity;

		public ReceiptWindow(int capacity = 4096)
		{
			this.capacity = capacity;
		}

		public bool Take(string id)
		{
			if (string.IsNullOrEmpty(id) || !seen.Add(id))
			{
				return false;
			}
			order.Enqueue(id);
			while (order.Count > capacity)
			{
				seen.Remove(order.Dequeue());
			}
			return true;
		}

		public void Clear()
		{
			seen.Clear();
			order.Clear();
		}
	}
	public sealed class CycleReceipts
	{
		private readonly Dictionary<string, long> latest = new Dictionary<string, long>();

		public bool Take(string source, long cycle)
		{
			if (string.IsNullOrEmpty(source) || cycle < 0)
			{
				return false;
			}
			if (latest.TryGetValue(source, out var value) && cycle <= value)
			{
				return false;
			}
			latest[source] = cycle;
			return true;
		}

		public void Clear()
		{
			latest.Clear();
		}
	}
	public sealed class SharedPulse
	{
		private readonly int seed;

		private readonly double minimum;

		private readonly double maximum;

		private long serial;

		private double next;

		public long Serial => serial;

		public SharedPulse(int seed, double min, double max, double elapsed = 0.0)
		{
			if (min <= 0.0 || max < min || double.IsNaN(elapsed) || double.IsInfinity(elapsed) || elapsed < 0.0)
			{
				throw new ArgumentException("Invalid shared pulse");
			}
			this.seed = seed;
			minimum = min;
			maximum = max;
			next = Interval(0L);
			Advance(elapsed, fire: false);
		}

		private double Interval(long index)
		{
			uint num = (uint)(seed ^ ((int)index * 747796405 + -1403630843));
			num = (num ^ (num >> 16)) * 2246822519u;
			num = (num ^ (num >> 13)) * 3266489917u;
			num ^= num >> 16;
			return minimum + (maximum - minimum) * ((double)num / 4294967295.0);
		}

		private bool Advance(double now, bool fire)
		{
			bool flag = false;
			int num = 0;
			while (now >= next)
			{
				serial++;
				next += Interval(serial);
				flag = true;
				if (++num > 1000000)
				{
					throw new InvalidOperationException("Pulse clock outside supported run length");
				}
			}
			return fire && flag;
		}

		public bool Tick(double elapsed)
		{
			if (double.IsNaN(elapsed) || double.IsInfinity(elapsed) || elapsed < 0.0)
			{
				throw new ArgumentException("Invalid pulse time");
			}
			return Advance(elapsed, fire: true);
		}

		public double Remaining(double elapsed)
		{
			return Math.Max(0.0, next - elapsed);
		}
	}
	public static class PeerGate
	{
		public static bool Match(string expected, string received)
		{
			return !string.IsNullOrEmpty(expected) && string.Equals(expected, received, StringComparison.Ordinal);
		}

		public static bool CanCommit(int peers, int matching, int ready, double start, double now)
		{
			return peers > 0 && peers == matching && peers == ready && start > 0.0 && now >= start;
		}

		public static bool StaysReady(bool committed, int peers, int matching, int ready, double start, double now)
		{
			return committed || CanCommit(peers, matching, ready, start, now);
		}

		public static bool SamePlacement(float[] a, float[] b)
		{
			if (a == null || b == null || a.Length != 16 || b.Length != 16)
			{
				return false;
			}
			for (int i = 0; i < 16; i++)
			{
				if (float.IsNaN(a[i]) || float.IsNaN(b[i]) || float.IsInfinity(a[i]) || float.IsInfinity(b[i]) || Math.Abs(a[i] - b[i]) > 0.01f)
				{
					return false;
				}
			}
			return true;
		}
	}
	public static class RoomEntryRepair
	{
		public static bool Needed(bool offline, bool joined, bool master, bool hostState, bool inRoomState)
		{
			return !offline && joined && master && hostState && !inRoomState;
		}
	}
	public static class EnvelopeGate
	{
		public static bool Accept(object[] p, int sender, int master, string epoch, ReceiptWindow receipts)
		{
			return sender == master && p != null && p.Length == 5 && p[0] as string == "ThunderfenMP1" && p[1] as string == epoch && !string.IsNullOrEmpty(epoch) && p[2] is string { Length: <40 } && p[3] is string { Length: <100 } text2 && p[4] is object[] array && array.Length <= 32 && receipts.Take(text2);
		}
	}
	public static class ElectricalBurstMath
	{
		public static bool Eligible(float a, float b, float squaredDistance)
		{
			return a > 0f && b > 0f && Math.Max(a, b) > 0.25f && squaredDistance <= 3.0625f;
		}

		public static float Injury(float ownCharge)
		{
			return Math.Max(0f, Math.Min(1f, ownCharge)) / 3f;
		}
	}
	public sealed class SharedWorld : MonoBehaviour
	{
		[Serializable]
		private sealed class NetworkReport
		{
			public string utc;

			public string protocol = "ThunderfenMP1";

			public string fingerprint;

			public string epoch;

			public string status;

			public bool online;

			public bool ready;

			public bool admitted;

			public bool committed;

			public bool healthy;

			public bool localMapReady;

			public int revision;

			public int actor;

			public int master;

			public int seed;

			public string[] peerBuilds;

			public float[] placement;

			public double elapsed;
		}

		private const byte EventCode = 180;

		private const string Magic = "ThunderfenMP1";

		private const string WorldKey = "TF_World1";

		private const string PeerKey = "TF_Peer1";

		private static SharedWorld instance;

		private readonly ReceiptWindow receipts = new ReceiptWindow();

		private readonly HashSet<string> modules = new HashSet<string>();

		private HashSet<string> siteClaims = new HashSet<string>();

		private int claimOwner = -1;

		private string claimEpoch;

		private string fingerprint;

		private string fingerprintRun;

		private string epoch;

		private string status = "Waiting for room";

		private string lastAdvertisement;

		private double epochAt;

		private long sequence;

		private bool broken;

		private bool wasIsland;

		private bool admitted;

		private bool committed;

		private bool ready;

		private float next;

		private int stable;

		private Transform frame;

		private float[] admittedPose;

		private string waiting;

		private float nextReport;

		private float nextWorldPublish;

		public static bool Online => PhotonNetwork.InRoom && !PhotonNetwork.OfflineMode;

		public static bool Ready => !Online || (Object.op_Implicit((Object)(object)instance) && instance.ready);

		public static bool Authority => PhotonNetwork.InRoom && PhotonNetwork.IsMasterClient;

		public static string Epoch => instance?.epoch ?? "";

		public static string RoomRun => Online ? (((RoomInfo)PhotonNetwork.CurrentRoom).CustomProperties[(object)"TF_MapRun2"] as string) : null;

		public static double Elapsed => Online ? Math.Max(0.0, PhotonNetwork.Time - (instance?.epochAt ?? PhotonNetwork.Time)) : ((double)Time.time);

		public static string Status => instance?.status ?? "Network bootstrap not installed";

		public static string WaitingFor => instance?.waiting;

		internal static string StartupFailure { get; private set; }

		public static event Action<string, string, object[]> Message;

		private bool Healthy()
		{
			return UnhealthyModule() == null;
		}

		public static string UnhealthyModule()
		{
			foreach (KeyValuePair<string, PluginInfo> pluginInfo in Chainloader.PluginInfos)
			{
				if (pluginInfo.Key.StartsWith("local.peak.poisonforest.", StringComparison.Ordinal) && !(pluginInfo.Key == "local.peak.poisonforest.solo"))
				{
					BaseUnityPlugin val = pluginInfo.Value.Instance;
					if (!Object.op_Implicit((Object)(object)val))
					{
						return pluginInfo.Value.Metadata.Name;
					}
					BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
					FieldInfo field = ((object)val).GetType().GetField("ready", bindingAttr);
					FieldInfo field2 = ((object)val).GetType().GetField("failed", bindingAttr);
					if ((field != null && field.FieldType == typeof(bool) && !(bool)field.GetValue(val)) || (field2 != null && field2.FieldType == typeof(bool) && (bool)field2.GetValue(val)))
					{
						return pluginInfo.Value.Metadata.Name;
					}
				}
			}
			return null;
		}

		public static void Install(GameObject owner)
		{
			if (!Object.op_Implicit((Object)(object)instance))
			{
				instance = owner.AddComponent<SharedWorld>();
			}
		}

		public static void Uninstall(GameObject owner)
		{
			if (Object.op_Implicit((Object)(object)instance) && !((Object)(object)((Component)instance).gameObject != (Object)(object)owner))
			{
				SharedWorld sharedWorld = instance;
				sharedWorld.Detach();
				Object.Destroy((Object)(object)sharedWorld);
			}
		}

		public static void MarkStartupFailure(string module)
		{
			if (StartupFailure == null)
			{
				StartupFailure = module;
			}
		}

		public static void ModuleReady(string name, bool value)
		{
			if (Object.op_Implicit((Object)(object)instance))
			{
				if (value)
				{
					instance.modules.Add(name);
				}
				else
				{
					instance.modules.Remove(name);
				}
			}
		}

		public static bool SiteClaimed(string site)
		{
			if (!Online)
			{
				return Object.op_Implicit((Object)(object)instance) && instance.claimEpoch == "solo:" + RunData.Revision && instance.siteClaims.Contains(site);
			}
			return ((RoomInfo)PhotonNetwork.CurrentRoom).CustomProperties[(object)"TF_Sites"] is object[] array && array.Length == 2 && array[0] as string == Epoch && array[1] is string[] source && source.Contains(site);
		}

		public static bool ClaimSite(string site)
		{
			//IL_015d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0164: Expected O, but got Unknown
			if (!Object.op_Implicit((Object)(object)instance) || !Authority || !Ready)
			{
				return false;
			}
			if (!Online)
			{
				SharedWorld sharedWorld = instance;
				string text = "solo:" + RunData.Revision;
				if (sharedWorld.claimEpoch != text)
				{
					sharedWorld.claimEpoch = text;
					sharedWorld.siteClaims.Clear();
				}
				return sharedWorld.siteClaims.Add(site);
			}
			SharedWorld sharedWorld2 = instance;
			int actorNumber = PhotonNetwork.LocalPlayer.ActorNumber;
			if (sharedWorld2.claimEpoch != Epoch || sharedWorld2.claimOwner != actorNumber)
			{
				sharedWorld2.claimEpoch = Epoch;
				sharedWorld2.claimOwner = actorNumber;
				object[] array = ((RoomInfo)PhotonNetwork.CurrentRoom).CustomProperties[(object)"TF_Sites"] as object[];
				sharedWorld2.siteClaims = ((array != null && array.Length == 2 && array[0] as string == Epoch && array[1] is string[] collection) ? new HashSet<string>(collection) : new HashSet<string>());
			}
			if (!sharedWorld2.siteClaims.Add(site))
			{
				return false;
			}
			Room currentRoom = PhotonNetwork.CurrentRoom;
			Hashtable val = new Hashtable();
			((Dictionary<object, object>)(object)val).Add((object)"TF_Sites", (object)new object[2]
			{
				Epoch,
				sharedWorld2.siteClaims.OrderBy<string, string>((string x) => x, StringComparer.Ordinal).ToArray()
			});
			currentRoom.SetCustomProperties(val, (Hashtable)null, (WebFlags)null);
			return true;
		}

		private static string Hash(byte[] b)
		{
			using SHA256 sHA = SHA256.Create();
			return BitConverter.ToString(sHA.ComputeHash(b)).Replace("-", "");
		}

		public static string SettingsHash(string path)
		{
			string input = File.ReadAllText(path);
			input = Regex.Replace(input, "\"(?:showOverlay|spawnKey|clearKey|presetKey|forceStrikeKey|toggleAutomaticKey)\"\\s*:\\s*(?:true|false|\"[^\"]*\")\\s*,?", "");
			input = Regex.Replace(input, ",\\s*}", "}");
			StringBuilder stringBuilder = new StringBuilder();
			bool flag = false;
			bool flag2 = false;
			string text = input;
			foreach (char c in text)
			{
				if (flag || !char.IsWhiteSpace(c))
				{
					stringBuilder.Append(c);
					if (flag2)
					{
						flag2 = false;
					}
					else if (c == '\\' && flag)
					{
						flag2 = true;
					}
					else if (c == '"')
					{
						flag = !flag;
					}
				}
			}
			return Hash(Encoding.UTF8.GetBytes(stringBuilder.ToString()));
		}

		private string Fingerprint()
		{
			StringBuilder stringBuilder = new StringBuilder("ThunderfenMP1");
			stringBuilder.Append(Hash(File.ReadAllBytes(typeof(PllBiomeDefinition).Assembly.Location)));
			stringBuilder.Append('|').Append(GeneratedData.ContentHash);
			RunData.Seed = GeneratedData.Seed;
			foreach (KeyValuePair<string, PluginInfo> item in Chainloader.PluginInfos.OrderBy<KeyValuePair<string, PluginInfo>, string>((KeyValuePair<string, PluginInfo> p) => p.Key, StringComparer.Ordinal))
			{
				if (item.Key.StartsWith("local.peak.poisonforest.", StringComparison.Ordinal))
				{
					stringBuilder.Append('|').Append(item.Key).Append(':')
						.Append(Hash(File.ReadAllBytes(item.Value.Location)));
					string path = Path.Combine(Path.GetDirectoryName(item.Value.Location), Path.GetFileNameWithoutExtension(item.Value.Location) + ".settings.json");
					if (File.Exists(path))
					{
						stringBuilder.Append(':').Append(SettingsHash(path));
					}
				}
			}
			return Hash(Encoding.UTF8.GetBytes(stringBuilder.ToString()));
		}

		private void Awake()
		{
			instance = this;
			PhotonNetwork.NetworkingClient.EventReceived += Receive;
		}

		private void Report()
		{
			if (!RuntimeDiagnostics.PeriodicSnapshots || Time.unscaledTime < nextReport)
			{
				return;
			}
			nextReport = Time.unscaledTime + 2f;
			try
			{
				string text = Path.Combine(Application.persistentDataPath, "Thunderfen");
				Directory.CreateDirectory(text);
				string[] peerBuilds = (Online ? PhotonNetwork.PlayerList.Select(delegate(Player p)
				{
					object[] array = p.CustomProperties[(object)"TF_Peer1"] as object[];
					return p.ActorNumber + ":" + (p.IsInactive ? "inactive:" : "") + ((array == null) ? "unadvertised" : string.Join("|", from x in array.Take(3)
						select x?.ToString() ?? "null"));
				}).ToArray() : new string[0]);
				string path = Path.Combine(text, "multiplayer-state.json");
				NetworkReport obj = new NetworkReport
				{
					utc = DateTime.UtcNow.ToString("O"),
					fingerprint = fingerprint,
					epoch = epoch,
					status = status,
					online = Online,
					localMapReady = SoloGenerationPlugin.LocalMapReady,
					revision = RunData.Revision,
					ready = ready,
					admitted = admitted,
					committed = committed,
					healthy = Healthy()
				};
				Player localPlayer = PhotonNetwork.LocalPlayer;
				obj.actor = ((localPlayer != null) ? localPlayer.ActorNumber : 0);
				Player masterClient = PhotonNetwork.MasterClient;
				obj.master = ((masterClient != null) ? masterClient.ActorNumber : 0);
				obj.seed = RunData.Seed;
				obj.peerBuilds = peerBuilds;
				obj.placement = admittedPose;
				obj.elapsed = Elapsed;
				File.WriteAllText(path, JsonUtility.ToJson((object)obj, true));
			}
			catch (Exception ex)
			{
				Debug.LogWarning((object)("Thunderfen network diagnostic: " + ex.Message));
			}
		}

		private void Update()
		{
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			if (Time.unscaledTime < next)
			{
				return;
			}
			next = Time.unscaledTime + 0.2f;
			if (broken)
			{
				Scene sceneByName = SceneManager.GetSceneByName("WilIsland");
				if (!((Scene)(ref sceneByName)).isLoaded)
				{
					broken = false;
					ResetLocal();
					modules.Clear();
					status = "Prepared multiplayer build verified; waiting for native level loading";
					Debug.Log((object)"Thunderfen multiplayer setup recovered after leaving the island.");
				}
			}
			try
			{
				if (!broken)
				{
					Tick();
				}
			}
			catch (Exception ex)
			{
				broken = true;
				ready = false;
				RunData.Pending = Online;
				status = "Thunderfen multiplayer setup failed: " + ex.Message;
				Debug.LogError((object)status);
			}
			Report();
		}

		private Transform Find()
		{
			//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)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Expected O, but got Unknown
			Scene sceneByName = SceneManager.GetSceneByName("WilIsland");
			if (!((Scene)(ref sceneByName)).IsValid())
			{
				return null;
			}
			GameObject[] rootGameObjects = ((Scene)(ref sceneByName)).GetRootGameObjects();
			foreach (GameObject val in rootGameObjects)
			{
				if (!(((Object)val).name == "Map"))
				{
					continue;
				}
				Transform val2 = val.transform.Find("Global");
				if (!Object.op_Implicit((Object)(object)val2))
				{
					return null;
				}
				foreach (Transform item in val2)
				{
					Transform val3 = item;
					if (((Object)val3).name.Contains("first-ridge"))
					{
						Transform val4 = ((IEnumerable<Transform>)((Component)val3).GetComponentsInChildren<Transform>(true)).FirstOrDefault((Func<Transform, bool>)((Transform n) => ((Object)n).name == "PF_HybridTerrain" && Object.op_Implicit((Object)(object)n.parent) && ((Object)n.parent).name == "RootsTerrain"));
						if (Object.op_Implicit((Object)(object)val4))
						{
							return val4;
						}
					}
				}
			}
			return null;
		}

		private void ResetLocal()
		{
			waiting = null;
			ready = (admitted = (committed = false));
			epoch = null;
			epochAt = 0.0;
			frame = null;
			admittedPose = null;
			stable = 0;
			lastAdvertisement = null;
			receipts.Clear();
		}

		private void Tick()
		{
			//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)
			//IL_01cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d3: Expected O, but got Unknown
			//IL_0206: 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_0217: Expected O, but got Unknown
			//IL_021e: Expected O, but got Unknown
			//IL_04d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_04d7: Expected O, but got Unknown
			//IL_07a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_07b0: Expected O, but got Unknown
			//IL_07ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_07f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_07ff: Expected O, but got Unknown
			//IL_0806: Expected O, but got Unknown
			Scene sceneByName = SceneManager.GetSceneByName("WilIsland");
			bool isLoaded = ((Scene)(ref sceneByName)).isLoaded;
			if (!Online)
			{
				if (wasIsland)
				{
					ResetLocal();
				}
				wasIsland = isLoaded;
				return;
			}
			string selectedRun = MapRotation.SelectedRun;
			if (!isLoaded)
			{
				fingerprint = null;
				fingerprintRun = null;
			}
			else if (fingerprint == null || fingerprintRun != selectedRun)
			{
				if (MapRotation.PreparedBaseline && MapRotation.SelectedFolder == null)
				{
					ready = false;
					return;
				}
				fingerprint = Fingerprint();
				fingerprintRun = selectedRun;
				ResetLocal();
				RunData.Pending = true;
				nextWorldPublish = 0f;
			}
			if (!isLoaded)
			{
				if (wasIsland)
				{
					ResetLocal();
					modules.Clear();
				}
				wasIsland = false;
				status = "Prepared multiplayer build verified; waiting for native level loading";
				return;
			}
			if (!wasIsland)
			{
				ResetLocal();
				RunData.Pending = true;
				nextWorldPublish = 0f;
			}
			wasIsland = true;
			Room currentRoom = PhotonNetwork.CurrentRoom;
			waiting = null;
			object[] array = ((RoomInfo)currentRoom).CustomProperties[(object)"TF_World1"] as object[];
			if (string.IsNullOrEmpty(selectedRun) || array == null || array.Length != 3 || array[1] as string != selectedRun)
			{
				if (Authority && selectedRun != null && Time.unscaledTime >= nextWorldPublish)
				{
					nextWorldPublish = Time.unscaledTime + 1f;
					Hashtable val = new Hashtable();
					((Dictionary<object, object>)(object)val).Add((object)"TF_World1", (object)new object[3] { fingerprint, selectedRun, 0.0 });
					Hashtable obj = val;
					Hashtable val2 = new Hashtable();
					((Dictionary<object, object>)val2).Add((object)"TF_MapRun2", (object)selectedRun);
					currentRoom.SetCustomProperties(obj, val2, (WebFlags)null);
				}
				ready = false;
				RunData.Pending = true;
				status = "Waiting for this run's Thunderfen world identity";
				return;
			}
			if (!PeerGate.Match(fingerprint, array[0] as string))
			{
				ready = false;
				RunData.Pending = true;
				status = "Thunderfen build/settings mismatch with host; install the same Thunderfen release and settings";
				return;
			}
			string text = array[1] as string;
			if (epoch != text)
			{
				epoch = text;
				admitted = (committed = false);
				ready = false;
				receipts.Clear();
				lastAdvertisement = null;
			}
			epochAt = Convert.ToDouble(array[2]);
			if (!SoloGenerationPlugin.LocalMapReady)
			{
				admitted = (committed = (ready = false));
				stable = 0;
				RunData.Pending = true;
			}
			if (!admitted)
			{
				frame = Find();
				Transform currentSegment = null;
				if (Object.op_Implicit((Object)(object)Singleton<MapHandler>.Instance) && MapHandler.CurrentMapSegment != null && Object.op_Implicit((Object)(object)MapHandler.CurrentMapSegment.segmentParent))
				{
					currentSegment = MapHandler.CurrentMapSegment.segmentParent.transform;
				}
				string reason = "";
				int pendingMaterials = 0;
				bool localMapReady = SoloGenerationPlugin.LocalMapReady;
				bool flag = localMapReady && AssemblyReadiness.CanAdmit(frame, currentSegment, out reason, out pendingMaterials);
				bool flag2 = modules.Contains("nativeprops");
				bool flag3 = flag && flag2;
				stable = (flag3 ? (stable + 1) : 0);
				if (stable >= 3)
				{
					admitted = true;
					admittedPose = Enumerable.Range(0, 16).Select(delegate(int i)
					{
						//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)
						Matrix4x4 localToWorldMatrix = frame.localToWorldMatrix;
						return ((Matrix4x4)(ref localToWorldMatrix))[i];
					}).ToArray();
					if (pendingMaterials > 0)
					{
						Debug.LogWarning((object)("Thunderfen joined the shared world with " + pendingMaterials + " terrain renderers lacking native PEAK materials; they may look plain."));
					}
				}
				status = (flag3 ? "Confirming matching Thunderfen scene" : ((!localMapReady) ? "Waiting for this PC's Thunderfen map" : ((!flag) ? ("Waiting for Thunderfen terrain: " + reason) : "Waiting for Thunderfen native props")));
			}
			bool flag4 = admitted && Healthy();
			float[] array2 = admittedPose;
			string text2 = fingerprint + "|" + epoch + "|" + flag4;
			if (lastAdvertisement != text2)
			{
				Player localPlayer = PhotonNetwork.LocalPlayer;
				Hashtable val = new Hashtable();
				((Dictionary<object, object>)(object)val).Add((object)"TF_Peer1", (object)new object[4] { fingerprint, epoch, flag4, array2 });
				localPlayer.SetCustomProperties(val, (Hashtable)null, (WebFlags)null);
				lastAdvertisement = text2;
			}
			Player[] array3 = PhotonNetwork.PlayerList.Where((Player p) => !p.IsInactive).ToArray();
			int num = array3.Length;
			int num2 = 0;
			int num3 = 0;
			List<string> list = new List<string>();
			object obj2;
			if (admitted)
			{
				string text3 = UnhealthyModule();
				obj2 = ((text3 != null) ? (text3 + " stopped working") : "still loading Thunderfen");
			}
			else
			{
				obj2 = status;
			}
			string text4 = (string)obj2;
			Player[] array4 = array3;
			bool flag5 = default(bool);
			foreach (Player val3 in array4)
			{
				string text5 = (val3.IsLocal ? "this PC" : (string.IsNullOrEmpty(val3.NickName) ? ("player " + val3.ActorNumber) : val3.NickName));
				if (!(val3.CustomProperties[(object)"TF_Peer1"] is object[] array5) || array5.Length != 4)
				{
					list.Add(text5 + " (no Thunderfen report)");
					continue;
				}
				if (!PeerGate.Match(fingerprint, array5[0] as string))
				{
					list.Add(text5 + " (different Thunderfen build or settings)");
					continue;
				}
				if (array5[1] as string != epoch)
				{
					list.Add(text5 + " (on another run)");
					continue;
				}
				num2++;
				object obj3 = array5[2];
				int num5;
				if (obj3 is bool)
				{
					flag5 = (bool)obj3;
					num5 = 1;
				}
				else
				{
					num5 = 0;
				}
				if (((uint)num5 & (flag5 ? 1u : 0u)) == 0)
				{
					list.Add(text5 + (val3.IsLocal ? (" (" + text4 + ")") : " (still loading Thunderfen)"));
				}
				else if (array2 != null)
				{
					if (!PeerGate.SamePlacement(array2, array5[3] as float[]))
					{
						list.Add(text5 + " (Thunderfen terrain in a different position)");
					}
					else
					{
						num3++;
					}
				}
			}
			waiting = ((list.Count == 0) ? null : ("waiting for " + string.Join(", ", list)));
			if (Authority && num2 == num && num3 == num && epochAt == 0.0)
			{
				Hashtable val = new Hashtable();
				((Dictionary<object, object>)(object)val).Add((object)"TF_World1", (object)new object[3]
				{
					fingerprint,
					epoch,
					PhotonNetwork.Time + 0.75
				});
				Hashtable obj4 = val;
				Hashtable val4 = new Hashtable();
				((Dictionary<object, object>)val4).Add((object)"TF_MapRun2", (object)selectedRun);
				currentRoom.SetCustomProperties(obj4, val4, (WebFlags)null);
			}
			ready = PeerGate.StaysReady(committed, num, num2, num3, epochAt, PhotonNetwork.Time);
			if (ready && !committed)
			{
				committed = true;
				RunData.Pending = false;
				Debug.Log((object)("Thunderfen multiplayer map committed: " + fingerprint + " seed=" + RunData.Seed + " peers=" + num));
			}
			if (committed)
			{
				RunData.Pending = false;
			}
			status = (ready ? ("Thunderfen multiplayer ready (" + num + " peers), seed " + RunData.Seed) : (admitted ? ("Waiting for matching/loaded peers: " + num2 + "/" + num + " matching, " + num3 + "/" + num + " loaded (including placement)") : status));
		}

		public static string Emit(string kind, object[] data, bool reliable = true)
		{
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d5: 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_00dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ee: Expected O, but got Unknown
			if (!Online)
			{
				string text = "solo:" + Guid.NewGuid().ToString("N");
				Dispatch(kind, text, data);
				return text;
			}
			if (!Object.op_Implicit((Object)(object)instance) || !Authority || !Ready)
			{
				return null;
			}
			string text2 = PhotonNetwork.LocalPlayer.ActorNumber + ":" + ++instance.sequence;
			object[] array = new object[5] { "ThunderfenMP1", Epoch, kind, text2, data };
			PhotonNetwork.RaiseEvent((byte)180, (object)array, new RaiseEventOptions
			{
				Receivers = (ReceiverGroup)0
			}, reliable ? SendOptions.SendReliable : SendOptions.SendUnreliable);
			instance.receipts.Take(text2);
			Dispatch(kind, text2, data);
			return text2;
		}

		private static void Dispatch(string kind, string id, object[] data)
		{
			Action<string, string, object[]> message = SharedWorld.Message;
			if (message == null)
			{
				return;
			}
			Delegate[] invocationList = message.GetInvocationList();
			for (int i = 0; i < invocationList.Length; i++)
			{
				Action<string, string, object[]> action = (Action<string, string, object[]>)invocationList[i];
				try
				{
					action(kind, id, data);
				}
				catch (Exception ex)
				{
					Debug.LogException(ex);
				}
			}
		}

		private void Receive(EventData ev)
		{
			if (ev.Code == 180 && Online)
			{
				object[] array = ev.CustomData as object[];
				if (EnvelopeGate.Accept(array, ev.Sender, PhotonNetwork.MasterClient.ActorNumber, epoch, receipts))
				{
					Dispatch((string)array[2], (string)array[3], (object[])array[4]);
				}
			}
		}

		public static Character CharacterFor(int view)
		{
			return ((IEnumerable<Character>)Character.AllCharacters).FirstOrDefault((Func<Character, bool>)((Character c) => Object.op_Implicit((Object)(object)c) && Object.op_Implicit((Object)(object)((MonoBehaviourPun)c).photonView) && ((MonoBehaviourPun)c).photonView.ViewID == view));
		}

		public static void Charge(string source, int view, float amount, float delay = 0f, long cycle = 0L)
		{
			if (!Online || Authority)
			{
				Emit("charge", new object[5]
				{
					source,
					view,
					amount,
					PhotonNetwork.Time + (double)delay,
					cycle
				});
			}
		}

		private void Detach()
		{
			if (PhotonNetwork.NetworkingClient != null)
			{
				PhotonNetwork.NetworkingClient.EventReceived -= Receive;
			}
			if ((Object)(object)instance == (Object)(object)this)
			{
				instance = null;
			}
			ready = false;
			((Behaviour)this).enabled = false;
		}

		private void OnDestroy()
		{
			Detach();
		}
	}
	public static class SnapshotCodec
	{
		public static byte[] Pack(string text)
		{
			byte[] bytes = Encoding.UTF8.GetBytes(text);
			if (bytes.Length > 65536)
			{
				throw new InvalidDataException("Snapshot too large");
			}
			using MemoryStream memoryStream = new MemoryStream();
			using (DeflateStream deflateStream = new DeflateStream(memoryStream, CompressionLevel.Fastest, leaveOpen: true))
			{
				deflateStream.Write(bytes, 0, bytes.Length);
			}
			return memoryStream.ToArray();
		}

		public static string Unpack(byte[] data)
		{
			if (data == null || data.Length < 2 || data.Length > 65536)
			{
				throw new InvalidDataException("Snapshot packet length");
			}
			using MemoryStream stream = new MemoryStream(data);
			using DeflateStream deflateStream = new DeflateStream(stream, CompressionMode.Decompress);
			using MemoryStream memoryStream = new MemoryStream();
			byte[] array = new byte[4096];
			int num;
			while ((num = deflateStream.Read(array, 0, array.Length)) > 0)
			{
				if (memoryStream.Length + num > 65536)
				{
					throw new InvalidDataException("Expanded snapshot too large");
				}
				memoryStream.Write(array, 0, num);
			}
			if (memoryStream.Length == 0)
			{
				throw new InvalidDataException("Empty snapshot");
			}
			return new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true).GetString(memoryStream.ToArray());
		}
	}
	public sealed class ResumePlacement : MonoBehaviour
	{
		public static int Holds;

		public static int Corrections;

		public static string Last = "not used";

		internal static int ExactDepth;

		internal static bool HostContinue;

		private Character character;

		private Transform root;

		private Rigidbody[] bodies;

		private bool[] kinematic;

		private bool checkpoint;

		private bool finished;

		private Vector3 requested;

		private int readyFrames;

		private int targetSegment = -1;

		private const float HoldLimit = 60f;

		private float holdStarted = -1f;

		public static void Begin(Character c, bool exact, int destination = -1)
		{
			//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)
			Transform currentRoot = ThunderfenMist.CurrentRoot;
			if (Object.op_Implicit((Object)(object)c) && Object.op_Implicit((Object)(object)((MonoBehaviourPun)c).photonView) && ((MonoBehaviourPun)c).photonView.IsMine && !Object.op_Implicit((Object)(object)((Component)c).GetComponent<ResumePlacement>()))
			{
				ResumePlacement resumePlacement = ((Component)c).gameObject.AddComponent<ResumePlacement>();
				resumePlacement.character = c;
				resumePlacement.targetSegment = destination;
				resumePlacement.root = currentRoot;
				resumePlacement.requested = ((Component)c).transform.position;
				resumePlacement.checkpoint = !exact;
				resumePlacement.bodies = ((Component)c).GetComponentsInChildren<Rigidbody>(true);
				resumePlacement.kinematic = resumePlacement.bodies.Select((Rigidbody b) => b.isKinematic).ToArray();
				Holds++;
				Last = "waiting for collision; exact=" + exact + " requested=" + ((object)Unsafe.As<Vector3, Vector3>(ref resumePlacement.requested)/*cast due to .constrained prefix*/).ToString();
				resumePlacement.Hold();
			}
		}

		private void Hold()
		{
			if (bodies == null)
			{
				return;
			}
			Rigidbody[] array = bodies;
			foreach (Rigidbody val in array)
			{
				if (Object.op_Implicit((Object)(object)val))
				{
					val.isKinematic = true;
				}
			}
		}

		public void NativeKinematics(IEnumerable<Rigidbody> changed, bool value)
		{
			if (finished || bodies == null)
			{
				return;
			}
			foreach (Rigidbody item in changed)
			{
				int num = Array.IndexOf(bodies, item);
				if (num >= 0)
				{
					kinematic[num] = value;
				}
			}
			Hold();
		}

		private void FixedUpdate()
		{
			if (!finished)
			{
				Hold();
			}
		}

		private static int CurrentSegment()
		{
			MapHandler instance = Singleton<MapHandler>.Instance;
			MapSegment currentMapSegment = MapHandler.CurrentMapSegment;
			return (Object.op_Implicit((Object)(object)instance) && instance.segments != null && currentMapSegment != null) ? Array.IndexOf(instance.segments, currentMapSegment) : (-1);
		}

		private static bool ForeignSegment()
		{
			MapSegment currentMapSegme