Decompiled source of TemporalStorm v0.0.8

BepInEx/plugins/TemporalStormWeather.dll

Decompiled 3 days 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.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Threading.Tasks;
using BasedDecorPlacement.API;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using BrutalCompanyMinus;
using BrutalCompanyMinus.Minus;
using BrutalCompanyMinus.Minus.Handlers.Modded;
using Coroner;
using CullFactory;
using CullFactory.Extenders;
using Dawn;
using GameNetcodeStuff;
using HarmonyLib;
using HatLib;
using HatLib.Tools;
using Microsoft.CodeAnalysis;
using PathfindingLib.API.SmartPathfinding;
using PathfindingLib.Utilities;
using TMPro;
using TemporalStormWeather.API;
using TemporalStormWeather.Compat;
using TemporalStormWeather.Compat.BCMERCompat;
using TemporalStormWeather.Compat.BCMERCompat.Events.LocustSwarm;
using TemporalStormWeather.Compat.BCMERCompat.Events.RusticAllItems;
using TemporalStormWeather.Compat.BCMERCompat.Events.TemporalAllItems;
using TemporalStormWeather.Compat.BCMERCompat.Events.WorldOfRust;
using TemporalStormWeather.Enemies;
using TemporalStormWeather.Hazards;
using TemporalStormWeather.Items;
using TemporalStormWeather.NetcodePatcher;
using TemporalStormWeather.Patches;
using TemporalStormWeather.TemporalStormManagers;
using TemporalStormWeather.TemporalStormManagers.Helpers;
using TemporalStormWeather.TemporalStormManagers.RustLightning;
using TemporalStormWeather.Unlockables;
using TemporalStormWeather.Utils;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.Animations;
using UnityEngine.Events;
using UnityEngine.Experimental.Rendering;
using UnityEngine.Rendering;
using UnityEngine.Rendering.HighDefinition;
using UnityEngine.SceneManagement;
using UnityEngine.Serialization;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("TemporalStormWeather")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("0.0.8.0")]
[assembly: AssemblyInformationalVersion("0.0.8")]
[assembly: AssemblyProduct("TemporalStormWeather")]
[assembly: AssemblyTitle("TemporalStormWeather")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.0.8.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
[module: NetcodePatchedAssembly]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace TemporalStormWeather
{
	internal static class ConfigManager
	{
		private static readonly DuskConfigInjector DuskConfig = new DuskConfigInjector("MrHat.TemporalStormWeather");

		internal static ConfigEntry<bool> TemporalRiftSkipDisabledEnemies { get; private set; } = null;

		internal static ConfigEntry<bool> TemporalRiftRespectEnemyMaxCount { get; private set; } = null;

		internal static ConfigEntry<bool> TemporalRiftUseCurrentMoonEnemyList { get; private set; } = null;

		internal static ConfigEntry<bool> TemporalRiftUnrestrictEnemySpawns { get; private set; } = null;

		internal static ConfigEntry<float> TemporalRiftLocustSwarmChance { get; private set; } = null;

		internal static ConfigEntry<int> TemporalRiftMinimumLocustWaveSize { get; private set; } = null;

		internal static ConfigEntry<int> TemporalRiftMaximumLocustWaveSize { get; private set; } = null;

		internal static ConfigEntry<float> TemporalRiftMinimumEnemyPowerBudget { get; private set; } = null;

		internal static ConfigEntry<float> TemporalRiftMaximumEnemyPowerBudget { get; private set; } = null;

		internal static ConfigEntry<string> TemporalRiftInsideEnemyBlacklist { get; private set; } = null;

		internal static ConfigEntry<string> TemporalRiftOutsideEnemyBlacklist { get; private set; } = null;

		internal static ConfigEntry<bool> EntityGlitchEnabled { get; private set; } = null;

		internal static ConfigEntry<bool> EntityGlitchPlayerModels { get; private set; } = null;

		internal static ConfigEntry<string> EntityGlitchEnemyBlacklist { get; private set; } = null;

		internal static ConfigEntry<bool> AudioPitchingEnabled { get; private set; } = null;

		internal static ConfigEntry<float> MaxBackgroundAudioVolume { get; private set; } = null;

		internal static ConfigEntry<float> MaxTuningCylinderAudioVolume { get; private set; } = null;

		internal static ConfigEntry<float> MaxApproachingWarningAudioVolume { get; private set; } = null;

		internal static ConfigEntry<float> MaxImminentWarningAudioVolume { get; private set; } = null;

		internal static ConfigEntry<float> MaxLowStabilityAudioVolume { get; private set; } = null;

		internal static ConfigEntry<float> MaxWaningAudioVolume { get; private set; } = null;

		internal static ConfigEntry<float> MaxWarningBellAudioVolume { get; private set; } = null;

		internal static ConfigEntry<bool> DebugLogsEnabled { get; private set; } = null;

		internal static void BindConfigs()
		{
			TemporalRiftSkipDisabledEnemies = DuskConfig.Bind<bool>("Temporal Rift Options", "Skip disabled enemies", true, "If true, temporal rifts will not spawn enemies marked as spawning disabled");
			TemporalRiftRespectEnemyMaxCount = DuskConfig.Bind<bool>("Temporal Rift Options", "Respect enemy max count", false, "If true, temporal rifts will not spawn an enemy after its max count allowed on the moon is reached");
			TemporalRiftUseCurrentMoonEnemyList = DuskConfig.Bind<bool>("Temporal Rift Options", "Use current moon enemy list", true, "If true, temporal rifts can only spawn enemies from the current moon's spawnable enemy lists. This option respects 'Inside/Outside enemy blacklists'");
			TemporalRiftUnrestrictEnemySpawns = DuskConfig.Bind<bool>("Temporal Rift Options", "Unrestrict enemy spawns", false, "If true and StarlancerAIFix is installed, temporal rifts ignore inside/outside enemy location restrictions. This option respects 'Use current moon enemy list' and 'Inside/Outside enemy blacklists'");
			TemporalRiftLocustSwarmChance = DuskConfig.Bind<float>("Temporal Rift Options", "Locust only rift chance", 0.85f, "Chance that a rift becomes a locust swarm when its first enemy wave begins, e.g. 0.85 = 85%");
			TemporalRiftMinimumLocustWaveSize = DuskConfig.Bind<int>("Temporal Rift Options", "Min locust spawn count", 1, "Minimum number of locusts released in each wave from a locust swarm rift");
			TemporalRiftMaximumLocustWaveSize = DuskConfig.Bind<int>("Temporal Rift Options", "Max locust spawn count", 3, "Maximum number of locusts released in each wave from a locust swarm rift");
			TemporalRiftMinimumEnemyPowerBudget = DuskConfig.Bind<float>("Temporal Rift Options", "Minimum enemy power budget", 2f, "Minimum enemy power budget assigned to a temporal rift");
			TemporalRiftMaximumEnemyPowerBudget = DuskConfig.Bind<float>("Temporal Rift Options", "Maximum enemy power budget", 4f, "Maximum enemy power budget assigned to a temporal rift");
			TemporalRiftInsideEnemyBlacklist = DuskConfig.Bind<string>("Temporal Rift Options", "Inside enemy blacklist", "lethal_company:butler_bees,lethal_company:girl", "DawnLib enemy namespaced keys that inside temporal rifts cannot spawn, separated by commas");
			TemporalRiftOutsideEnemyBlacklist = DuskConfig.Bind<string>("Temporal Rift Options", "Outside enemy blacklist", "lethal_company:red_locust_bees,lethal_company:manticoil,lethal_company:docile_locust_bees,lethal_company:feiopar,lethal_company:giantkiwi,lethal_company:bush_wolf,lethallib:sparktower,code_rebirth:tornado,code_rebirth:guardsman", "DawnLib enemy namespaced keys that outside temporal rifts cannot spawn, separated by commas");
			EntityGlitchEnabled = DuskConfig.Bind<bool>("Temporal Storm Visual Options", "Entity Glitch Enabled", true, "If true, temporal instability can apply glitch materials to entities");
			EntityGlitchPlayerModels = DuskConfig.Bind<bool>("Temporal Storm Visual Options", "Player models glitch", true, "If true, temporal instability can apply glitch materials to other player models");
			EntityGlitchEnemyBlacklist = DuskConfig.Bind<string>("Temporal Storm Visual Options", "Enemy Blacklist", "lethal_company:girl,lethal_company:blob,lethal_company:clay_surgeon,surfaced:mantis_shrimp,surfaced:urchin,surfaced:horse,surfaced:scary,lethallib:shrimp,lethallib:sparktower,lethallib:tourist,lethallib:tour_bus,code_rebirth:tornado,code_rebirth:mistress", "DawnLib enemy namespaced keys that cannot receive temporal glitch effects, separated by commas");
			AudioPitchingEnabled = DuskConfig.Bind<bool>("Temporal Storm Audio Options", "Audio Pitching Enabled", true, "If true, temporal instability can pitch and filter active audio sources");
			MaxBackgroundAudioVolume = DuskConfig.Bind<float>("Temporal Storm Audio Options", "Maximum Background Audio Volume", 0.8f, "The maximum volume level for background audio during Temporal Storms, e.g. 1 = 100% volume, 0.5 = 50% volume, etc.");
			MaxTuningCylinderAudioVolume = DuskConfig.Bind<float>("Temporal Storm Audio Options", "Maximum Tuning Cylinder Audio Volume", 1f, "The maximum volume level for tuning cylinder music, e.g. 1 = 100% volume, 0.5 = 50% volume, etc.");
			MaxApproachingWarningAudioVolume = DuskConfig.Bind<float>("Temporal Storm Audio Options", "Maximum Approaching Warning Audio Volume", 1f, "The maximum volume level for the first warning audio, e.g. 1 = 100% volume, 0.5 = 50% volume, etc.");
			MaxImminentWarningAudioVolume = DuskConfig.Bind<float>("Temporal Storm Audio Options", "Maximum Imminent Warning Audio Volume", 0.7f, "The maximum volume level for the second warning audio, e.g. 1 = 100% volume, 0.5 = 50% volume, etc.");
			MaxLowStabilityAudioVolume = DuskConfig.Bind<float>("Temporal Storm Audio Options", "Maximum Low Stability Warning Audio Volume", 0.9f, "The maximum volume level for third warning audio, e.g. 1 = 100% volume, 0.5 = 50% volume, etc.");
			MaxWaningAudioVolume = DuskConfig.Bind<float>("Temporal Storm Audio Options", "Maximum Waning Audio Volume", 0.9f, "The maximum volume level for bell audio that plays when the storm wanes, e.g. 1 = 100% volume, 0.5 = 50% volume, etc.");
			MaxWarningBellAudioVolume = DuskConfig.Bind<float>("Temporal Storm Audio Options", "Maximum Warning Bell Audio Volume", 0.9f, "The maximum volume level for bell audio that plays at each warning, e.g. 1 = 100% volume, 0.5 = 50% volume, etc.");
			DebugLogsEnabled = DuskConfig.Bind<bool>("Internal", "Enable Debug Logging", false, "If true, enables debug logging");
		}
	}
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInPlugin("MrHat.TemporalStormWeather.Internals", "TemporalStormWeather", "0.0.8")]
	internal class Plugin : BaseUnityPlugin
	{
		private const string DawnLibGUID = "com.github.teamxiaolan.dawnlib";

		private const string DuskGUID = "com.github.teamxiaolan.dawnlib.dusk";

		private const string PathfindingLibGUID = "Zaggy1024.PathfindingLib";

		private const string HatLibGUID = "MrHat.Lib";

		private const string BasedDecorPlacementGUID = "MrHat.BasedDecorPlacement";

		private const string CullFactoryGUID = "com.fumiko.CullFactory";

		private const string BrutalCompanyMinusExtraRebornGUID = "SoftDiamond.BrutalCompanyMinusExtraReborn";

		private const string StarlancerAIFixGUID = "AudioKnight.StarlancerAIFix";

		private const string CoronerGUID = "com.elitemastereric.coroner";

		internal const string modGUID = "MrHat.TemporalStormWeather.Internals";

		internal const string modName = "TemporalStormWeather";

		internal const string modVersion = "0.0.8";

		internal static ManualLogSource? mls;

		internal static bool hasBasedDecorPlacement;

		internal static bool hasCullFactory;

		internal static bool hasBCMER;

		internal static bool hasStarlancerAIFix;

		internal static bool hasCoroner;

		private readonly Harmony _harmony = new Harmony("MrHat.TemporalStormWeather.Internals");

		internal static Plugin? Instance { get; private set; }

		private void Awake()
		{
			Instance = this;
			mls = Logger.CreateLogSource("MrHat.TemporalStormWeather.Internals");
			Log.Info("                   +++     +++");
			Log.Info("            ++     ++++   ++++     ++");
			Log.Info("           +++++ +++++++++++++++ +++++");
			Log.Info("            +++++++++++++++++++++++++");
			Log.Info("      ++++++++++++++++++++++++++++++++++++++");
			Log.Info("      +++++++++++++++++++++++++++++++++++++");
			Log.Info("        +++++++++++    ++++    +++++++++++");
			Log.Info("  ++++++++++++++       ++++       ++++++++++++++");
			Log.Info(" +++++++++++++         ++++         +++++++++++++");
			Log.Info("     +++++++++++++   ++++++++   +++++++++++++");
			Log.Info("    ++++++++ ++++++++++++++++++++++++ ++++++++");
			Log.Info("+++++++++++     +++++++     ++++++     +++++++++++");
			Log.Info("+++++++++++      ++++        ++++      +++++++++++");
			Log.Info("    +++++++      ++++        ++++      +++++++");
			Log.Info("    +++++++     ++++++      ++++++     +++++++");
			Log.Info("++++++++++++ ++++++++++++++++++++++++ ++++++++++++");
			Log.Info(" ++++++++++++++++    ++++++++    ++++++++++++++++");
			Log.Info("     +++++++++         ++++         +++++++++");
			Log.Info("     +++++++++++       ++++        ++++++++++");
			Log.Info("   +++++++++++++++     ++++     +++++++++++++++");
			Log.Info("    +++  ++++++++++++++++++++++++++++++++  +++");
			Log.Info("          ++++++++++++++++++++++++++++++");
			Log.Info("         ++++++++++++++++++++++++++++++++");
			Log.Info("          ++    ++++++++++++++++++    ++");
			Log.Info("                ++++   ++++   ++++");
			Log.Info("                 ++    ++++    ++");
			hasBasedDecorPlacement = Chainloader.PluginInfos.ContainsKey("MrHat.BasedDecorPlacement");
			hasCullFactory = Chainloader.PluginInfos.ContainsKey("com.fumiko.CullFactory");
			hasBCMER = Chainloader.PluginInfos.ContainsKey("SoftDiamond.BrutalCompanyMinusExtraReborn");
			hasStarlancerAIFix = Chainloader.PluginInfos.ContainsKey("AudioKnight.StarlancerAIFix");
			hasCoroner = Chainloader.PluginInfos.ContainsKey("com.elitemastereric.coroner");
			ConfigManager.BindConfigs();
			DawnSaveManager.HookItemEffectSave();
			StartOfRoundEvents.Register();
			GameObject val = TemporalInstabilityManager.LoadTemporalInstabilityPrefab();
			if ((Object)(object)val == (Object)null)
			{
				Log.Error("Temporal storm network prefab is missing");
			}
			else
			{
				DawnLib.RegisterNetworkPrefab(val);
			}
			InitialiseNetworkBehaviour(typeof(BellEnemyAI));
			InitialiseNetworkBehaviour(typeof(LocustEnemyBase));
			InitialiseNetworkBehaviour(typeof(LocustEnemyAI));
			InitialiseNetworkBehaviour(typeof(SawbladeLocustEnemyAI));
			InitialiseNetworkBehaviour(typeof(CorruptLocustEnemyAI));
			InitialiseNetworkBehaviour(typeof(GearPileHazard));
			InitialiseNetworkBehaviour(typeof(TemporalRift));
			InitialiseNetworkBehaviour(typeof(TemporalGearItem));
			InitialiseNetworkBehaviour(typeof(ResonatorSurface));
			InitialiseNetworkBehaviour(typeof(RustHazardManager));
			InitialiseNetworkBehaviour(typeof(TemporalInstabilityManager));
			Log.Info("TemporalStormWeather 0.0.8 loaded");
			_harmony.PatchAll(typeof(EnemyAIPatches));
			_harmony.PatchAll(typeof(FlashlightItemPatches));
			_harmony.PatchAll(typeof(GameNetworkManagerPatches));
			_harmony.PatchAll(typeof(GrabbableObjectPatches));
			_harmony.PatchAll(typeof(HUDManagerPatches));
			_harmony.PatchAll(typeof(LungPropPatches));
			_harmony.PatchAll(typeof(PlayerControllerBPatches));
			_harmony.PatchAll(typeof(SoundManagerPatches));
			_harmony.PatchAll(typeof(ChatGlitchManager));
			_harmony.PatchAll(typeof(TimeOfDayPatches));
			if (hasBasedDecorPlacement)
			{
				Log.Debug("Running BasedDecorPlacement compatibility");
				BasedDecorPlacementCompat.RegisterSurfaceExtensions();
				Log.Info("BasedDecorPlacement compatibility enabled");
			}
			if (hasCullFactory)
			{
				Log.Debug("Running CullFactory compatibility");
				_harmony.PatchAll(typeof(CullFactoryCompat));
				Log.Info("CullFactory compatibility enabled");
			}
			if (hasBCMER)
			{
				Log.Debug("Running Brutal Company Minus Extra Reborn compatibility");
				BCMERCompatibility.RegisterEvents();
				Log.Info("Brutal Company Minus Extra Reborn compatibility enabled");
			}
			if (hasCoroner)
			{
				Log.Debug("Running Coroner compatibility");
				CoronerCompat.Register();
				Log.Info("Coroner compatibility enabled");
			}
		}

		private void InitialiseNetworkBehaviour(Type type)
		{
			MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic);
			MethodInfo[] array = methods;
			foreach (MethodInfo methodInfo in array)
			{
				object[] customAttributes = methodInfo.GetCustomAttributes(typeof(RuntimeInitializeOnLoadMethodAttribute), inherit: false);
				if (customAttributes.Length != 0)
				{
					methodInfo.Invoke(null, null);
				}
			}
		}
	}
	public static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "TemporalStormWeather";

		public const string PLUGIN_NAME = "TemporalStormWeather";

		public const string PLUGIN_VERSION = "0.0.8";
	}
}
namespace TemporalStormWeather.Utils
{
	internal static class Keys
	{
		public const string DuskGUID = "MrHat.TemporalStormWeather";

		public const string AssetBundleName = "temporalstormotherassets";

		public const string TemporalInstabilityNetworkPrefabPath = "Assets/LethalCompany/Mods/plugins/TemporalStormWeather/Content/Temporal Storm/TemporalInstabilityNetwork.prefab";

		public const string TemporalStormAmbienceLibraryPath = "Assets/LethalCompany/Mods/plugins/TemporalStormWeather/Content/Temporal Storm/TemporalStormAmbienceLibrary.asset";

		public const string Namespace = "temporalstorm";

		public const string TemporalStorm = "temporal_storm";

		public const string TemporalRift = "temporal_rift";

		public const string ItemEffects = "item_effects";

		public const string GearsPile = "gears_pile";

		public const string LargeSpikesPile = "large_spikes_pile";

		public const string MediumSpikesPile = "medium_spikes_pile";

		public const string SmallSpikesPile = "small_spikes_pile";

		public const string SpikesOne = "spikesone";

		public const string SpikesTwo = "spikestwo";

		public const string SpikesThree = "spikesthree";

		public const string TinySpikesPile = "tiny_spikes_pile";

		public const string TemporalGear = "temporal_gear";

		public const string MadnessGear = "madness_gear";

		public const string LocustEnemy = "locustenemy";

		public const string SawbladeLocustEnemy = "sawbladelocustenemy";

		public const string CorruptLocustEnemy = "corruptlocustenemy";

		public static readonly NamespacedKey<DawnWeatherEffectInfo> TemporalStormWeather = NamespacedKey<DawnWeatherEffectInfo>.From("temporalstorm", "temporal_storm");

		public static readonly NamespacedKey<DawnMapObjectInfo> TemporalRiftMapObject = NamespacedKey<DawnMapObjectInfo>.From("temporalstorm", "temporal_rift");

		public static readonly NamespacedKey ItemEffectsSaveData = NamespacedKey.From("temporalstorm", "item_effects");

		public static readonly NamespacedKey<DawnMapObjectInfo> GearsPileMapObject = NamespacedKey<DawnMapObjectInfo>.From("temporalstorm", "gears_pile");

		public static readonly NamespacedKey<DawnMapObjectInfo> LargeSpikesPileMapObject = NamespacedKey<DawnMapObjectInfo>.From("temporalstorm", "large_spikes_pile");

		public static readonly NamespacedKey<DawnMapObjectInfo> MediumSpikesPileMapObject = NamespacedKey<DawnMapObjectInfo>.From("temporalstorm", "medium_spikes_pile");

		public static readonly NamespacedKey<DawnMapObjectInfo> SmallSpikesPileMapObject = NamespacedKey<DawnMapObjectInfo>.From("temporalstorm", "small_spikes_pile");

		public static readonly NamespacedKey<DawnMapObjectInfo> SpikesOneMapObject = NamespacedKey<DawnMapObjectInfo>.From("temporalstorm", "spikesone");

		public static readonly NamespacedKey<DawnMapObjectInfo> SpikesTwoMapObject = NamespacedKey<DawnMapObjectInfo>.From("temporalstorm", "spikestwo");

		public static readonly NamespacedKey<DawnMapObjectInfo> SpikesThreeMapObject = NamespacedKey<DawnMapObjectInfo>.From("temporalstorm", "spikesthree");

		public static readonly NamespacedKey<DawnMapObjectInfo> TinySpikesPileMapObject = NamespacedKey<DawnMapObjectInfo>.From("temporalstorm", "tiny_spikes_pile");

		public static readonly NamespacedKey<DawnItemInfo> TemporalGearItem = NamespacedKey<DawnItemInfo>.From("temporalstorm", "temporal_gear");

		public static readonly NamespacedKey<DawnItemInfo> MadnessGearItem = NamespacedKey<DawnItemInfo>.From("temporalstorm", "madness_gear");

		public static readonly NamespacedKey<DawnEnemyInfo> LocustEnemyInfo = NamespacedKey<DawnEnemyInfo>.From("temporalstorm", "locustenemy");

		public static readonly NamespacedKey<DawnEnemyInfo> SawbladeLocustEnemyInfo = NamespacedKey<DawnEnemyInfo>.From("temporalstorm", "sawbladelocustenemy");

		public static readonly NamespacedKey<DawnEnemyInfo> CorruptLocustEnemyInfo = NamespacedKey<DawnEnemyInfo>.From("temporalstorm", "corruptlocustenemy");

		public static readonly NamespacedKey<DawnMapObjectInfo>[] TemporalRustMapObjects = new NamespacedKey<DawnMapObjectInfo>[7] { LargeSpikesPileMapObject, MediumSpikesPileMapObject, SmallSpikesPileMapObject, SpikesOneMapObject, SpikesTwoMapObject, SpikesThreeMapObject, TinySpikesPileMapObject };
	}
	internal static class Log
	{
		public static void Debug(string message)
		{
			if (ConfigManager.DebugLogsEnabled.Value)
			{
				Write((LogLevel)32, message);
			}
		}

		public static void Info(string message)
		{
			Write((LogLevel)16, message);
		}

		public static void Warn(string message)
		{
			Write((LogLevel)4, message);
		}

		public static void Error(string message)
		{
			Write((LogLevel)2, message);
		}

		public static void Fatal(string message)
		{
			Write((LogLevel)1, message);
		}

		private static void Write(LogLevel logLevel, string message)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			if (Plugin.mls != null)
			{
				Plugin.mls.Log(logLevel, (object)message);
			}
		}
	}
	internal static class Utility
	{
		public static void BindPositionConstraint(PositionConstraint positionConstraint, Transform sourceTransform)
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			if (positionConstraint.sourceCount > 0)
			{
				ConstraintSource source = positionConstraint.GetSource(0);
				if (!((Object)(object)((ConstraintSource)(ref source)).sourceTransform == (Object)(object)sourceTransform))
				{
					((ConstraintSource)(ref source)).sourceTransform = sourceTransform;
					positionConstraint.SetSource(0, source);
				}
			}
		}

		public static float ClampInstability(float value)
		{
			return Mathf.Clamp(value, 0f, 100f);
		}

		public static float InstabilityProgress(float temporalInstabilityLevel, float startLevel, float fullLevel)
		{
			return Mathf.InverseLerp(startLevel, fullLevel, temporalInstabilityLevel);
		}

		public static bool ShouldRunWeatherLifecycle()
		{
			return (Object)(object)StartOfRound.Instance != (Object)null && (Object)(object)RoundManager.Instance?.currentLevel != (Object)null && (Object)(object)TimeOfDay.Instance != (Object)null;
		}

		public static PlayerControllerB LocalPlayer()
		{
			return GameNetworkManager.Instance.localPlayerController;
		}

		public static Camera? LocalViewCamera()
		{
			PlayerControllerB val = LocalPlayer();
			return (val != null && val.isPlayerDead && (Object)(object)StartOfRound.Instance?.spectateCamera != (Object)null) ? StartOfRound.Instance.spectateCamera : val?.gameplayCamera;
		}

		public static Transform? LocalViewTransform()
		{
			Camera? obj = LocalViewCamera();
			return (obj != null) ? ((Component)obj).transform : null;
		}

		public static bool LocalViewIsInsideFactory()
		{
			PlayerControllerB val = LocalPlayer();
			return (val != null && val.isPlayerDead && (Object)(object)val.spectatedPlayerScript != (Object)null) ? val.spectatedPlayerScript.isInsideFactory : (val?.isInsideFactory ?? false);
		}

		public static bool IsPlayerActive(PlayerControllerB? player)
		{
			return player != null && player.isPlayerControlled && !player.isPlayerDead;
		}

		public static float RandomRange(Random random, float minimum, float maximum)
		{
			return Mathf.Lerp(minimum, maximum, (float)random.NextDouble());
		}

		public static float RandomRange(Random random, Vector2 range)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			return RandomRange(random, range.x, range.y);
		}
	}
	internal static class MapSpawnUtils
	{
		public static bool MatchesOutsideFloorTags(Collider collider, string[] spawnableFloorTags)
		{
			if (spawnableFloorTags == null || spawnableFloorTags.Length == 0)
			{
				return true;
			}
			for (int i = 0; i < spawnableFloorTags.Length; i++)
			{
				if (((Component)collider).CompareTag(spawnableFloorTags[i]))
				{
					return true;
				}
			}
			return false;
		}

		public static bool TryRaycastClosest(Vector3 origin, Vector3 direction, RaycastHit[] hits, float maxDistance, int layerMask, QueryTriggerInteraction queryTriggerInteraction, out RaycastHit closestHit)
		{
			//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_0007: 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_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_005b: 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)
			int num = Physics.RaycastNonAlloc(origin, direction, hits, maxDistance, layerMask, queryTriggerInteraction);
			float num2 = float.MaxValue;
			closestHit = default(RaycastHit);
			for (int i = 0; i < num; i++)
			{
				RaycastHit val = hits[i];
				if (!((Object)(object)((RaycastHit)(ref val)).collider == (Object)null) && !(((RaycastHit)(ref val)).distance >= num2))
				{
					num2 = ((RaycastHit)(ref val)).distance;
					closestHit = val;
				}
			}
			return (Object)(object)((RaycastHit)(ref closestHit)).collider != (Object)null;
		}

		public static bool IsDeniedOutsidePosition(Vector3 position, float objectWidth, EntranceTeleport[] entranceTeleports, Transform[] shipSpawnPathPoints, GameObject[] spawnDenialPoints, GameObject itemShipLandingNode)
		{
			//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_002b: 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_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: 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_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0140: 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_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)
			Collider shipBounds = StartOfRound.Instance.shipBounds;
			if ((Object)(object)shipBounds != (Object)null)
			{
				float num = Mathf.Max(0f, objectWidth);
				Vector3 val = shipBounds.ClosestPoint(position);
				Vector3 val2 = val - position;
				if (((Vector3)(ref val2)).sqrMagnitude <= num * num)
				{
					return true;
				}
			}
			if (shipSpawnPathPoints != null)
			{
				for (int i = 0; i < shipSpawnPathPoints.Length; i++)
				{
					if (Vector3.Distance(shipSpawnPathPoints[i].position, position) < objectWidth + 6f)
					{
						return true;
					}
				}
			}
			for (int j = 0; j < entranceTeleports.Length; j++)
			{
				if (Vector3.Distance(((Component)entranceTeleports[j]).transform.position, position) < objectWidth + 6f)
				{
					return true;
				}
			}
			if (spawnDenialPoints != null)
			{
				for (int k = 0; k < spawnDenialPoints.Length; k++)
				{
					if (Vector3.Distance(spawnDenialPoints[k].transform.position, position) < objectWidth)
					{
						return true;
					}
				}
			}
			return (Object)(object)itemShipLandingNode != (Object)null && Vector3.Distance(itemShipLandingNode.transform.position, position) < objectWidth;
		}

		public static void DestroyTreesAroundOutsideObject(SpawnableOutsideObject spawnableObject, Vector3 position)
		{
			//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_004d: Unknown result type (might be due to invalid IL or missing references)
			if (!spawnableObject.destroyTrees)
			{
				return;
			}
			GameObject[] array = GameObject.FindGameObjectsWithTag("Tree");
			for (int i = 0; i < array.Length; i++)
			{
				if (Vector3.Distance(array[i].transform.position, position) < (float)spawnableObject.objectWidth)
				{
					RoundManager.Instance.DestroyTreeAtPosition(array[i].transform.position, 5f);
				}
			}
		}
	}
	internal readonly struct OriginalMaterialPropertyIds
	{
		public readonly int Texture;

		public readonly int Color;

		public readonly int AlphaClipThreshold;

		public readonly int NormalTexture;

		public readonly int NormalScale;

		public readonly int Smoothness;

		public readonly int Metallic;

		public OriginalMaterialPropertyIds(int texture, int color, int alphaClipThreshold, int normalTexture, int normalScale, int smoothness, int metallic = -1)
		{
			Texture = texture;
			Color = color;
			AlphaClipThreshold = alphaClipThreshold;
			NormalTexture = normalTexture;
			NormalScale = normalScale;
			Smoothness = smoothness;
			Metallic = metallic;
		}
	}
	internal readonly struct EffectMaterialPropertyIds
	{
		public readonly int BaseTexture;

		public readonly int BaseColorTint;

		public readonly int AlphaClipThreshold;

		public readonly int NormalTexture;

		public readonly int NormalScale;

		public readonly int Smoothness;

		public readonly int Metallic;

		public EffectMaterialPropertyIds(int baseTexture, int baseColorTint, int alphaClipThreshold, int normalTexture, int normalScale, int smoothness, int metallic = -1)
		{
			BaseTexture = baseTexture;
			BaseColorTint = baseColorTint;
			AlphaClipThreshold = alphaClipThreshold;
			NormalTexture = normalTexture;
			NormalScale = normalScale;
			Smoothness = smoothness;
			Metallic = metallic;
		}
	}
	internal enum MaterialPropertyCopyKind
	{
		Float,
		Color,
		Texture
	}
	internal static class MaterialUtils
	{
		private static readonly int alphaCutoffEnablePropertyId = Shader.PropertyToID("_AlphaCutoffEnable");

		private static readonly int emissiveColorPropertyId = Shader.PropertyToID("_EmissiveColor");

		private static readonly int emissionColorPropertyId = Shader.PropertyToID("_EmissionColor");

		private static readonly int surfaceTypePropertyId = Shader.PropertyToID("_SurfaceType");

		private static readonly int blendModePropertyId = Shader.PropertyToID("_BlendMode");

		private static readonly int zWritePropertyId = Shader.PropertyToID("_ZWrite");

		private static readonly int transparentZWritePropertyId = Shader.PropertyToID("_TransparentZWrite");

		private static readonly int[] copiedFloatPropertyIds = new int[35]
		{
			Shader.PropertyToID("_SurfaceType"),
			Shader.PropertyToID("_BlendMode"),
			Shader.PropertyToID("_AlphaSrcBlend"),
			Shader.PropertyToID("_AlphaDstBlend"),
			Shader.PropertyToID("_SrcBlend"),
			Shader.PropertyToID("_DstBlend"),
			Shader.PropertyToID("_ZWrite"),
			Shader.PropertyToID("_TransparentZWrite"),
			Shader.PropertyToID("_ZTest"),
			Shader.PropertyToID("_CullMode"),
			Shader.PropertyToID("_CullModeForward"),
			Shader.PropertyToID("_TransparentCullMode"),
			Shader.PropertyToID("_AlphaCutoffEnable"),
			Shader.PropertyToID("_DoubleSidedEnable"),
			Shader.PropertyToID("_TransparentDepthPrepassEnable"),
			Shader.PropertyToID("_TransparentDepthPostpassEnable"),
			Shader.PropertyToID("_TransparentWritesMotionVec"),
			Shader.PropertyToID("_EnableFogOnTransparent"),
			Shader.PropertyToID("_ReceivesSSR"),
			Shader.PropertyToID("_ReceivesSSRTransparent"),
			Shader.PropertyToID("_TransparentSortPriority"),
			Shader.PropertyToID("_EnableBlendModePreserveSpecularLighting"),
			Shader.PropertyToID("_SpecularOcclusionMode"),
			Shader.PropertyToID("_MaterialID"),
			Shader.PropertyToID("_DisplacementMode"),
			Shader.PropertyToID("_RefractionModel"),
			Shader.PropertyToID("_RefractionSSRayModel"),
			Shader.PropertyToID("_ReceivesDecals"),
			Shader.PropertyToID("_GeometricSpecularAA"),
			Shader.PropertyToID("_UseShadowThreshold"),
			Shader.PropertyToID("_PreRefractionPass"),
			Shader.PropertyToID("_RenderingPass"),
			Shader.PropertyToID("_EmissiveIntensity"),
			Shader.PropertyToID("_EmissiveExposureWeight"),
			Shader.PropertyToID("_AlbedoAffectEmissive")
		};

		private static readonly int[] copiedColorPropertyIds = new int[1] { Shader.PropertyToID("_TransmittanceColor") };

		private static readonly int[] copiedTexturePropertyIds = new int[7]
		{
			Shader.PropertyToID("_MaskMap"),
			Shader.PropertyToID("_BentNormalMap"),
			Shader.PropertyToID("_CoatMaskMap"),
			Shader.PropertyToID("_DetailMap"),
			Shader.PropertyToID("_EmissiveColorMap"),
			Shader.PropertyToID("_EmissionMap"),
			Shader.PropertyToID("_TransmittanceColorMap")
		};

		private static readonly string[] copiedMaterialKeywords = new string[12]
		{
			"_ALPHATEST_ON", "_SURFACE_TYPE_TRANSPARENT", "_BLENDMODE_ALPHA", "_BLENDMODE_ADD", "_BLENDMODE_PRE_MULTIPLY", "_BLENDMODE_PRESERVE_SPECULAR_LIGHTING", "_ENABLE_FOG_ON_TRANSPARENT", "_ENABLE_SSR_TRANSPARENT", "_DOUBLESIDED_ON", "_NORMALMAP_TANGENT_SPACE",
			"_EMISSION", "_EMISSIVE_COLOR_MAP"
		};

		public static bool IsCreatedEffectMaterial(Material? material, Material[]? originalMaterials, int materialIndex)
		{
			return (Object)(object)material != (Object)null && (originalMaterials == null || materialIndex >= originalMaterials.Length || (Object)(object)material != (Object)(object)originalMaterials[materialIndex]);
		}

		public static float CopyOriginalMaterialProperties(Material originalMaterial, Material effectMaterial, OriginalMaterialPropertyIds originalIds, EffectMaterialPropertyIds effectIds, float defaultAlphaClipThreshold)
		{
			//IL_0008: 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_01be: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b0: 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_01f9: 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_0200: 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_021b: 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_0238: 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_01ec: 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_0290: 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_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)
			effectMaterial.SetColor(effectIds.BaseColorTint, Color.white);
			float num = defaultAlphaClipThreshold;
			if ((Object)(object)originalMaterial == (Object)null)
			{
				return num;
			}
			effectMaterial.renderQueue = originalMaterial.renderQueue;
			effectMaterial.doubleSidedGI = originalMaterial.doubleSidedGI;
			effectMaterial.globalIlluminationFlags = originalMaterial.globalIlluminationFlags;
			effectMaterial.enableInstancing = originalMaterial.enableInstancing;
			string tag = originalMaterial.GetTag("RenderType", false, string.Empty);
			if (!string.IsNullOrEmpty(tag))
			{
				effectMaterial.SetOverrideTag("RenderType", tag);
			}
			string tag2 = originalMaterial.GetTag("Queue", false, string.Empty);
			if (!string.IsNullOrEmpty(tag2))
			{
				effectMaterial.SetOverrideTag("Queue", tag2);
			}
			for (int i = 0; i < copiedMaterialKeywords.Length; i++)
			{
				string text = copiedMaterialKeywords[i];
				if (originalMaterial.IsKeywordEnabled(text))
				{
					effectMaterial.EnableKeyword(text);
				}
				else
				{
					effectMaterial.DisableKeyword(text);
				}
			}
			string[] shaderKeywords = originalMaterial.shaderKeywords;
			for (int j = 0; j < shaderKeywords.Length; j++)
			{
				effectMaterial.EnableKeyword(shaderKeywords[j]);
			}
			CopyMatchingProperties(originalMaterial, effectMaterial, copiedFloatPropertyIds, MaterialPropertyCopyKind.Float);
			CopyMatchingProperties(originalMaterial, effectMaterial, copiedColorPropertyIds, MaterialPropertyCopyKind.Color);
			CopyMatchingProperties(originalMaterial, effectMaterial, copiedTexturePropertyIds, MaterialPropertyCopyKind.Texture);
			CopyTextureProperties(originalMaterial, effectMaterial, originalIds.Texture, effectIds.BaseTexture, (Texture?)(object)Texture2D.whiteTexture);
			bool flag = (originalMaterial.HasProperty(alphaCutoffEnablePropertyId) && originalMaterial.GetFloat(alphaCutoffEnablePropertyId) > 0.5f) || originalMaterial.IsKeywordEnabled("_ALPHATEST_ON");
			Color val = (originalMaterial.HasProperty(originalIds.Color) ? originalMaterial.GetColor(originalIds.Color) : Color.white);
			Color val2 = (originalMaterial.HasProperty(emissiveColorPropertyId) ? originalMaterial.GetColor(emissiveColorPropertyId) : (originalMaterial.HasProperty(emissionColorPropertyId) ? originalMaterial.GetColor(emissionColorPropertyId) : Color.black));
			float num2 = val.r * 0.2126f + val.g * 0.7152f + val.b * 0.0722f;
			float num3 = val2.r * 0.2126f + val2.g * 0.7152f + val2.b * 0.0722f;
			bool flag2 = num2 <= 0.035f && num3 > 0.035f;
			if (flag2)
			{
				val2.a = val.a;
				val = val2;
			}
			effectMaterial.SetColor(effectIds.BaseColorTint, val);
			if (originalMaterial.HasProperty(originalIds.AlphaClipThreshold) && effectMaterial.HasProperty(effectIds.AlphaClipThreshold))
			{
				num = (flag ? originalMaterial.GetFloat(originalIds.AlphaClipThreshold) : 0f);
				effectMaterial.SetFloat(effectIds.AlphaClipThreshold, num);
			}
			else if (effectMaterial.HasProperty(effectIds.AlphaClipThreshold))
			{
				num = (flag ? defaultAlphaClipThreshold : 0f);
				effectMaterial.SetFloat(effectIds.AlphaClipThreshold, num);
			}
			if (!flag)
			{
				SetFloatIfPresent(effectMaterial, alphaCutoffEnablePropertyId, 0f);
				effectMaterial.DisableKeyword("_ALPHATEST_ON");
			}
			CopyTextureProperties(originalMaterial, effectMaterial, originalIds.NormalTexture, effectIds.NormalTexture);
			if (originalMaterial.HasProperty(originalIds.NormalScale) && effectMaterial.HasProperty(effectIds.NormalScale))
			{
				effectMaterial.SetFloat(effectIds.NormalScale, originalMaterial.GetFloat(originalIds.NormalScale));
			}
			if (originalMaterial.HasProperty(originalIds.Smoothness) && effectMaterial.HasProperty(effectIds.Smoothness))
			{
				effectMaterial.SetFloat(effectIds.Smoothness, flag2 ? 0.045f : originalMaterial.GetFloat(originalIds.Smoothness));
			}
			if (originalIds.Metallic >= 0 && effectIds.Metallic >= 0 && originalMaterial.HasProperty(originalIds.Metallic) && effectMaterial.HasProperty(effectIds.Metallic))
			{
				effectMaterial.SetFloat(effectIds.Metallic, flag2 ? 0f : originalMaterial.GetFloat(originalIds.Metallic));
			}
			return num;
		}

		public static void ForceOpaqueCutout(Material material)
		{
			material.renderQueue = 2450;
			material.SetOverrideTag("RenderType", "TransparentCutout");
			material.SetOverrideTag("Queue", "AlphaTest");
			material.DisableKeyword("_SURFACE_TYPE_TRANSPARENT");
			material.DisableKeyword("_BLENDMODE_ALPHA");
			material.DisableKeyword("_BLENDMODE_ADD");
			material.DisableKeyword("_BLENDMODE_PRE_MULTIPLY");
			SetFloatIfPresent(material, surfaceTypePropertyId, 0f);
			SetFloatIfPresent(material, blendModePropertyId, 0f);
			SetFloatIfPresent(material, zWritePropertyId, 1f);
			SetFloatIfPresent(material, transparentZWritePropertyId, 1f);
		}

		public static void DestroyMaterials(Material[]? materials, Material[]? originalMaterials = null)
		{
			if (materials == null)
			{
				return;
			}
			for (int i = 0; i < materials.Length; i++)
			{
				Material val = materials[i];
				if (IsCreatedEffectMaterial(val, originalMaterials, i))
				{
					Object.Destroy((Object)(object)val);
				}
			}
		}

		public static void SetFloatOnCreatedMaterials(Material[]? materials, Material[]? originalMaterials, int propertyId, float value)
		{
			if (materials == null)
			{
				return;
			}
			for (int i = 0; i < materials.Length; i++)
			{
				Material val = materials[i];
				if (IsCreatedEffectMaterial(val, originalMaterials, i))
				{
					val.SetFloat(propertyId, value);
				}
			}
		}

		public static void CopyFromFirstProperty(Material? sourceMaterial, Material targetMaterial, int[] sourcePropertyIds, int targetPropertyId, MaterialPropertyCopyKind propertyKind, Texture? defaultTexture = null)
		{
			//IL_0079: 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_00bc: Unknown result type (might be due to invalid IL or missing references)
			if (!targetMaterial.HasProperty(targetPropertyId))
			{
				return;
			}
			if ((Object)(object)sourceMaterial != (Object)null)
			{
				foreach (int num in sourcePropertyIds)
				{
					if (!sourceMaterial.HasProperty(num))
					{
						continue;
					}
					switch (propertyKind)
					{
					case MaterialPropertyCopyKind.Float:
						targetMaterial.SetFloat(targetPropertyId, sourceMaterial.GetFloat(num));
						return;
					case MaterialPropertyCopyKind.Color:
						targetMaterial.SetColor(targetPropertyId, sourceMaterial.GetColor(num));
						return;
					case MaterialPropertyCopyKind.Texture:
					{
						Texture texture = sourceMaterial.GetTexture(num);
						if ((Object)(object)texture == (Object)null)
						{
							break;
						}
						targetMaterial.SetTexture(targetPropertyId, texture);
						targetMaterial.SetTextureScale(targetPropertyId, sourceMaterial.GetTextureScale(num));
						targetMaterial.SetTextureOffset(targetPropertyId, sourceMaterial.GetTextureOffset(num));
						return;
					}
					}
				}
			}
			if (propertyKind == MaterialPropertyCopyKind.Texture && (Object)(object)defaultTexture != (Object)null)
			{
				targetMaterial.SetTexture(targetPropertyId, defaultTexture);
			}
		}

		private static void CopyTextureProperties(Material originalMaterial, Material effectMaterial, int originalPropertyId, int effectPropertyId, Texture? defaultTexture = null)
		{
			//IL_0062: 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 (!effectMaterial.HasProperty(effectPropertyId))
			{
				return;
			}
			Texture val = (originalMaterial.HasProperty(originalPropertyId) ? originalMaterial.GetTexture(originalPropertyId) : null);
			if (!((Object)(object)val == (Object)null) || !((Object)(object)defaultTexture == (Object)null))
			{
				effectMaterial.SetTexture(effectPropertyId, val ?? defaultTexture);
				if (originalMaterial.HasProperty(originalPropertyId))
				{
					effectMaterial.SetTextureScale(effectPropertyId, originalMaterial.GetTextureScale(originalPropertyId));
					effectMaterial.SetTextureOffset(effectPropertyId, originalMaterial.GetTextureOffset(originalPropertyId));
				}
			}
		}

		private static void SetFloatIfPresent(Material material, int propertyId, float value)
		{
			if (material.HasProperty(propertyId))
			{
				material.SetFloat(propertyId, value);
			}
		}

		private static void CopyMatchingProperties(Material originalMaterial, Material effectMaterial, int[] propertyIds, MaterialPropertyCopyKind propertyKind)
		{
			//IL_005a: 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_009a: Unknown result type (might be due to invalid IL or missing references)
			foreach (int num in propertyIds)
			{
				if (!originalMaterial.HasProperty(num) || !effectMaterial.HasProperty(num))
				{
					continue;
				}
				switch (propertyKind)
				{
				case MaterialPropertyCopyKind.Float:
					effectMaterial.SetFloat(num, originalMaterial.GetFloat(num));
					break;
				case MaterialPropertyCopyKind.Color:
					effectMaterial.SetColor(num, originalMaterial.GetColor(num));
					break;
				case MaterialPropertyCopyKind.Texture:
				{
					Texture texture = originalMaterial.GetTexture(num);
					if (!((Object)(object)texture == (Object)null))
					{
						effectMaterial.SetTexture(num, texture);
						effectMaterial.SetTextureScale(num, originalMaterial.GetTextureScale(num));
						effectMaterial.SetTextureOffset(num, originalMaterial.GetTextureOffset(num));
					}
					break;
				}
				}
			}
		}
	}
	internal static class ParticleUtils
	{
		public static void SetEmissionRateAndPlayback(ParticleSystem particleSystem, float rate, ParticleSystemStopBehavior stopBehavior)
		{
			//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_000b: 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)
			EmissionModule emission = particleSystem.emission;
			((EmissionModule)(ref emission)).rateOverTime = MinMaxCurve.op_Implicit(rate);
			if (rate > 0.001f)
			{
				if (!particleSystem.isPlaying)
				{
					particleSystem.Play(true);
				}
			}
			else if (particleSystem.isPlaying)
			{
				particleSystem.Stop(true, stopBehavior);
			}
		}
	}
	internal enum DawnItemPersistenceMode
	{
		PersistShip,
		Restore
	}
	internal static class DawnConfigUtils
	{
		public static HashSet<NamespacedKey<TInfo>> ParseNamespacedKeySet<TInfo>(string configuredKeys) where TInfo : INamespaced
		{
			HashSet<NamespacedKey<TInfo>> hashSet = new HashSet<NamespacedKey<TInfo>>();
			if (string.IsNullOrWhiteSpace(configuredKeys))
			{
				return hashSet;
			}
			string[] array = configuredKeys.Split(new char[4] { ',', ';', '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
			NamespacedKey val = default(NamespacedKey);
			for (int i = 0; i < array.Length; i++)
			{
				string text = array[i].Trim();
				if (NamespacedKey.TryParse(text, ref val))
				{
					hashSet.Add(val.AsTyped<TInfo>());
				}
			}
			return hashSet;
		}

		public static bool CanUseDawnItem(GrabbableObject item, bool includeNonConductive, DawnItemPersistenceMode persistenceMode)
		{
			return (Object)(object)item?.itemProperties != (Object)null && (item.itemProperties.isConductiveMetal || includeNonConductive) && (Object)(object)((Component)item).GetComponent<TemporalGearItem>() == (Object)null && ItemExtensions.GetDawnInfo(item.itemProperties) != null && (persistenceMode != DawnItemPersistenceMode.PersistShip || item.isInShipRoom) && !item.isHeld && (Object)(object)item.playerHeldBy == (Object)null && !item.isHeldByEnemy;
		}
	}
	internal static class ItemUtils
	{
		public static bool IsHeldByLocalPlayer(GrabbableObject item)
		{
			return (Object)(object)item?.playerHeldBy != (Object)null && (Object)(object)item.playerHeldBy == (Object)(object)Utility.LocalPlayer();
		}

		public static uint BuildItemSeed(GrabbableObject item)
		{
			ulong networkObjectId = ((NetworkBehaviour)item).NetworkObject.NetworkObjectId;
			uint num = 2166136261u;
			num = (num ^ (uint)(int)networkObjectId) * 16777619;
			num = (num ^ (uint)(int)(networkObjectId >> 32)) * 16777619;
			return (num ^ (uint)item.itemProperties.itemId) * 16777619;
		}

		public static uint Mix(uint value)
		{
			value ^= value >> 16;
			value *= 2246822519u;
			value ^= value >> 13;
			value *= 3266489917u;
			value ^= value >> 16;
			return value;
		}
	}
	internal static class TemporalMaterialUtils
	{
		public static void SetTemporalState(Renderer renderer, MaterialPropertyBlock propertyBlock, float glowStrength, float rustAmount)
		{
			renderer.GetPropertyBlock(propertyBlock);
			propertyBlock.SetFloat("_TemporalGlowStrength", glowStrength);
			propertyBlock.SetFloat("_TemporalRustAmount", rustAmount);
			renderer.SetPropertyBlock(propertyBlock);
		}
	}
	internal static class NetworkUtils
	{
		public static bool IsServer()
		{
			NetworkManager singleton = NetworkManager.Singleton;
			return singleton != null && singleton.IsServer;
		}

		public static bool IsServerOrNotNetworked()
		{
			NetworkManager singleton = NetworkManager.Singleton;
			return !singleton.IsListening || singleton.IsServer;
		}
	}
	internal static class AudioUtils
	{
		public static bool Configure2DAudioSource(AudioSource? audioSource, bool loop, float volume = 0f)
		{
			if ((Object)(object)audioSource == (Object)null)
			{
				return false;
			}
			audioSource.spatialBlend = 0f;
			audioSource.loop = loop;
			audioSource.playOnAwake = false;
			audioSource.volume = volume;
			return true;
		}

		public static void PlayOneShot(AudioSource? audioSource, AudioClip? audioClip, float volume)
		{
			if (!((Object)(object)audioSource == (Object)null) && !((Object)(object)audioClip == (Object)null))
			{
				audioSource.PlayOneShot(audioClip, volume);
			}
		}

		public static void LoadAudioClips(params AudioClip?[] audioClips)
		{
			int num = 0;
			foreach (AudioClip val in audioClips)
			{
				if (AudioTools.Load(val))
				{
					num++;
				}
			}
			if (num > 0)
			{
				Log.Info($"Loaded {num} audio clips");
			}
		}

		public static void UnloadAudioClips(params AudioClip?[] audioClips)
		{
			int num = 0;
			foreach (AudioClip val in audioClips)
			{
				if (AudioTools.Unload(val))
				{
					num++;
				}
			}
			if (num > 0)
			{
				Log.Info($"Unloaded {num} audio clips");
			}
		}
	}
	internal static class WeatherUtils
	{
		public static bool TemporalStormActive(bool checkSelected = true, bool checkActive = true)
		{
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Expected I4, but got Unknown
			if ((Object)(object)TimeOfDay.Instance == (Object)null || (!checkSelected && !checkActive))
			{
				return false;
			}
			if (checkSelected)
			{
				SelectableLevel currentLevel = TimeOfDay.Instance.currentLevel;
				if ((Object)(object)currentLevel == (Object)null && (Object)(object)RoundManager.Instance != (Object)null)
				{
					currentLevel = RoundManager.Instance.currentLevel;
				}
				if ((Object)(object)currentLevel != (Object)null)
				{
					int num = (int)currentLevel.currentWeather;
					if (num >= 0 && num < TimeOfDay.Instance.effects.Length)
					{
						WeatherEffect val = TimeOfDay.Instance.effects[num];
						GameObject effectObject = val.effectObject;
						GameObject effectPermanentObject = val.effectPermanentObject;
						if ((Object)(object)((effectObject != null) ? effectObject.GetComponentInChildren<VisualManager>(true) : null) != (Object)null || (Object)(object)((effectPermanentObject != null) ? effectPermanentObject.GetComponentInChildren<VisualManager>(true) : null) != (Object)null)
						{
							return true;
						}
					}
				}
			}
			if (!checkActive)
			{
				return false;
			}
			for (int i = 0; i < TimeOfDay.Instance.effects.Length; i++)
			{
				WeatherEffect val2 = TimeOfDay.Instance.effects[i];
				GameObject effectObject2 = val2.effectObject;
				GameObject effectPermanentObject2 = val2.effectPermanentObject;
				if ((val2.effectEnabled || (effectObject2 != null && effectObject2.activeInHierarchy) || (effectPermanentObject2 != null && effectPermanentObject2.activeInHierarchy)) && ((Object)(object)((effectObject2 != null) ? effectObject2.GetComponentInChildren<VisualManager>(true) : null) != (Object)null || (Object)(object)((effectPermanentObject2 != null) ? effectPermanentObject2.GetComponentInChildren<VisualManager>(true) : null) != (Object)null))
				{
					return true;
				}
			}
			return false;
		}
	}
}
namespace TemporalStormWeather.Unlockables
{
	public class ResonatorSurface : PlaceableObjectsSurface
	{
		private const float RestoreSearchRadius = 12f;

		private const float PlaceTimeoutSeconds = 6f;

		[Header("Cylinder")]
		[SerializeField]
		private Transform cylinderPlacement = null;

		[SerializeField]
		private ScanNodeProperties scanNodeProperties = null;

		[SerializeField]
		private BoxCollider playingInteractCollider = null;

		[Header("Hover")]
		[SerializeField]
		private InteractTrigger resonatorStartInteractTrigger = null;

		private const string NoTuningCylinderHoverTip = "[No Tuning Cylinder inserted]";

		private const string ResonatorActiveHoverTip = "[Resonator already active]";

		private const string TemporalInstabilityShutdownHoverTip = "[Temporal instability too high]";

		[Header("Animation")]
		[SerializeField]
		private Animator resonatorAnimator = null;

		[SerializeField]
		private string animationBoolName = "isPlaying";

		[SerializeField]
		private float animationSpeedTransitionSeconds = 1f;

		[Header("Audio")]
		[SerializeField]
		private AudioSource resonatorAudioSource = null;

		[SerializeField]
		private AudioClip cylinderPlacedClip = null;

		[SerializeField]
		private AudioClip cylinderRemovedClip = null;

		[SerializeField]
		private AudioClip resonatorStartedClip = null;

		[Header("Audio Reaction")]
		[SerializeField]
		private Transform audioReactiveScaleTarget = null;

		[SerializeField]
		private float minimumAudioReactiveScale = 1f;

		[SerializeField]
		private float maximumAudioReactiveScale = 1.5f;

		[SerializeField]
		private float audioReactiveStrength = 1.5f;

		[SerializeField]
		private float audioReactiveSmoothingSeconds = 0.08f;

		[Header("Temporal Instability Shutdown")]
		[SerializeField]
		[Range(0f, 100f)]
		private float temporalInstabilityStopThreshold = 90f;

		[SerializeField]
		[Min(0.01f)]
		private float temporalInstabilityStopSeconds = 0.85f;

		private TuningCylinderItem storedCylinder = null;

		private TuningCylinderItem? pendingCylinder;

		private DawnSaveSync? cylinderSync;

		private Coroutine? temporalInstabilityStopCoroutine;

		private BoxCollider placementCollider = null;

		private bool cylinderAttached;

		private bool resonatorPlaying;

		private bool songStartPending;

		private bool audioReactionRunning;

		private bool animationSpeedChanging;

		private bool stopAnimationWhenFinished;

		private float pendingCylinderTimeout;

		private float songStartTime;

		private float animationStartSpeed;

		private float animationTargetSpeed;

		private float animationElapsedSeconds;

		private Vector3 audioReactiveBaseScale;

		private readonly float[] audioSamples = new float[64];

		private float audioReactiveCurrentScale;

		private void Awake()
		{
			PlaceableShipObject val = ((Component)base.parentTo).GetComponentInChildren<PlaceableShipObject>() ?? ((Component)this).GetComponentInParent<PlaceableShipObject>();
			if ((Object)(object)val == (Object)null)
			{
				Log.Warn("Resonator could not find its ship object");
				return;
			}
			UnlockableItem val2 = StartOfRound.Instance.unlockablesList.unlockables[val.unlockableID];
			NamespacedKey typedKey = (NamespacedKey)(object)((DawnBaseInfo<DawnUnlockableItemInfo>)(object)UnlockableItemExtensions.GetDawnInfo(val2)).TypedKey;
			cylinderSync = DawnSaveSync.Bind(typedKey, (Func<string>)WriteStoredCylinderData, (Action<string>)RestoreStoredCylinder, false);
		}

		private void Start()
		{
			//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)
			placementCollider = ((Component)base.triggerScript).GetComponent<BoxCollider>();
			resonatorAnimator.speed = 0f;
			resonatorAnimator.SetBool(animationBoolName, false);
			audioReactiveBaseScale = audioReactiveScaleTarget.localScale;
			audioReactiveCurrentScale = minimumAudioReactiveScale;
			RefreshStartInteractTrigger();
		}

		private void LateUpdate()
		{
			//IL_03d7: 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)
			if ((Object)(object)pendingCylinder != (Object)null)
			{
				if (Time.realtimeSinceStartup >= pendingCylinderTimeout)
				{
					pendingCylinder = null;
				}
				else if (!((GrabbableObject)pendingCylinder).isHeld && (Object)(object)((GrabbableObject)pendingCylinder).playerHeldBy == (Object)null && !((GrabbableObject)pendingCylinder).isHeldByEnemy)
				{
					TuningCylinderItem cylinder = pendingCylinder;
					pendingCylinder = null;
					AttachCylinder(cylinder, saveItem: true, playPlacedSound: true);
				}
			}
			if (cylinderAttached)
			{
				if ((Object)(object)storedCylinder == (Object)null)
				{
					StopTemporalInstabilityShutdown();
					StopResonatorAnimation();
					StopAudioReaction();
					scanNodeProperties.subText = string.Empty;
					cylinderAttached = false;
					RefreshStartInteractTrigger();
					((Collider)placementCollider).enabled = true;
					ClearStoredCylinderSave();
				}
				else if (((GrabbableObject)storedCylinder).isHeld || (Object)(object)((GrabbableObject)storedCylinder).playerHeldBy != (Object)null || ((GrabbableObject)storedCylinder).isHeldByEnemy)
				{
					DetachCylinder(storedCylinder, saveItem: true);
				}
				else
				{
					ApplyCylinderTransform(storedCylinder);
				}
			}
			if (songStartPending && Time.time >= songStartTime)
			{
				songStartPending = false;
				TuningCylinderItem tuningCylinderItem = storedCylinder;
				if (resonatorPlaying && (Object)(object)tuningCylinderItem != (Object)null && HasStoredCylinder())
				{
					if (IsTemporalInstabilityShutdownActive())
					{
						StopResonatorAnimation();
					}
					else
					{
						tuningCylinderItem.PlaySong();
						scanNodeProperties.subText = tuningCylinderItem.SongDisplayName;
						audioReactionRunning = true;
					}
				}
			}
			if (animationSpeedChanging)
			{
				animationElapsedSeconds += Time.deltaTime;
				float num = ((animationSpeedTransitionSeconds <= 0f) ? 1f : Mathf.Clamp01(animationElapsedSeconds / animationSpeedTransitionSeconds));
				resonatorAnimator.speed = Mathf.Lerp(animationStartSpeed, animationTargetSpeed, num);
				if (num >= 1f)
				{
					animationSpeedChanging = false;
					if (stopAnimationWhenFinished)
					{
						resonatorAnimator.SetBool(animationBoolName, false);
						if (temporalInstabilityStopCoroutine == null)
						{
							((Collider)playingInteractCollider).enabled = true;
						}
						RefreshStartInteractTrigger();
					}
				}
			}
			if (!audioReactionRunning)
			{
				return;
			}
			TuningCylinderItem tuningCylinderItem2 = storedCylinder;
			if ((Object)(object)tuningCylinderItem2 == (Object)null)
			{
				StopAudioReaction();
				return;
			}
			AudioSource songAudioSource = tuningCylinderItem2.SongAudioSource;
			if (!songAudioSource.isPlaying)
			{
				StopAudioReaction();
				return;
			}
			if (IsTemporalInstabilityShutdownActive())
			{
				audioReactionRunning = false;
				CoroutineTools.Restart((MonoBehaviour)(object)this, ref temporalInstabilityStopCoroutine, StopForTemporalInstability(tuningCylinderItem2));
				return;
			}
			songAudioSource.GetOutputData(audioSamples, 0);
			float num2 = 0f;
			for (int i = 0; i < audioSamples.Length; i++)
			{
				num2 += Mathf.Abs(audioSamples[i]);
			}
			float num3 = Mathf.Clamp01(num2 / (float)audioSamples.Length * audioReactiveStrength);
			float num4 = Mathf.Lerp(minimumAudioReactiveScale, maximumAudioReactiveScale, num3);
			float num5 = 1f - Mathf.Exp((0f - Time.deltaTime) / Mathf.Max(0.001f, audioReactiveSmoothingSeconds));
			audioReactiveCurrentScale = Mathf.Lerp(audioReactiveCurrentScale, num4, num5);
			audioReactiveScaleTarget.localScale = audioReactiveBaseScale * audioReactiveCurrentScale;
		}

		public override void OnDestroy()
		{
			DawnSaveSync? obj = cylinderSync;
			if (obj != null)
			{
				obj.Disable();
			}
			((NetworkBehaviour)this).OnDestroy();
		}

		public void StartResonator()
		{
			if (HasStoredCylinder() && !resonatorPlaying && !IsTemporalInstabilityShutdownActive())
			{
				RequestStartResonatorRpc();
			}
		}

		[Rpc(/*Could not decode attribute arguments.*/)]
		private void RequestStartResonatorRpc()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Invalid comparison between Unknown and I4
			//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_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: 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_0085: 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)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1)
			{
				RpcAttributeParams val = new RpcAttributeParams
				{
					RequireOwnership = false
				};
				RpcParams val3 = default(RpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendRpc(4145759038u, val3, val, (SendTo)2, (RpcDelivery)0);
				((NetworkBehaviour)this).__endSendRpc(ref val2, 4145759038u, val3, val, (SendTo)2, (RpcDelivery)0);
			}
			if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 1)
			{
				((NetworkBehaviour)this).__rpc_exec_stage = (__RpcExecStage)0;
				if (HasStoredCylinder() && !resonatorPlaying && !IsTemporalInstabilityShutdownActive())
				{
					ConfirmStartResonatorRpc();
				}
			}
		}

		[Rpc(/*Could not decode attribute arguments.*/)]
		private void ConfirmStartResonatorRpc()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Invalid comparison between Unknown and I4
			//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_0051: 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_0064: 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_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1)
			{
				RpcAttributeParams val = default(RpcAttributeParams);
				RpcParams val3 = default(RpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendRpc(858130537u, val3, val, (SendTo)7, (RpcDelivery)0);
				((NetworkBehaviour)this).__endSendRpc(ref val2, 858130537u, val3, val, (SendTo)7, (RpcDelivery)0);
			}
			if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 1)
			{
				((NetworkBehaviour)this).__rpc_exec_stage = (__RpcExecStage)0;
				if (HasStoredCylinder() && !resonatorPlaying && !IsTemporalInstabilityShutdownActive())
				{
					resonatorPlaying = true;
					RefreshStartInteractTrigger();
					((Collider)playingInteractCollider).enabled = false;
					resonatorAnimator.SetBool(animationBoolName, true);
					AudioTools.PlayOneShot(resonatorAudioSource, resonatorStartedClip);
					songStartTime = Time.time + resonatorStartedClip.length;
					songStartPending = true;
					RampAnimatorSpeed(1f, stopAnimation: false);
				}
			}
		}

		public void PlaceObject(PlayerControllerB playerWhoTriggered)
		{
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			TuningCylinderItem tuningCylinderItem = default(TuningCylinderItem);
			if (playerWhoTriggered != null && playerWhoTriggered.isHoldingObject && !playerWhoTriggered.isGrabbingObjectAnimation && !((Object)(object)playerWhoTriggered.currentlyHeldObjectServer == (Object)null) && ((Component)playerWhoTriggered.currentlyHeldObjectServer).TryGetComponent<TuningCylinderItem>(ref tuningCylinderItem) && !HasStoredCylinder())
			{
				RequestPlaceRpc((int)playerWhoTriggered.playerClientId, new NetworkObjectReference(((NetworkBehaviour)tuningCylinderItem).NetworkObject));
			}
		}

		internal bool CanPlaceHeldTuningCylinder(PlayerControllerB player)
		{
			int result;
			if (!HasStoredCylinder() && player.isHoldingObject && !player.isGrabbingObjectAnimation)
			{
				GrabbableObject currentlyHeldObjectServer = player.currentlyHeldObjectServer;
				TuningCylinderItem tuningCylinderItem = default(TuningCylinderItem);
				result = ((currentlyHeldObjectServer != null && ((Component)currentlyHeldObjectServer).TryGetComponent<TuningCylinderItem>(ref tuningCylinderItem)) ? 1 : 0);
			}
			else
			{
				result = 0;
			}
			return (byte)result != 0;
		}

		internal bool TryGetDisabledHoverTip(PlayerControllerB player, InteractTrigger trigger, out string disabledHoverTip)
		{
			if ((Object)(object)trigger == (Object)(object)base.triggerScript && !CanPlaceHeldTuningCylinder(player))
			{
				disabledHoverTip = trigger.disabledHoverTip;
				return true;
			}
			disabledHoverTip = string.Empty;
			return false;
		}

		[Rpc(/*Could not decode attribute arguments.*/)]
		private void RequestPlaceRpc(int playerWhoTriggered, NetworkObjectReference cylinderReference)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: Invalid comparison between Unknown and I4
			//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_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: 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_008f: 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_00a9: 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_00db: 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)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1)
			{
				RpcAttributeParams val = new RpcAttributeParams
				{
					RequireOwnership = false
				};
				RpcParams val3 = default(RpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendRpc(2248419768u, val3, val, (SendTo)2, (RpcDelivery)0);
				BytePacker.WriteValueBitPacked(val2, playerWhoTriggered);
				((FastBufferWriter)(ref val2)).WriteValueSafe<NetworkObjectReference>(ref cylinderReference, default(ForNetworkSerializable));
				((NetworkBehaviour)this).__endSendRpc(ref val2, 2248419768u, val3, val, (SendTo)2, (RpcDelivery)0);
			}
			if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1)
			{
				return;
			}
			((NetworkBehaviour)this).__rpc_exec_stage = (__RpcExecStage)0;
			if (base.parentTo.IsSpawned && !HasStoredCylinder())
			{
				PlaceableShipObject componentInChildren = ((Component)base.parentTo).gameObject.GetComponentInChildren<PlaceableShipObject>();
				if (componentInChildren != null)
				{
					componentInChildren.lastTimeScrapWasPlaced = Time.realtimeSinceStartup;
				}
				ConfirmPlaceRpc(playerWhoTriggered, cylinderReference);
			}
		}

		[Rpc(/*Could not decode attribute arguments.*/)]
		private void ConfirmPlaceRpc(int playerId, NetworkObjectReference cylinderReference)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Invalid comparison between Unknown and I4
			//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_0051: 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_0064: 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_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: 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_00cd: 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_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_013c: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1)
			{
				RpcAttributeParams val = default(RpcAttributeParams);
				RpcParams val3 = default(RpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendRpc(3887734062u, val3, val, (SendTo)7, (RpcDelivery)0);
				BytePacker.WriteValueBitPacked(val2, playerId);
				((FastBufferWriter)(ref val2)).WriteValueSafe<NetworkObjectReference>(ref cylinderReference, default(ForNetworkSerializable));
				((NetworkBehaviour)this).__endSendRpc(ref val2, 3887734062u, val3, val, (SendTo)7, (RpcDelivery)0);
			}
			if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 1)
			{
				((NetworkBehaviour)this).__rpc_exec_stage = (__RpcExecStage)0;
				PlayerControllerB val4 = Utility.LocalPlayer();
				if ((Object)(object)val4 != (Object)null && (int)val4.playerClientId == playerId && val4.isHoldingObject && !val4.isGrabbingObjectAnimation && (Object)(object)val4.currentlyHeldObjectServer != (Object)null)
				{
					Vector3 val5 = ((Component)base.parentTo).transform.InverseTransformPoint(cylinderPlacement.position);
					val4.DiscardHeldObject(true, base.parentTo, val5, false);
				}
				pendingCylinderTimeout = Time.realtimeSinceStartup + 6f;
				NetworkRefs.WhenReady<TuningCylinderItem>((MonoBehaviour)(object)this, cylinderReference, (Action<TuningCylinderItem>)delegate(TuningCylinderItem cylinder)
				{
					pendingCylinder = cylinder;
				}, 6f, 0);
			}
		}

		private void AttachCylinder(TuningCylinderItem cylinder, bool saveItem, bool playPlacedSound)
		{
			storedCylinder = cylinder;
			cylinderAttached = true;
			pendingCylinder = null;
			cylinder.LoadSong();
			ApplyCylinderTransform(cylinder);
			scanNodeProperties.subText = string.Empty;
			((Collider)placementCollider).enabled = false;
			if (playPlacedSound)
			{
				AudioTools.PlayOneShot(resonatorAudioSource, cylinderPlacedClip);
			}
			RefreshStartInteractTrigger();
			if (saveItem && ((NetworkBehaviour)this).IsServer && cylinderSync != null)
			{
				string value = WriteStoredCylinderData();
				if (string.IsNullOrWhiteSpace(value))
				{
					ClearStoredCylinderSave();
					return;
				}
				cylinderSync.SaveAndPublish();
				Log.Debug("Resonator cylinder save updated");
			}
		}

		private void DetachCylinder(TuningCylinderItem cylinder, bool saveItem)
		{
			cylinder.StopSong();
			cylinder.UnloadSong();
			AudioTools.PlayOneShot(resonatorAudioSource, cylinderRemovedClip);
			StopTemporalInstabilityShutdown();
			StopResonatorAnimation();
			StopAudioReaction();
			scanNodeProperties.subText = string.Empty;
			if ((Object)(object)storedCylinder == (Object)(object)cylinder)
			{
				storedCylinder = null;
				cylinderAttached = false;
			}
			((Collider)placementCollider).enabled = true;
			RefreshStartInteractTrigger();
			if (saveItem)
			{
				ClearStoredCylinderSave();
			}
		}

		private string WriteStoredCylinderData()
		{
			if (!HasStoredCylinder())
			{
				return string.Empty;
			}
			return ((object)FindItems.DawnKey((GrabbableObject)(object)storedCylinder))?.ToString() ?? string.Empty;
		}

		private void RestoreStoredCylinder(string rawItemKey)
		{
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			if (HasStoredCylinder() || string.IsNullOrWhiteSpace(rawItemKey))
			{
				return;
			}
			NamespacedKey val = default(NamespacedKey);
			if (!NamespacedKey.TryParse(rawItemKey, ref val))
			{
				if (((NetworkBehaviour)this).IsServer)
				{
					ClearStoredCylinderSave();
				}
				Log.Warn("Resonator cylinder save data could not be read");
				return;
			}
			NamespacedKey<DawnItemInfo> val2 = val.AsTyped<DawnItemInfo>();
			GrabbableObject val3 = FindItems.ClosestTo(val2, cylinderPlacement.position, 12f, (Func<GrabbableObject, bool>)((GrabbableObject item) => item is TuningCylinderItem && !item.isHeld && (Object)(object)item.playerHeldBy == (Object)null && !item.isHeldByEnemy));
			if (!(val3 is TuningCylinderItem cylinder))
			{
				if (((NetworkBehaviour)this).IsServer)
				{
					ClearStoredCylinderSave();
				}
			}
			else
			{
				AttachCylinder(cylinder, saveItem: false, playPlacedSound: false);
				Log.Debug("Resonator cylinder restored");
			}
		}

		private void ClearStoredCylinderSave()
		{
			if (((NetworkBehaviour)this).IsServer && cylinderSync != null)
			{
				cylinderSync.Remove();
				cylinderSync.Publish();
				Log.Debug("Resonator cylinder save cleared");
			}
		}

		private bool HasStoredCylinder()
		{
			int result;
			if (cylinderAttached)
			{
				TuningCylinderItem tuningCylinderItem = storedCylinder;
				if (tuningCylinderItem != null && !((GrabbableObject)tuningCylinderItem).isHeld && (Object)(object)((GrabbableObject)storedCylinder).playerHeldBy == (Object)null)
				{
					result = ((!((GrabbableObject)storedCylinder).isHeldByEnemy) ? 1 : 0);
					goto IL_0044;
				}
			}
			result = 0;
			goto IL_0044;
			IL_0044:
			return (byte)result != 0;
		}

		private void RefreshStartInteractTrigger()
		{
			bool flag = HasStoredCylinder();
			bool flag2 = IsTemporalInstabilityShutdownActive();
			bool flag3 = flag && !resonatorPlaying && !flag2;
			resonatorStartInteractTrigger.interactable = flag3;
			if (!flag3)
			{
				resonatorStartInteractTrigger.disabledHoverTip = ((!flag) ? "[No Tuning Cylinder inserted]" : (resonatorPlaying ? "[Resonator already active]" : (flag2 ? "[Temporal instability too high]" : "[No Tuning Cylinder inserted]")));
			}
		}

		private void ApplyCylinderTransform(TuningCylinderItem cylinder)
		{
			//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_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			Vector3 val = ((Component)base.parentTo).transform.InverseTransformPoint(cylinderPlacement.position);
			Quaternion val2 = Quaternion.Inverse(((Component)base.parentTo).transform.rotation) * cylinderPlacement.rotation;
			Vector3 eulerAngles = ((Quaternion)(ref val2)).eulerAngles;
			eulerAngles.x = 0f;
			GrabbablePlacement.PlaceLocal((GrabbableObject)(object)cylinder, ((Component)base.parentTo).transform, val, Quaternion.Euler(eulerAngles));
		}

		private void StopResonatorAnimation()
		{
			resonatorPlaying = false;
			songStartPending = false;
			RampAnimatorSpeed(0f, stopAnimation: true);
		}

		private void RampAnimatorSpeed(float targetSpeed, bool stopAnimation)
		{
			animationStartSpeed = resonatorAnimator.speed;
			animationTargetSpeed = targetSpeed;
			animationElapsedSeconds = 0f;
			animationSpeedChanging = true;
			stopAnimationWhenFinished = stopAnimation;
		}

		private IEnumerator StopForTemporalInstability(TuningCylinderItem cylinder)
		{
			StopResonatorAnimation();
			scanNodeProperties.subText = string.Empty;
			yield return cylinder.StopSong(temporalInstabilityStopSeconds);
			StopAudioReaction();
			((Collider)playingInteractCollider).enabled = true;
			temporalInstabilityStopCoroutine = null;
		}

		private void StopTemporalInstabilityShutdown()
		{
			if (temporalInstabilityStopCoroutine != null)
			{
				((MonoBehaviour)this).StopCoroutine(temporalInstabilityStopCoroutine);
				temporalInstabilityStopCoroutine = null;
			}
		}

		private bool IsTemporalInstabilityShutdownActive()
		{
			float temporalInstabilityLevel;
			return TemporalInstabilityAPI.TryGetServerInstabilityLevel(out temporalInstabilityLevel) && temporalInstabilityLevel >= temporalInstabilityStopThreshold;
		}

		private void StopAudioReaction()
		{
			//IL_000f: 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)
			audioReactionRunning = false;
			audioReactiveScaleTarget.localScale = audioReactiveBaseScale * minimumAudioReactiveScale;
			audioReactiveCurrentScale = minimumAudioReactiveScale;
		}

		protected override void __initializeVariables()
		{
			((PlaceableObjectsSurface)this).__initializeVariables();
		}

		protected override void __initializeRpcs()
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Expected O, but got Unknown
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Expected O, but got Unknown
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Expected O, but got Unknown
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Expected O, but got Unknown
			((NetworkBehaviour)this).__registerRpc(4145759038u, new RpcReceiveHandler(__rpc_handler_4145759038), "RequestStartResonatorRpc");
			((NetworkBehaviour)this).__registerRpc(858130537u, new RpcReceiveHandler(__rpc_handler_858130537), "ConfirmStartResonatorRpc");
			((NetworkBehaviour)this).__registerRpc(2248419768u, new RpcReceiveHandler(__rpc_handler_2248419768), "RequestPlaceRpc");
			((NetworkBehaviour)this).__registerRpc(3887734062u, new RpcReceiveHandler(__rpc_handler_3887734062), "ConfirmPlaceRpc");
			((PlaceableObjectsSurface)this).__initializeRpcs();
		}

		private static void __rpc_handler_4145759038(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0029: 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)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				target.__rpc_exec_stage = (__RpcExecStage)1;
				((ResonatorSurface)(object)target).RequestStartResonatorRpc();
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_858130537(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0029: 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)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				target.__rpc_exec_stage = (__RpcExecStage)1;
				((ResonatorSurface)(object)target).ConfirmStartResonatorRpc();
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_2248419768(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0023: 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_0042: 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_0060: 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)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				int playerWhoTriggered = default(int);
				ByteUnpacker.ReadValueBitPacked(reader, ref playerWhoTriggered);
				NetworkObjectReference cylinderReference = default(NetworkObjectReference);
				((FastBufferReader)(ref reader)).ReadValueSafe<NetworkObjectReference>(ref cylinderReference, default(ForNetworkSerializable));
				target.__rpc_exec_stage = (__RpcExecStage)1;
				((ResonatorSurface)(object)target).RequestPlaceRpc(playerWhoTriggered, cylinderReference);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_3887734062(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0023: 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_0042: 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_0060: 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)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				int playerId = default(int);
				ByteUnpacker.ReadValueBitPacked(reader, ref playerId);
				NetworkObjectReference cylinderReference = default(NetworkObjectReference);
				((FastBufferReader)(ref reader)).ReadValueSafe<NetworkObjectReference>(ref cylinderReference, default(ForNetworkSerializable));
				target.__rpc_exec_stage = (__RpcExecStage)1;
				((ResonatorSurface)(object)target).ConfirmPlaceRpc(playerId, cylinderReference);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		protected internal override string __getTypeName()
		{
			return "ResonatorSurface";
		}
	}
}
namespace TemporalStormWeather.TemporalStormManagers
{
	internal class AudioManager : MonoBehaviour, ITemporalInstability
	{
		[Serializable]
		private class InstabilityLoop
		{
			public AudioSource AudioSource = null;

			public AudioClip AudioClip = null;
		}

		private const float CrossfadeSeconds = 1f;

		private static readonly NamespacedKey<DawnEnemyInfo>[] locustEnemyKeys = new NamespacedKey<DawnEnemyInfo>[3]
		{
			Keys.LocustEnemyInfo,
			Keys.SawbladeLocustEnemyInfo,
			Keys.CorruptLocustEnemyInfo
		};

		[Header("Volume")]
		private float maximumAudioVolume;

		[SerializeField]
		[Range(0f, 100f)]
		private float volumeIncreaseStartInstability = 0f;

		[SerializeField]
		[Range(0f, 100f)]
		private float maximumVolumeInstability = 90f;

		[Header("Low Instability")]
		[SerializeField]
		private InstabilityLoop lowInstability = new InstabilityLoop();

		[Header("Medium Instability")]
		[SerializeField]
		private InstabilityLoop mediumInstability = new InstabilityLoop();

		[Header("High Instability")]
		[SerializeField]
		private InstabilityLoop highInstability = new InstabilityLoop();

		[Header("Extreme Instability")]
		[SerializeField]
		private InstabilityLoop extremeInstability = new InstabilityLoop();

		private Coroutine? crossfadeCoroutine;

		private InstabilityLoop[] instabilityLoops = Array.Empty<InstabilityLoop>();

		private InstabilityLoop? activeLoop;

		private float temporalInstabilityLevel;

		private bool weatherFlowActive;

		private bool audioSourcesReady;

		private void Awake()
		{
			instabilityLoops = new InstabilityLoop[4] { lowInstability, mediumInstability, highInstability, extremeInstability };
			audioSourcesReady = true;
			for (int i = 0; i < instabilityLoops.Length; i++)
			{
				InstabilityLoop instabilityLoop = instabilityLoops[i];
				if (!AudioUtils.Configure2DAudioSource(instabilityLoop.AudioSource, loop: true))
				{
					audioSourcesReady = false;
					continue;
				}
				AudioTools.SwapClip(instabilityLoop.AudioSource, instabilityLoop.AudioClip, false);
				AudioTools.Stop(instabilityLoop.AudioSource, true);
			}
		}

		private void OnEnable()
		{
			if (audioSourcesReady && Utility.ShouldRunWeatherLifecycle())
			{
				if (ConfigManager.MaxBackgroundAudioVolume != null)
				{
					maximumAudioVolume = ConfigManager.MaxBackgroundAudioVolume.Value;
				}
				AudioUtils.LoadAudioClips(WeatherAudioClips());
				weatherFlowActive = true;
				TemporalInstabilityAPI.Register(this, TemporalInstabilityFeed.Client);
			}
		}

		private void OnDisable()
		{
			if (!weatherFlowActive)
			{
				return;
			}
			weatherFlowActive = false;
			TemporalInstabilityAPI.Unregister(this);
			CoroutineTools.Stop((MonoBehaviour)(object)this, ref crossfadeCoroutine);
			for (int i = 0; i < instabilityLoops.Length; i++)
			{
				AudioSource audioSource = instabilityLoops[i].AudioSource;
				if (!((Object)(object)audioSource == (Object)null))
				{
					AudioTools.Stop(audioSource, true);
				}
			}
			activeLoop = null;
			temporalInstabilityLevel = 0f;
			AudioUtils.UnloadAudioClips(WeatherAudioClips());
		}

		public void SetTemporalInstabilityLevel(float value)
		{
			temporalInstabilityLevel = Utility.ClampInstability(value);
			InstabilityLoop instabilityLoop = ((temporalInstabilityLevel < 25f) ? lowInstability : ((temporalInstabilityLevel < 55f) ? mediumInstability : ((temporalInstabilityLevel < 90f) ? highInstability : extremeInstability)));
			if (instabilityLoop == activeLoop)
			{
				if (activeLoop != null && crossfadeCoroutine == null)
				{
					StopInactiveLoops(activeLoop);
					activeLoop.AudioSource.volume = (((Object)(object)activeLoop.AudioClip != (Object)null) ? WantedVolume() : 0f);
				}
			}
			else
			{
				StopInactiveLoops(activeLoop, instabilityLoop);
				CoroutineTools.Restart((MonoBehaviour)(object)this, ref crossfadeCoroutine, CrossfadeToLoop(instabilityLoop));
			}
		}

		private IEnumerator CrossfadeToLoop(InstabilityLoop newLoop)
		{
			InstabilityLoop previousLoop = activeLoop;
			activeLoop = newLoop;
			AudioSource previousSource = previousLoop?.AudioSource;
			AudioSource newSource = newLoop.AudioSource;
			float previousStartVolume = ((previousSource != null) ? previousSource.volume : 0f);
			float newStartVolume = ((newSource != null) ? newSource.volume : 0f);
			if ((Object)(object)newLoop.AudioClip != (Object)null && (Object)(object)newSource != (Object)null)
			{
				AudioTools.SwapClip(newSource, newLoop.AudioClip, false);
				if (!newSource.isPlaying)
				{
					newSource.time = 0f;
					newSource.Play();
				}
			}
			float elapsedSeconds = 0f;
			while (elapsedSeconds < 1f)
			{
				elapsedSeconds += Time.deltaTime;
				float fadeAmount = Mathf.SmoothStep(0f, 1f, elapsedSeconds / 1f);
				if (previousSource != null)
				{
					previousSource.volume = Mathf.Lerp(previousStartVolume, 0f, fadeAmount);
				}
				if (newSource != null)
				{
					newSource.volume = (((Object)(object)newLoop.AudioClip != (Object)null) ? Mathf.Lerp(newStartVolume, WantedVolume(), fadeAmount) : 0f);
				}
				yield return null;
			}
			if ((Object)(object)previousSource != (Object)null)
			{
				AudioTools.Stop(previousSource, true);
			}
			if (newSource != null)
			{
				newSource.volume = (((Object)(object)newLoop.AudioClip != (Object)null) ? WantedVolume() : 0f);
			}
			StopInactiveLoops(newLoop);
			crossfadeCoroutine = null;
		}

		private float WantedVolume()
		{
			if (temporalInstabilityLevel < volumeIncreaseStartInstability)
			{
				return 0f;
			}
			float fullLevel = Mathf.Max(volumeIncreaseStartInstability + 0.01f, maximumVolumeInstability);
			float num = Mathf.Lerp(0.1f, 1f, Utility.InstabilityProgress(temporalInstabilityLevel, volumeIncreaseStartInstability, fullLevel));
			return num * maximumAudioVolume;
		}

		private AudioClip?[] WeatherAudioClips()
		{
			WarningManager warningManager = Object.FindFirstObjectByType<WarningManager>((FindObjectsInactive)1);
			ThunderlordAnimationEvents thunderlordAnimationEvents = Object.FindFirstObjectByType<ThunderlordAnimationEvents>((FindObjectsInactive)1);
			List<AudioClip> list = new List<AudioClip>();
			list.Add(lowInstability.AudioClip);
			list.Add(mediumInstability.AudioClip);
			list.Add(highInstability.AudioClip);
			list.Add(extremeInstability.AudioClip);
			list.AddRange(TemporalStormAmbience.GetAudioClips());
			list.AddRange(warningManager?.AudioClips ?? Array.Empty<AudioClip>());
			list.AddRange(thunderlordAnimationEvents?.AudioClips ?? Array.Empty<AudioClip>());
			list.AddRange(RiftAudioClips());
			list.AddRange(LocustAudioClips());
			return list.ToArray();
		}

		private static AudioClip?[] RiftAudioClips()
		{
			DawnMapObjectInfo val = default(DawnMapObjectInfo);
			if (!((Registry<DawnMapObjectInfo>)(object)LethalContent.MapObjects).TryGetValue(Keys.TemporalRiftMapObject, ref val))
			{
				return Array.Empty<AudioClip>();
			}
			DawnInsideMapObjectInfo insideInfo = val.InsideInfo;
			GameObject riftPrefab = (((Object)(object)((insideInfo != null) ? insideInfo.IndoorMapHazardType : null) != (Object)null) ? val.InsideInfo.IndoorMapHazardType.prefabToSpawn : null);
			DawnOutsideMapObjectInfo outsideInfo = val.OutsideInfo;
			GameObject riftPrefab2 = (((Object)(object)((outsideInfo != null) ? outsideInfo.SpawnableOutsideObject : null) != (Object)null) ? val.OutsideInfo.SpawnableOutsideObject.prefabToSpawn : null);
			AudioClip[] array = RiftAudioClips(riftPrefab);
			AudioClip[] array2 = RiftAudioClips(riftPrefab2);
			int num = 0;
			AudioClip[] array3 = (AudioClip[])(object)new AudioClip[array.Length + array2.Length];
			ReadOnlySpan<AudioClip> readOnlySpan = new ReadOnlySpan<AudioClip>(array);
			readOnlySpan.CopyTo(new Span<AudioClip>(array3).Slice(num, readOnlySpan.Length));
			num += readOnlySpan.Length;
			ReadOnlySpan<AudioClip> readOnlySpan2 = new ReadOnlySpan<AudioClip>(array2);
			readOnlySpan2.CopyTo(new Span<AudioClip>(array3).Slice(num, readOnlySpan2.Length));
			num += readOnlySpan2.Length;
			return array3;
		}

		private static AudioClip?[] RiftAudioClips(GameObject? riftPrefab)
		{
			return ((riftPrefab != null) ? riftPrefab.GetComponentInChildren<TemporalRift>(true) : null)?.AudioClips ?? Array.Empty<AudioClip>();
		}

		private static AudioClip?[] LocustAudioClips()
		{
			AudioClip[] array = LocustAudioClips(locustEnemyKeys[0]);
			AudioClip[] array2 = LocustAudioClips(locustEnemyKeys[1]);
			AudioClip[] array3 = LocustAudioClips(locustEnemyKeys[2]);
			int num = 0;
			AudioClip[] array4 = (AudioClip[])(object)new AudioClip[array.Length + array2.Length + array3.Length];
			ReadOnlySpan<AudioClip> readOnlySpan = new ReadOnlySpan<AudioClip>(array);
			readOnlySpan.CopyTo(new Span<AudioClip>(array4).Slice(num, readOnlySpan.Length));
			num += readOnlySpan.Length;
			ReadOnlySpan<AudioClip> readOnlySpan2 = new ReadOnlySpan<AudioClip>(array2);
			readOnlySpan2.CopyTo(new Span<AudioClip>(array4).Slice(num, readOnlySpan2.Length));
			num += readOnlySpan2.Length;
			ReadOnlySpan<AudioClip> readOnlySpan3 = new ReadOnlySpan<AudioClip>(array3);
			readOnlySpan3.CopyTo(new Span<AudioClip>(array4).Slice(num, readOnlySpan3.Length));
			num += readOnlySpan3.Length;
			return array4;
		}

		private static AudioClip?[] LocustAudioClips(NamespacedKey<DawnEnemyInfo> enemyKey)
		{
			DawnEnemyInfo val = default(DawnEnemyInfo);
			if (!((Registry<DawnEnemyInfo>)(object)LethalContent.Enemies).TryGetValue(enemyKey, ref val) || (Object)(object)val.EnemyType?.enemyPrefab == (Object)null)
			{
				return Array.Empty<AudioClip>();
			}
			return val.EnemyType.enemyPrefab.GetComponent<LocustEnemyBase>()?.AudioClips ?? Array.Empty<AudioClip>();
		}

		private void StopInactiveLoops(InstabilityLoop? firstKeptLoop = null, InstabilityLoop? secondKeptLoop = null)
		{
			for (int i = 0; i < instabilityLoops.Length; i++)
			{
				InstabilityLoop instabilityLoop = instabilityLoops[i];
				if (instabilityLoop != firstKeptLoop && instabilityLoop != secondKeptLoop)
				{
					AudioSource audioSource = instabilityLoop.AudioSource;
					if (!((Object)(object)audioSource == (Object)null))
					{
						AudioTools.Stop(audioSource, true);
					}
				}
			}
		}
	}
	internal class ChatGlitchManager : ITemporalInstability
	{
		private const float ChatCorruptionStartInstability = 90f;

		private static readonly ChatGlitchManager Receiver = new ChatGlitchManager();

		private static bool registered;

		private static bool active;

		public void SetTemporalInstabilityLevel(float temporalInstabilityLevel)
		{
			bool flag = active;
			active = temporalInstabilityLevel >= 90f;
			if (active != flag)
			{
				Log.Debug(active ? "Chat corruption enabled" : "Chat corruption disabled");
			}
		}

		public static void CorruptMessage(ref string chatMessage)
		{
			if (!registered)
			{
				registered = true;
				TemporalInstabilityAPI.Register(Receiver, TemporalInstabilityFeed.Server);
				Log.Debug("Registered chat corruption receiver");
			}
			if (!active || string.IsNullOrEmpty(chatMessage))
			{
				return;
			}
			StringBuilder stringBuilder = new StringBuilder(chatMessage.Length * 2);
			for (int i = 0; i < chatMessage.Length; i++)
			{
				char c = chatMessage[i];
				if (!char.IsWhiteSpace(c))
				{
					stringBuilder.Append(c);
					stringBuilder.Append('□');
				}
				else
				{
					stringBuilder.Append(c);
				}
			}
			chatMessage = stringBuilder.ToString();
		}

		public static void Reset()
		{
			TemporalInstabilityAPI.Unregister(Receiver);
			registered = false;
			active = false;
		}

		[HarmonyPatch(typeof(HUDManager), "AddTextToChatOnServer")]
		[HarmonyPrefix]
		private static void Prefix(ref string chatMessage, int playerId)
		{
			if (playerId != -1)
			{
				CorruptMessage(ref chatMessage);
			}
		}
	}
	[Serializable]
	internal class TemporalStormItemContractSaveData
	{
		public List<TemporalStormSavedItem> Items = new List<TemporalStormSavedItem>();
	}
	[Serializable]
	internal class TemporalStormSavedItem
	{
		public string ItemNamespacedKey = string.Empty;

		public string ItemName = string.Empty;

		public Vector3 Position;

		public uint ItemSeed;

		public int ScrapValue;

		public float RusticLevel;

		public float VisualAmount;

		public int State;

		public uint TemporalRollsConsumed;

		public bool IncludeNonConductive;
	}
	public class DawnSaveManager : MonoBehaviour
	{
		private static DawnSaveSync? itemEffectSync;

		internal static void HookItemEffectSave()
		{
			if (itemEffectSync == null)
			{
				itemEffectSync = DawnSaveSync.Bind(Keys.ItemEffectsSaveData, (Func<string>)BuildCurrentSaveDataJson, (Action<string>)LoadSavedItems, true);
			}
		}

		private static string BuildCurrentSaveDataJson()
		{
			TemporalStormItemContractSaveData temporalStormItemContractSaveData = BuildCurrentSaveData();
			return (temporalStormItemContractSaveData.Items.Count == 0) ? string.Empty : JsonUtility.ToJson((object)temporalStormItemContractSaveData);
		}

		private static void LoadSavedItems(string rawSaveData)
		{
			LoadSavedItems(ReadItemContractSaveData(rawSaveData));
		}

		private static TemporalStormItemContractSaveData BuildCurrentSaveData()
		{
			TemporalStormItemContractSaveData temporalStormItemContractSaveData = new TemporalStormItemContractSaveData();
			ItemEffect[] array = Object.FindObjectsByType<ItemEffect>((FindObjectsInactive)0, (FindObjectsSortMode)0);
			foreach (ItemEffect itemEffect in array)
			{
				if (itemEffect.WriteDawnSaveEntry(out TemporalStormSavedItem savedItem))
				{
					temporalStormItemContractSaveData.Items.Add(savedItem);
				}
			}
			return temporalStormItemContractSaveData;
		}

		private static List<GrabbableObject> GatherRestoreCandidates()
		{
			return FindItems.Active