Decompiled source of CrowdControl HollowKnightSilksong v1.0.2

BepInEx/plugins/CrowdControl/ConnectorLib.JSON.dll

Decompiled 3 days ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Threading;
using Microsoft.CodeAnalysis;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("Warp World, Inc.")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("© 2025 Warp World, Inc.")]
[assembly: AssemblyFileVersion("5.0.9382.28006")]
[assembly: AssemblyInformationalVersion("5.0.9382.28006+ac392b277b065ac1b9257234480aab6526829f20")]
[assembly: AssemblyProduct("ConnectorLib.JSON")]
[assembly: AssemblyTitle("ConnectorLib.JSON")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("5.0.9382.28006")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class IsUnmanagedAttribute : Attribute
	{
	}
	[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 ConnectorLib.JSON
{
	internal class AnnotatedEnumConverter<T> : JsonConverter<T> where T : unmanaged, Enum
	{
		[AttributeUsage(AttributeTargets.Field)]
		public class JsonValueAttribute(string value) : Attribute()
		{
			public readonly string Value = value;
		}

		private static readonly Dictionary<T, JsonValueAttribute?> _attributes;

		static AnnotatedEnumConverter()
		{
			_attributes = ((T[])Enum.GetValues(typeof(T))).Select((T m) => new KeyValuePair<T, JsonValueAttribute>(m, GetAttributeOfType<JsonValueAttribute>(m))).ToDictionary();
		}

		private static T? GetAttributeOfType<T>(Enum enumVal) where T : Attribute
		{
			object[] array = enumVal.GetType().GetTypeInfo().DeclaredMembers.First((MemberInfo m) => string.Equals(m.Name, enumVal.ToString(), StringComparison.Ordinal)).GetCustomAttributes(typeof(T), inherit: false).ToArray();
			if (array.Length == 0)
			{
				return null;
			}
			return (T)array[0];
		}

		public override void WriteJson(JsonWriter writer, T value, JsonSerializer serializer)
		{
			JsonValueAttribute jsonValueAttribute = _attributes[value];
			if (jsonValueAttribute != null)
			{
				serializer.Serialize(writer, (object)jsonValueAttribute.Value);
			}
			else
			{
				serializer.Serialize(writer, (object)Enum.GetName(typeof(T), value));
			}
		}

		public override T ReadJson(JsonReader reader, Type objectType, T existingValue, bool hasExistingValue, JsonSerializer serializer)
		{
			string value = serializer.Deserialize<string>(reader);
			if (value == null)
			{
				return default(T);
			}
			KeyValuePair<T, JsonValueAttribute>? keyValuePair = _attributes.Cast<KeyValuePair<T, JsonValueAttribute>?>().FirstOrDefault((KeyValuePair<T, JsonValueAttribute>? a) => a?.Value?.Value?.Equals(value, StringComparison.OrdinalIgnoreCase) == true);
			if (keyValuePair.HasValue)
			{
				return keyValuePair.Value.Key;
			}
			if (Enum.TryParse<T>(value, ignoreCase: true, out var result))
			{
				return result;
			}
			return default(T);
		}
	}
	public class CamelCaseStringEnumConverter : JsonConverter<Enum>
	{
		public override void WriteJson(JsonWriter writer, Enum? value, JsonSerializer serializer)
		{
			if (value == null)
			{
				serializer.Serialize(writer, (object)null);
			}
			else
			{
				serializer.Serialize(writer, (object)value.ToCamelCase());
			}
		}

		public override Enum ReadJson(JsonReader reader, Type objectType, Enum? existingValue, bool hasExistingValue, JsonSerializer serializer)
		{
			return ReadJToken(JToken.ReadFrom(reader), objectType);
		}

		public static Enum ReadJToken(JToken reader, Type objectType)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Invalid comparison between Unknown and I4
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Invalid comparison between Unknown and I4
			JTokenType type = reader.Type;
			if ((int)type != 6)
			{
				if ((int)type == 8)
				{
					string text = Extensions.Value<string>((IEnumerable<JToken>)reader);
					if (text == null)
					{
						throw new SerializationException("The value was null.");
					}
					if (Enum.TryParse(objectType, text, ignoreCase: true, out object result))
					{
						return (Enum)result;
					}
					throw new SerializationException("The value was not recognized.");
				}
				throw new SerializationException("The value was not a string or number.");
			}
			int? num = Extensions.Value<int>((IEnumerable<JToken>)reader);
			if (!num.HasValue)
			{
				throw new SerializationException("The value was null.");
			}
			return (Enum)Enum.ToObject(objectType, num.Value);
		}
	}
	[Serializable]
	public class DataRequest : SimpleJSONRequest
	{
		public string key;

		public DataRequest(string key)
		{
			this.key = key;
			type = RequestType.DataRequest;
		}
	}
	[Serializable]
	public class DataResponse : SimpleJSONResponse
	{
		public string key;

		public JToken? value;

		public EffectStatus status;

		public long timeRemaining;

		public string? message;

		[JsonConstructor]
		public DataResponse(string key, EffectStatus status, object? value = null, long timeRemaining = 0L, string? message = null)
		{
			this.key = key;
			this.value = value.IfNotNull((Func<object, JToken?>)JToken.FromObject);
			this.status = status;
			this.timeRemaining = timeRemaining;
			this.message = message;
			type = ResponseType.DataResponse;
		}

		public static DataResponse SuccessIfDefined(string key, object? value, string failMessage = "")
		{
			if (value == null)
			{
				return Retry(key, 0L, failMessage);
			}
			if (value is string input && input.IsNullOrWhiteSpace())
			{
				return Retry(key, 0L, failMessage);
			}
			return Success(key, value);
		}

		public static DataResponse Success(string key, object? value)
		{
			return new DataResponse(key, EffectStatus.Success, value, 0L);
		}

		public static DataResponse Success(string key, object? value, string? message)
		{
			return new DataResponse(key, EffectStatus.Success, value, 0L, message);
		}

		public static DataResponse Failure(string key)
		{
			return new DataResponse(key, EffectStatus.Failure, null, 0L);
		}

		public static DataResponse Failure(string key, string? message)
		{
			return new DataResponse(key, EffectStatus.Failure, null, 0L, message);
		}

		public static DataResponse Failure(string key, object? value, string? message = null)
		{
			return new DataResponse(key, EffectStatus.Failure, value, 0L, message);
		}

		public static DataResponse Retry(string key, long delay = 0L, string? message = null)
		{
			return new DataResponse(key, EffectStatus.Retry, null, delay, message);
		}
	}
	[Serializable]
	public class EffectRequest : SimpleJSONRequest
	{
		[Serializable]
		public class Target
		{
			public string? service;

			public string? id;

			public string? name;

			public string? avatar;
		}

		public string? code;

		public string? message;

		public JToken? parameters;

		public uint? quantity;

		public JArray? targets;

		public long? duration;

		public string? viewer;

		public JArray? viewers;

		public long? cost;

		public Guid? requestID;

		[JsonConverter(typeof(IEffectSourceDetails.Converter))]
		public IEffectSourceDetails? sourceDetails;

		public EffectRequest()
		{
			type = RequestType.Start;
		}
	}
	[Serializable]
	public class EffectResponse : SimpleJSONResponse
	{
		private class MetadataConverter : JsonConverter<Dictionary<string, DataResponse>?>
		{
			public override void WriteJson(JsonWriter writer, Dictionary<string, DataResponse>? value, JsonSerializer serializer)
			{
				//IL_000c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0012: Expected O, but got Unknown
				if (value == null)
				{
					serializer.Serialize(writer, (object)null);
					return;
				}
				JObject val = new JObject();
				foreach (KeyValuePair<string, DataResponse> item in value)
				{
					JObject val2 = JObject.FromObject((object)item.Value);
					val2.Remove("key");
					val[item.Key] = (JToken)(object)val2;
				}
				serializer.Serialize(writer, (object)val);
			}

			public override Dictionary<string, DataResponse>? ReadJson(JsonReader reader, Type objectType, Dictionary<string, DataResponse>? existingValue, bool hasExistingValue, JsonSerializer serializer)
			{
				//IL_0008: Unknown result type (might be due to invalid IL or missing references)
				//IL_000e: Expected O, but got Unknown
				//IL_0034: Unknown result type (might be due to invalid IL or missing references)
				//IL_003b: Expected O, but got Unknown
				JObject val = (JObject)serializer.Deserialize(reader);
				if (val == null)
				{
					return null;
				}
				Dictionary<string, DataResponse> dictionary = new Dictionary<string, DataResponse>();
				foreach (JProperty item in val.Properties())
				{
					JObject val2 = (JObject)item.Value;
					val2["key"] = JToken.op_Implicit(item.Name);
					dictionary.Add(item.Name, ((JToken)val2).ToObject<DataResponse>());
				}
				return dictionary;
			}
		}

		public EffectStatus status;

		public string? message;

		public StandardErrors messageID;

		public long timeRemaining;

		[JsonConverter(typeof(MetadataConverter))]
		public Dictionary<string, DataResponse>? metadata;

		public EffectResponse()
		{
		}

		public EffectResponse(uint id, EffectStatus status)
			: this(id, status, 0L, null)
		{
		}

		public EffectResponse(uint id, EffectStatus status, StandardErrors messageID)
			: this(id, status, 0L, messageID)
		{
		}

		public EffectResponse(uint id, EffectStatus status, string? message)
			: this(id, status, 0L, message)
		{
		}

		public EffectResponse(uint id, EffectStatus status, TimeSpan timeRemaining)
			: this(id, status, checked((long)timeRemaining.TotalMilliseconds), null)
		{
		}

		public EffectResponse(uint id, EffectStatus status, TimeSpan timeRemaining, StandardErrors messageID)
			: this(id, status, checked((long)timeRemaining.TotalMilliseconds), messageID)
		{
		}

		public EffectResponse(uint id, EffectStatus status, TimeSpan timeRemaining, string? message)
			: this(id, status, checked((long)timeRemaining.TotalMilliseconds), message)
		{
		}

		public EffectResponse(uint id, EffectStatus status, long timeRemaining)
			: this(id, status, timeRemaining, null)
		{
		}

		public EffectResponse(uint id, EffectStatus status, long timeRemaining, StandardErrors messageID)
			: this(id, status, timeRemaining)
		{
			this.messageID = messageID;
		}

		[JsonConstructor]
		public EffectResponse(uint id, EffectStatus status, long timeRemaining, string? message)
		{
			base.id = id;
			this.status = status;
			this.timeRemaining = timeRemaining;
			this.message = message;
			type = ResponseType.EffectRequest;
		}

		public static EffectResponse Success(uint id, string? message = null)
		{
			return new EffectResponse(id, EffectStatus.Success, message);
		}

		public static EffectResponse Success(uint id, long delay, string? message = null)
		{
			return new EffectResponse(id, EffectStatus.Success, delay, message);
		}

		public static EffectResponse Success(uint id, TimeSpan delay, string? message = null)
		{
			return new EffectResponse(id, EffectStatus.Success, delay, message);
		}

		public static EffectResponse Failure(uint id, string? message = null)
		{
			return new EffectResponse(id, EffectStatus.Failure, message);
		}

		public static EffectResponse Failure(uint id, StandardErrors error)
		{
			return new EffectResponse(id, EffectStatus.Failure, error);
		}

		public static EffectResponse Unavailable(uint id, string? message = null)
		{
			return new EffectResponse(id, EffectStatus.Unavailable, message);
		}

		public static EffectResponse Unavailable(uint id, StandardErrors error)
		{
			return new EffectResponse(id, EffectStatus.Unavailable, error);
		}

		public static EffectResponse Retry(uint id, string? message = null)
		{
			return new EffectResponse(id, EffectStatus.Retry, 0L, message);
		}

		public static EffectResponse Retry(uint id, long delay, string? message = null)
		{
			return new EffectResponse(id, EffectStatus.Retry, delay, message);
		}

		public static EffectResponse Retry(uint id, TimeSpan delay, string? message = null)
		{
			return new EffectResponse(id, EffectStatus.Retry, delay, message);
		}

		public static EffectResponse Retry(uint id, StandardErrors error)
		{
			return new EffectResponse(id, EffectStatus.Retry, 0L, error);
		}

		public static EffectResponse Retry(uint id, long delay, StandardErrors error)
		{
			return new EffectResponse(id, EffectStatus.Retry, delay, error);
		}

		public static EffectResponse Retry(uint id, TimeSpan delay, StandardErrors error)
		{
			return new EffectResponse(id, EffectStatus.Retry, delay, error);
		}

		public static EffectResponse Paused(uint id, string? message = null)
		{
			return new EffectResponse(id, EffectStatus.Paused, 0L, message);
		}

		public static EffectResponse Paused(uint id, long timeRemaining, string? message = null)
		{
			return new EffectResponse(id, EffectStatus.Paused, timeRemaining, message);
		}

		public static EffectResponse Paused(uint id, TimeSpan timeRemaining, string? message = null)
		{
			return new EffectResponse(id, EffectStatus.Paused, timeRemaining, message);
		}

		public static EffectResponse Paused(uint id, StandardErrors error)
		{
			return new EffectResponse(id, EffectStatus.Paused, 0L, error);
		}

		public static EffectResponse Paused(uint id, long timeRemaining, StandardErrors error)
		{
			return new EffectResponse(id, EffectStatus.Paused, timeRemaining, error);
		}

		public static EffectResponse Paused(uint id, TimeSpan timeRemaining, StandardErrors error)
		{
			return new EffectResponse(id, EffectStatus.Paused, timeRemaining, error);
		}

		public static EffectResponse Resumed(uint id, string? message = null)
		{
			return new EffectResponse(id, EffectStatus.Resumed, 0L, message);
		}

		public static EffectResponse Resumed(uint id, long timeRemaining, string? message = null)
		{
			return new EffectResponse(id, EffectStatus.Resumed, timeRemaining, message);
		}

		public static EffectResponse Resumed(uint id, TimeSpan timeRemaining, string? message = null)
		{
			return new EffectResponse(id, EffectStatus.Resumed, timeRemaining, message);
		}

		public static EffectResponse Resumed(uint id, StandardErrors error)
		{
			return new EffectResponse(id, EffectStatus.Resumed, 0L, error);
		}

		public static EffectResponse Resumed(uint id, long timeRemaining, StandardErrors error)
		{
			return new EffectResponse(id, EffectStatus.Resumed, timeRemaining, error);
		}

		public static EffectResponse Resumed(uint id, TimeSpan timeRemaining, StandardErrors error)
		{
			return new EffectResponse(id, EffectStatus.Resumed, timeRemaining, error);
		}

		public static EffectResponse Finished(uint id, string? message = null)
		{
			return new EffectResponse(id, EffectStatus.Finished, 0L, message);
		}

		public static EffectResponse Finished(uint id, StandardErrors error)
		{
			return new EffectResponse(id, EffectStatus.Finished, 0L, error);
		}
	}
	public interface IEffectSourceDetails
	{
		public class Converter : JsonConverter<IEffectSourceDetails?>
		{
			public static readonly Converter Instance = new Converter();

			public override IEffectSourceDetails? ReadJson(JsonReader reader, Type objectType, IEffectSourceDetails? existingValue, bool hasExistingValue, JsonSerializer serializer)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_0008: Invalid comparison between Unknown and I4
				if ((int)reader.TokenType == 11)
				{
					return null;
				}
				JObject val = JObject.Load(reader);
				JToken obj = val["type"];
				return ((obj != null) ? Extensions.Value<string>((IEnumerable<JToken>)obj) : null) switch
				{
					"twitch-channel-reward" => ((JToken)val).ToObject<TwitchChannelRewardSourceDetails>(), 
					"stream-labs-donation" => ((JToken)val).ToObject<StreamLabsDonationSourceDetails>(), 
					"event-hype-train" => ((JToken)val).ToObject<HypeTrainSourceDetails>(), 
					"tiktok-gift" => ((JToken)val).ToObject<TikTokGiftSourceDetails>(), 
					"tiktok-like" => ((JToken)val).ToObject<TikTokLikeSourceDetails>(), 
					"tiktok-follow" => ((JToken)val).ToObject<TikTokFollowSourceDetails>(), 
					"tiktok-share" => ((JToken)val).ToObject<TikTokShareSourceDetails>(), 
					"pulsoid-trigger" => ((JToken)val).ToObject<PulsoidTriggerSourceDetails>(), 
					"crowd-control-test" => ((JToken)val).ToObject<CrowdControlTestSourceDetails>(), 
					"crowd-control-chaos-mode" => ((JToken)val).ToObject<CrowdControlChaosModeSourceDetails>(), 
					"crowd-control-retry" => ((JToken)val).ToObject<CrowdControlRetrySourceDetails>(), 
					_ => null, 
				};
			}

			public override void WriteJson(JsonWriter writer, IEffectSourceDetails? value, JsonSerializer serializer)
			{
				serializer.Serialize(writer, (object)((value == null) ? null : JObject.FromObject((object)value)));
			}
		}

		[JsonProperty("type")]
		string Type { get; }
	}
	public class TwitchChannelRewardSourceDetails : IEffectSourceDetails
	{
		[JsonProperty("type")]
		public string Type => "twitch-channel-reward";

		[JsonProperty("rewardID")]
		public string RewardID { get; set; }

		[JsonProperty("redemptionID")]
		public string RedemptionID { get; set; }

		[JsonProperty("twitchID")]
		public string TwitchID { get; set; }

		[JsonProperty("name")]
		public string Name { get; set; }

		[JsonProperty("cost")]
		public int Cost { get; set; }
	}
	public class StreamLabsDonationSourceDetails : IEffectSourceDetails
	{
		[JsonProperty("type")]
		public string Type => "stream-labs-donation";

		[JsonProperty("donationID")]
		public string DonationID { get; set; }

		[JsonProperty("cost")]
		public string Cost { get; set; }

		[JsonProperty("currency")]
		public string Currency { get; set; }

		[JsonProperty("name")]
		public string? Name { get; set; }

		[JsonProperty("message")]
		public string? Message { get; set; }
	}
	public class HypeTrainSourceDetails : IEffectSourceDetails
	{
		public class Contribution
		{
			[JsonProperty("user_id")]
			public string UserID { get; set; }

			[JsonProperty("user_login")]
			public string UserLogin { get; set; }

			[JsonProperty("user_name")]
			public string UserName { get; set; }

			[JsonProperty("type")]
			public string Type { get; set; }

			[JsonProperty("total")]
			public int Total { get; set; }
		}

		[JsonProperty("type")]
		public string Type => "event-hype-train";

		[JsonProperty("total")]
		public int Total { get; set; }

		[JsonProperty("progress")]
		public int Progress { get; set; }

		[JsonProperty("goal")]
		public int Goal { get; set; }

		[JsonProperty("top_contributions")]
		public List<Contribution> TopContributions { get; set; }

		[JsonProperty("last_contribution")]
		public Contribution LastContribution { get; set; }

		[JsonProperty("level")]
		public int Level { get; set; }
	}
	public abstract class TikTokSourceDetails : IEffectSourceDetails
	{
		[JsonProperty("type")]
		public abstract string Type { get; }

		[JsonProperty("cost")]
		public int Cost { get; set; }

		[JsonProperty("name")]
		public string Name { get; set; }

		[JsonProperty("userID")]
		public string UserID { get; set; }
	}
	public class TikTokGiftSourceDetails : TikTokSourceDetails
	{
		[JsonProperty("type")]
		public override string Type => "tiktok-gift";

		[JsonProperty("giftID")]
		public int GiftID { get; set; }

		[JsonProperty("giftName")]
		public string GiftName { get; set; }

		[JsonProperty("transactionID")]
		public string? TransactionID { get; set; }
	}
	public class TikTokLikeSourceDetails : TikTokSourceDetails
	{
		[JsonProperty("type")]
		public override string Type => "tiktok-like";
	}
	public class TikTokFollowSourceDetails : TikTokSourceDetails
	{
		[JsonProperty("type")]
		public override string Type => "tiktok-follow";
	}
	public class TikTokShareSourceDetails : TikTokSourceDetails
	{
		[JsonProperty("type")]
		public override string Type => "tiktok-share";
	}
	public class PulsoidTriggerSourceDetails : IEffectSourceDetails
	{
		[JsonProperty("type")]
		public string Type => "pulsoid-trigger";

		[JsonProperty("heartRate")]
		public int HeartRate { get; set; }

		[JsonProperty("uuid")]
		public Guid Uuid { get; set; }

		[JsonProperty("triggerType")]
		public string TriggerType { get; set; }

		[JsonProperty("targetHeartRate")]
		public int TargetHeartRate { get; set; }

		[JsonProperty("holdTime")]
		public int HoldTime { get; set; }

		[JsonProperty("cooldown")]
		public int Cooldown { get; set; }
	}
	public class CrowdControlTestSourceDetails : IEffectSourceDetails
	{
		[JsonProperty("type")]
		public string Type => "crowd-control-test";
	}
	public class CrowdControlChaosModeSourceDetails : IEffectSourceDetails
	{
		[JsonProperty("type")]
		public string Type => "crowd-control-chaos-mode";
	}
	public class CrowdControlRetrySourceDetails : IEffectSourceDetails
	{
		[JsonProperty("type")]
		public string Type => "crowd-control-retry";
	}
	[JsonConverter(typeof(CamelCaseStringEnumConverter))]
	public enum EffectStatus
	{
		Success = 0,
		Failure = 1,
		Unavailable = 2,
		Retry = 3,
		Queue = 4,
		Running = 5,
		Paused = 6,
		Resumed = 7,
		Finished = 8,
		Wait = 9,
		RemoteScheduled = 10,
		Visible = 128,
		NotVisible = 129,
		Selectable = 130,
		NotSelectable = 131,
		Reserved0 = 160,
		NotReady = 255
	}
	[Serializable]
	public class EffectUpdate : SimpleJSONResponse
	{
		[JsonConverter(typeof(CamelCaseStringEnumConverter))]
		public enum IdentifierType
		{
			Effect,
			Group,
			Category
		}

		[Obsolete("This field is deprecated. Please use the ids field instead.")]
		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public string? code;

		[JsonProperty(/*Could not decode attribute arguments.*/)]
		public string[]? ids;

		public IdentifierType idType;

		public EffectStatus status;

		public string? message;

		public EffectUpdate()
		{
		}

		public EffectUpdate(string code, EffectStatus status, string? message = null)
		{
			ids = new string[1] { code };
			idType = IdentifierType.Effect;
			this.status = status;
			this.message = message;
			type = ResponseType.EffectStatus;
		}

		public EffectUpdate(string[] ids, EffectStatus status, string? message = null)
		{
			this.ids = ids;
			idType = IdentifierType.Effect;
			this.status = status;
			this.message = message;
			type = ResponseType.EffectStatus;
		}

		public EffectUpdate(IEnumerable<string> ids, EffectStatus status, string? message = null)
		{
			this.ids = ids.ToArray();
			idType = IdentifierType.Effect;
			this.status = status;
			this.message = message;
			type = ResponseType.EffectStatus;
		}
	}
	[Serializable]
	public class EmptyRequest : SimpleJSONRequest
	{
	}
	[Serializable]
	public class EmptyResponse : SimpleJSONResponse
	{
	}
	internal static class EnumEx
	{
		internal static string ToCamelCase(this Enum value)
		{
			return value.ToString("G").ToCamelCase();
		}
	}
	[JsonConverter(typeof(CamelCaseStringEnumConverter))]
	public enum GameState
	{
		Unknown = 0,
		Ready = 1,
		Error = -1,
		Unmodded = -2,
		BadGameSettings = -3,
		WrongVersion = -4,
		NotFocused = -5,
		Loading = -6,
		Paused = -7,
		WrongMode = -8,
		SafeArea = -9,
		UntimedArea = -10,
		Cutscene = -11,
		BadPlayerState = -12,
		Menu = -13,
		Map = -14,
		InCombat = -15,
		NotInCombat = -16,
		PipelineBusy = -128
	}
	[Serializable]
	public class GameUpdate : SimpleJSONResponse
	{
		public GameState state;

		public string? message;

		public GameUpdate(GameState state, string? message = null)
		{
			this.state = state;
			this.message = message;
			type = ResponseType.GameUpdate;
		}
	}
	[Serializable]
	public class GenericEventRequest : SimpleJSONRequest
	{
		[JsonProperty(PropertyName = "internal")]
		public bool @internal;

		public string eventType;

		public Dictionary<string, object>? data;

		public GenericEventRequest(string eventType)
		{
			type = RequestType.GenericEvent;
			this.eventType = eventType;
		}

		[JsonConstructor]
		public GenericEventRequest(string eventType, IEnumerable<KeyValuePair<string, object>>? data)
			: this(eventType)
		{
			this.data = ((data != null) ? data.ToDictionary() : null);
		}

		[JsonConstructor]
		public GenericEventRequest(string eventType, IEnumerable<KeyValuePair<string, object>>? data, bool @internal)
			: this(eventType, data)
		{
			this.@internal = @internal;
		}
	}
	[Serializable]
	public class GenericEventResponse : SimpleJSONResponse
	{
		[JsonProperty(PropertyName = "internal")]
		public bool @internal;

		public string eventType;

		public Dictionary<string, object>? data;

		public GenericEventResponse(string eventType)
		{
			type = ResponseType.GenericEvent;
			this.eventType = eventType;
		}

		public GenericEventResponse(string eventType, IEnumerable<KeyValuePair<string, object>>? data, bool @internal = false)
			: this(eventType)
		{
			this.data = ((data != null) ? data.ToDictionary() : null);
			this.@internal = @internal;
		}

		[JsonConstructor]
		public GenericEventResponse(string eventType, Dictionary<string, object>? data, [JsonProperty(PropertyName = "internal")] bool @internal)
			: this(eventType, data)
		{
			this.@internal = @internal;
		}
	}
	internal class HexColorConverter : JsonConverter<ParameterColorValue>
	{
		private static readonly Dictionary<char, byte> CHAR_LOOKUP = new Dictionary<char, byte>
		{
			{ '0', 0 },
			{ '1', 1 },
			{ '2', 2 },
			{ '3', 3 },
			{ '4', 4 },
			{ '5', 5 },
			{ '6', 6 },
			{ '7', 7 },
			{ '8', 8 },
			{ '9', 9 },
			{ 'A', 10 },
			{ 'B', 11 },
			{ 'C', 12 },
			{ 'D', 13 },
			{ 'E', 14 },
			{ 'F', 15 }
		};

		public override void WriteJson(JsonWriter writer, ParameterColorValue value, JsonSerializer serializer)
		{
			serializer.Serialize(writer, (object)string.Format("#{0}{1:X2}{2:X2}{3:X2}", (value.A != byte.MaxValue) ? value.A.ToString("X2") : string.Empty, value.R, value.G, value.B));
		}

		public override ParameterColorValue ReadJson(JsonReader reader, Type objectType, ParameterColorValue existingValue, bool hasExistingValue, JsonSerializer serializer)
		{
			if (TryParse(serializer.Deserialize<string>(reader), out var color))
			{
				return color;
			}
			throw new SerializationException("Unrecognized color code.");
		}

		public static bool TryParse(string? value, out ParameterColorValue color)
		{
			if (value == null)
			{
				color = default(ParameterColorValue);
				return false;
			}
			value = value.TrimStart('#');
			switch (value.Length)
			{
			case 6:
			{
				string[] array2 = value.Chop(2);
				byte result2;
				byte red3 = (byte)(byte.TryParse(array2[0], NumberStyles.AllowHexSpecifier, NumberFormatInfo.InvariantInfo, out result2) ? result2 : 0);
				byte green3 = (byte)(byte.TryParse(array2[1], NumberStyles.AllowHexSpecifier, NumberFormatInfo.InvariantInfo, out result2) ? result2 : 0);
				byte blue3 = (byte)(byte.TryParse(array2[2], NumberStyles.AllowHexSpecifier, NumberFormatInfo.InvariantInfo, out result2) ? result2 : 0);
				color = ParameterColorValue.FromArgb(red3, green3, blue3);
				return true;
			}
			case 8:
			{
				string[] array = value.Chop(2);
				byte result;
				byte alpha2 = (byte)(byte.TryParse(array[0], NumberStyles.AllowHexSpecifier, NumberFormatInfo.InvariantInfo, out result) ? result : 0);
				byte red2 = (byte)(byte.TryParse(array[1], NumberStyles.AllowHexSpecifier, NumberFormatInfo.InvariantInfo, out result) ? result : 0);
				byte green2 = (byte)(byte.TryParse(array[2], NumberStyles.AllowHexSpecifier, NumberFormatInfo.InvariantInfo, out result) ? result : 0);
				byte blue2 = (byte)(byte.TryParse(array[3], NumberStyles.AllowHexSpecifier, NumberFormatInfo.InvariantInfo, out result) ? result : 0);
				color = ParameterColorValue.FromArgb(alpha2, red2, green2, blue2);
				return true;
			}
			case 3:
			{
				byte value3;
				byte red4 = (byte)(CHAR_LOOKUP.TryGetValue(value[0], out value3) ? checked((byte)(value3 * 16)) : 0);
				byte green4 = (byte)(CHAR_LOOKUP.TryGetValue(value[1], out value3) ? checked((byte)(value3 * 16)) : 0);
				byte blue4 = (byte)(CHAR_LOOKUP.TryGetValue(value[2], out value3) ? checked((byte)(value3 * 16)) : 0);
				color = ParameterColorValue.FromArgb(red4, green4, blue4);
				return true;
			}
			case 4:
			{
				byte value2;
				byte alpha = (byte)(CHAR_LOOKUP.TryGetValue(value[0], out value2) ? checked((byte)(value2 * 16)) : 0);
				byte red = (byte)(CHAR_LOOKUP.TryGetValue(value[1], out value2) ? checked((byte)(value2 * 16)) : 0);
				byte green = (byte)(CHAR_LOOKUP.TryGetValue(value[2], out value2) ? checked((byte)(value2 * 16)) : 0);
				byte blue = (byte)(CHAR_LOOKUP.TryGetValue(value[3], out value2) ? checked((byte)(value2 * 16)) : 0);
				color = ParameterColorValue.FromArgb(alpha, red, green, blue);
				return true;
			}
			default:
				color = default(ParameterColorValue);
				return false;
			}
		}
	}
	internal static class IEnumerableEx
	{
		internal static Dictionary<TKey, TValue> ToDictionary<TKey, TValue>(this IEnumerable<KeyValuePair<TKey, TValue>> values) where TKey : notnull
		{
			Dictionary<TKey, TValue> dictionary = new Dictionary<TKey, TValue>();
			foreach (KeyValuePair<TKey, TValue> value in values)
			{
				dictionary.Add(value.Key, value.Value);
			}
			return dictionary;
		}
	}
	public interface IParameterValue
	{
		string ID { get; }

		string Name { get; }

		ParameterBase.ParameterType Type { get; }

		object? Value { get; }
	}
	[Serializable]
	public class LoginRequest : SimpleJSONRequest
	{
		public string? login;

		public string? password;
	}
	[Serializable]
	public class MessageRequest : SimpleJSONRequest
	{
		public string? message;
	}
	[Serializable]
	public class MessageResponse : SimpleJSONResponse
	{
		public string? message;
	}
	internal static class ObjectEx
	{
		internal static T2? IfNotNull<T1, T2>(this T1? value, Func<T1, T2?> selector) where T2 : class
		{
			if (value == null)
			{
				return null;
			}
			return selector(value);
		}
	}
	public abstract class ParameterBase
	{
		[JsonConverter(typeof(AnnotatedEnumConverter<ParameterType>))]
		public enum ParameterType
		{
			[AnnotatedEnumConverter<ParameterType>.JsonValue("options")]
			Options,
			[AnnotatedEnumConverter<ParameterType>.JsonValue("hex-color")]
			HexColor
		}

		[JsonIgnore]
		public readonly string ID;

		[JsonProperty(PropertyName = "title")]
		public readonly string Name;

		[JsonProperty(PropertyName = "type")]
		public readonly ParameterType Type;

		protected ParameterBase(string name, string id, ParameterType type)
		{
			ID = id;
			Name = name;
			Type = type;
		}
	}
	public class ParameterColor : ParameterBase, IParameterValue
	{
		[JsonProperty(PropertyName = "value")]
		[JsonConverter(typeof(HexColorConverter))]
		public ParameterColorValue Value;

		[JsonIgnore]
		string IParameterValue.ID => ID;

		[JsonIgnore]
		string IParameterValue.Name => Name;

		[JsonIgnore]
		ParameterType IParameterValue.Type => Type;

		[JsonIgnore]
		object? IParameterValue.Value => Value;

		[JsonConstructor]
		public ParameterColor(string name, string id, ParameterColorValue value)
			: base(name, id, ParameterType.HexColor)
		{
			Value = value;
		}

		[JsonConstructor]
		public ParameterColor(string name, string id, string value)
			: base(name, id, ParameterType.HexColor)
		{
			if (!HexColorConverter.TryParse(value, out Value))
			{
				throw new ArgumentException("Unknown color code.", "value");
			}
		}
	}
	[Serializable]
	[DebuggerDisplay("{NameAndARGBValue}")]
	[TypeForwardedFrom("System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
	public readonly struct ParameterColorValue : IEquatable<ParameterColorValue>
	{
		public static readonly ParameterColorValue Empty;

		private const short StateARGBValueValid = 2;

		private const short StateValueMask = 2;

		private const short StateNameValid = 8;

		private const long NotDefinedValue = 0L;

		internal const int ARGBAlphaShift = 24;

		internal const int ARGBRedShift = 16;

		internal const int ARGBGreenShift = 8;

		internal const int ARGBBlueShift = 0;

		internal const uint ARGBAlphaMask = 4278190080u;

		internal const uint ARGBRedMask = 16711680u;

		internal const uint ARGBGreenMask = 65280u;

		internal const uint ARGBBlueMask = 255u;

		private readonly long value;

		private readonly short state;

		public byte R => (byte)(Value >> 16);

		public byte G => (byte)(Value >> 8);

		public byte B => (byte)Value;

		public byte A => (byte)(Value >> 24);

		public bool IsEmpty => state == 0;

		private long Value
		{
			get
			{
				if ((state & 2) != 0)
				{
					return value;
				}
				return 0L;
			}
		}

		private ParameterColorValue(long value, short state)
		{
			this.value = value;
			this.state = state;
		}

		private static ParameterColorValue FromArgb(uint argb)
		{
			return new ParameterColorValue(argb, 2);
		}

		public static ParameterColorValue FromArgb(int argb)
		{
			return FromArgb((uint)argb);
		}

		public static ParameterColorValue FromArgb(byte alpha, byte red, byte green, byte blue)
		{
			return FromArgb((uint)((alpha << 24) | (red << 16) | (green << 8) | blue));
		}

		public static ParameterColorValue FromArgb(int alpha, ParameterColorValue baseColor)
		{
			return FromArgb(checked(((uint)alpha << 24) | ((uint)baseColor.Value & 0xFFFFFF)));
		}

		public static ParameterColorValue FromArgb(byte red, byte green, byte blue)
		{
			return FromArgb(byte.MaxValue, red, green, blue);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private void GetRgbValues(out byte r, out byte g, out byte b)
		{
			checked
			{
				uint num = (uint)Value;
				r = (byte)((num & 0xFF0000) >> 16);
				g = (byte)((num & 0xFF00) >> 8);
				b = (byte)(num & 0xFF);
			}
		}

		public float GetBrightness()
		{
			GetRgbValues(out var r, out var g, out var b);
			int num = Math.Min(Math.Min(r, g), b);
			return (float)checked(Math.Max(Math.Max(r, g), b) + num) / 510f;
		}

		public float GetHue()
		{
			GetRgbValues(out var r, out var g, out var b);
			if (r == g && g == b)
			{
				return 0f;
			}
			int num = Math.Min(Math.Min(r, g), b);
			int num2 = Math.Max(Math.Max(r, g), b);
			checked
			{
				float num3 = num2 - num;
				float num4 = ((r == num2) ? ((float)(g - b) / num3) : ((g != num2) ? ((float)(r - g) / num3 + 4f) : ((float)(b - r) / num3 + 2f)));
				num4 *= 60f;
				if (num4 < 0f)
				{
					num4 += 360f;
				}
				return num4;
			}
		}

		public float GetSaturation()
		{
			GetRgbValues(out var r, out var g, out var b);
			if (r == g && g == b)
			{
				return 0f;
			}
			int num = Math.Min(Math.Min(r, g), b);
			int num2 = Math.Max(Math.Max(r, g), b);
			checked
			{
				int num3 = num2 + num;
				if (num3 > 255)
				{
					num3 = 510 - num2 - num;
				}
				return (float)(num2 - num) / (float)num3;
			}
		}

		public int ToArgb()
		{
			return (int)Value;
		}

		public override string ToString()
		{
			if ((state & 2) != 0)
			{
				return "ParameterColorValue [A=" + A + ", R=" + R + ", G=" + G + ", B=" + B + "]";
			}
			return "ParameterColorValue [Empty]";
		}

		public static bool operator ==(ParameterColorValue left, ParameterColorValue right)
		{
			if (left.value == right.value)
			{
				return left.state == right.state;
			}
			return false;
		}

		public static bool operator !=(ParameterColorValue left, ParameterColorValue right)
		{
			return !(left == right);
		}

		public override bool Equals(object? obj)
		{
			if (obj is ParameterColorValue other)
			{
				return Equals(other);
			}
			return false;
		}

		public bool Equals(ParameterColorValue other)
		{
			return this == other;
		}

		public override int GetHashCode()
		{
			return (value.GetHashCode() * 397) ^ state.GetHashCode();
		}
	}
	public class ParameterValue<TValue> : ParameterBase, IParameterValue
	{
		[JsonProperty(PropertyName = "value")]
		public TValue? Value;

		[JsonIgnore]
		string IParameterValue.ID => ID;

		[JsonIgnore]
		string IParameterValue.Name => Name;

		[JsonIgnore]
		ParameterType IParameterValue.Type => Type;

		[JsonIgnore]
		object? IParameterValue.Value => Value;

		[JsonConstructor]
		public ParameterValue(string name, string id, TValue? value)
			: base(name, id, ParameterType.Options)
		{
			Value = value;
		}

		public override string ToString()
		{
			return Name;
		}
	}
	[Serializable]
	public class PlayerInfo : SimpleJSONRequest
	{
		public JObject? player;

		public PlayerInfo()
		{
			type = RequestType.PlayerInfo;
		}
	}
	[Serializable]
	[JsonConverter(typeof(Converter))]
	public class RequestParameters : IReadOnlyList<string>, IEnumerable<string>, IEnumerable, IReadOnlyCollection<string>, IReadOnlyDictionary<string, IParameterValue>, IEnumerable<KeyValuePair<string, IParameterValue>>, IReadOnlyCollection<KeyValuePair<string, IParameterValue>>
	{
		private class Converter : JsonConverter<RequestParameters>
		{
			public override void WriteJson(JsonWriter writer, RequestParameters? value, JsonSerializer serializer)
			{
				serializer.Serialize(writer, (object)value?._parameters);
			}

			public override RequestParameters? ReadJson(JsonReader reader, Type objectType, RequestParameters? existingValue, bool hasExistingValue, JsonSerializer serializer)
			{
				JObject obj = JObject.Load(reader);
				List<IParameterValue> list = new List<IParameterValue>();
				foreach (KeyValuePair<string, JToken> item in obj)
				{
					string key = item.Key;
					string name = Extensions.Value<string>((IEnumerable<JToken>)item.Value[(object)"name"]);
					switch (Extensions.Value<ParameterBase.ParameterType>((IEnumerable<JToken>)item.Value[(object)"type"]))
					{
					case ParameterBase.ParameterType.Options:
					{
						string value = Extensions.Value<string>((IEnumerable<JToken>)item.Value[(object)"value"]);
						list.Add(new ParameterValue<string>(name, key, value));
						break;
					}
					case ParameterBase.ParameterType.HexColor:
					{
						if (HexColorConverter.TryParse(Extensions.Value<string>((IEnumerable<JToken>)item.Value[(object)"value"]), out var color))
						{
							list.Add(new ParameterColor(name, key, color));
						}
						break;
					}
					default:
						throw new SerializationException();
					}
				}
				return new RequestParameters(list);
			}
		}

		private readonly Dictionary<string, IParameterValue> _parameters;

		private readonly List<string> _parameter_list;

		int IReadOnlyCollection<string>.Count => _parameters.Count;

		int IReadOnlyCollection<KeyValuePair<string, IParameterValue>>.Count => _parameters.Count;

		public string this[int index] => _parameter_list[index];

		public IParameterValue this[string key] => _parameters[key];

		public IEnumerable<string> Keys => _parameters.Keys;

		public IEnumerable<IParameterValue> Values => _parameters.Values;

		public int Count => _parameters.Count;

		private RequestParameters()
		{
			_parameters = new Dictionary<string, IParameterValue>();
			_parameter_list = new List<string>();
		}

		public RequestParameters(IEnumerable<IParameterValue> parameters)
		{
			parameters = parameters.ToArray();
			_parameters = parameters.ToDictionary((IParameterValue d) => d.ID);
			_parameter_list = parameters.Select((IParameterValue v) => v.Value.ToString()).ToList();
		}

		public RequestParameters(IEnumerable<KeyValuePair<string, IParameterValue>> parameters)
		{
			_parameters = parameters.ToDictionary();
			_parameter_list = _parameters.Values.Select((IParameterValue p) => p.Value.ToString()).ToList();
		}

		IEnumerator<KeyValuePair<string, IParameterValue>> IEnumerable<KeyValuePair<string, IParameterValue>>.GetEnumerator()
		{
			return _parameters.GetEnumerator();
		}

		IEnumerator<string> IEnumerable<string>.GetEnumerator()
		{
			return _parameters.Values.Select((IParameterValue v) => v.Value?.ToString()).GetEnumerator();
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return ((IEnumerable<string>)this).GetEnumerator();
		}

		public bool ContainsKey(string key)
		{
			return _parameters.ContainsKey(key);
		}

		public bool TryGetValue(string key, out IParameterValue value)
		{
			return _parameters.TryGetValue(key, out value);
		}

		public IEnumerable<string> Where(Func<string, bool> predicate)
		{
			return Enumerable.Where(this, predicate);
		}

		public IEnumerable<TResult> Select<TResult>(Func<string, TResult> selector)
		{
			return Enumerable.Select(this, selector);
		}

		public IEnumerable<TResult> SelectMany<TResult>(Func<string, IEnumerable<TResult>> selector)
		{
			return Enumerable.SelectMany(this, selector);
		}

		public IEnumerable<TResult> SelectMany<TResult>(Func<string, int, IEnumerable<TResult>> selector)
		{
			return Enumerable.SelectMany(this, selector);
		}

		public string First()
		{
			return this.First<string>();
		}

		public string First(Func<string, bool> predicate)
		{
			return Enumerable.First(this, predicate);
		}

		public string? FirstOrDefault()
		{
			return this.FirstOrDefault<string>();
		}

		public string FirstOrDefault(string defaultValue)
		{
			return this.FirstOrDefault<string>() ?? defaultValue;
		}

		public string? FirstOrDefault(Func<string, bool> predicate)
		{
			return Enumerable.FirstOrDefault(this, predicate);
		}

		public string FirstOrDefault(Func<string, bool> predicate, string defaultValue)
		{
			return Enumerable.FirstOrDefault(this, predicate) ?? defaultValue;
		}

		public bool Any()
		{
			return this.Any<string>();
		}

		public bool Any(Func<string, bool> predicate)
		{
			return Enumerable.Any(this, predicate);
		}
	}
	public enum RequestType : byte
	{
		[Obsolete("Use EffectTest instead.")]
		Test = 0,
		EffectTest = 0,
		[Obsolete("Use EffectStart instead.")]
		Start = 1,
		EffectStart = 1,
		[Obsolete("Use EffectStop instead.")]
		Stop = 2,
		EffectStop = 2,
		GenericEvent = 16,
		DataRequest = 32,
		RpcResponse = 208,
		PlayerInfo = 224,
		Login = 240,
		GameUpdate = 253,
		KeepAlive = byte.MaxValue
	}
	[JsonConverter(typeof(CamelCaseStringEnumConverter))]
	public enum ResponseType : byte
	{
		EffectRequest = 0,
		EffectStatus = 1,
		GenericEvent = 16,
		LoadEvent = 24,
		SaveEvent = 25,
		DataResponse = 32,
		RpcRequest = 208,
		Login = 240,
		LoginSuccess = 241,
		GameUpdate = 253,
		Disconnect = 254,
		KeepAlive = byte.MaxValue
	}
	[Serializable]
	public class RpcRequest : SimpleJSONResponse
	{
		public string? method;

		public object?[]? args;

		public RpcRequest()
		{
			type = ResponseType.RpcRequest;
		}
	}
	[Serializable]
	public class RpcResponse : SimpleJSONRequest
	{
		public object? value;

		public RpcResponse()
		{
			type = RequestType.RpcResponse;
		}
	}
	public abstract class SimpleJSONMessage
	{
		public static readonly JsonSerializerSettings JSON_SERIALIZER_SETTINGS = new JsonSerializerSettings
		{
			NullValueHandling = (NullValueHandling)1,
			MissingMemberHandling = (MissingMemberHandling)0,
			Formatting = (Formatting)0
		};

		public static readonly JsonSerializer JSON_SERIALIZER = new JsonSerializer
		{
			NullValueHandling = JSON_SERIALIZER_SETTINGS.NullValueHandling,
			MissingMemberHandling = JSON_SERIALIZER_SETTINGS.MissingMemberHandling,
			Formatting = JSON_SERIALIZER_SETTINGS.Formatting
		};

		private static int _next_id = 0;

		public static uint NextID
		{
			get
			{
				uint result;
				while ((result = (uint)Interlocked.Increment(ref _next_id)) == 0)
				{
				}
				return result;
			}
		}

		public abstract uint ID { get; }

		public abstract bool IsKeepAlive { get; }

		public string Serialize()
		{
			return JsonConvert.SerializeObject((object)this, JSON_SERIALIZER_SETTINGS);
		}
	}
	[Serializable]
	public class SimpleJSONRequest : SimpleJSONMessage
	{
		public uint id = SimpleJSONMessage.NextID;

		public RequestType type;

		[JsonIgnore]
		public override uint ID => id;

		[JsonIgnore]
		public override bool IsKeepAlive => type == RequestType.KeepAlive;

		public static bool TryParse(string json, [MaybeNullWhen(false)] out SimpleJSONRequest request)
		{
			return TryParse(JObject.Parse(json), out request);
		}

		public static bool TryParse(JObject j, [MaybeNullWhen(false)] out SimpleJSONRequest request)
		{
			try
			{
				JToken value = j.GetValue("type");
				RequestType requestType = ((value != null) ? ((RequestType)(object)CamelCaseStringEnumConverter.ReadJToken(value, typeof(RequestType))) : RequestType.Test);
				switch (requestType)
				{
				case RequestType.Stop:
					if (requestType != RequestType.Stop)
					{
						break;
					}
					request = ((JToken)j).ToObject<EffectRequest>(SimpleJSONMessage.JSON_SERIALIZER);
					return true;
				case RequestType.Test:
				case RequestType.Start:
					request = ((JToken)j).ToObject<EffectRequest>(SimpleJSONMessage.JSON_SERIALIZER);
					return true;
				case RequestType.DataRequest:
					request = ((JToken)j).ToObject<DataRequest>(SimpleJSONMessage.JSON_SERIALIZER);
					return true;
				case RequestType.RpcResponse:
					request = ((JToken)j).ToObject<RpcResponse>(SimpleJSONMessage.JSON_SERIALIZER);
					return true;
				case RequestType.PlayerInfo:
					request = ((JToken)j).ToObject<PlayerInfo>(SimpleJSONMessage.JSON_SERIALIZER);
					return true;
				case RequestType.Login:
					request = ((JToken)j).ToObject<MessageRequest>(SimpleJSONMessage.JSON_SERIALIZER);
					return true;
				case RequestType.GameUpdate:
					request = ((JToken)j).ToObject<EmptyRequest>(SimpleJSONMessage.JSON_SERIALIZER);
					return true;
				case RequestType.KeepAlive:
					request = ((JToken)j).ToObject<EmptyRequest>(SimpleJSONMessage.JSON_SERIALIZER);
					return true;
				}
			}
			catch
			{
			}
			request = null;
			return false;
		}
	}
	[Serializable]
	public class SimpleJSONResponse : SimpleJSONMessage
	{
		public uint id;

		public ResponseType type;

		[JsonIgnore]
		public override uint ID => id;

		[JsonIgnore]
		public override bool IsKeepAlive => type == ResponseType.KeepAlive;

		[JsonIgnore]
		public static SimpleJSONResponse KeepAlive { get; } = new EmptyResponse
		{
			type = ResponseType.KeepAlive
		};

		public static bool TryParse(string json, [MaybeNullWhen(false)] out SimpleJSONResponse response)
		{
			return TryParse(JObject.Parse(json), out response);
		}

		public static bool TryParse(JObject j, [MaybeNullWhen(false)] out SimpleJSONResponse response)
		{
			try
			{
				JToken value = j.GetValue("type");
				ResponseType responseType = ((value != null) ? ((ResponseType)(object)CamelCaseStringEnumConverter.ReadJToken(value, typeof(ResponseType))) : ResponseType.EffectRequest);
				switch (responseType)
				{
				case ResponseType.EffectStatus:
					if (responseType != ResponseType.EffectStatus)
					{
						break;
					}
					response = ((JToken)j).ToObject<EffectUpdate>(SimpleJSONMessage.JSON_SERIALIZER);
					return true;
				case ResponseType.EffectRequest:
					response = ((JToken)j).ToObject<EffectResponse>(SimpleJSONMessage.JSON_SERIALIZER);
					return true;
				case ResponseType.RpcRequest:
					response = ((JToken)j).ToObject<RpcRequest>(SimpleJSONMessage.JSON_SERIALIZER);
					return true;
				case ResponseType.GenericEvent:
					response = ((JToken)j).ToObject<GenericEventResponse>(SimpleJSONMessage.JSON_SERIALIZER);
					return true;
				case ResponseType.DataResponse:
					response = ((JToken)j).ToObject<DataResponse>(SimpleJSONMessage.JSON_SERIALIZER);
					return true;
				case ResponseType.Login:
					response = ((JToken)j).ToObject<EmptyResponse>(SimpleJSONMessage.JSON_SERIALIZER);
					return true;
				case ResponseType.LoginSuccess:
					response = ((JToken)j).ToObject<EmptyResponse>(SimpleJSONMessage.JSON_SERIALIZER);
					return true;
				case ResponseType.GameUpdate:
					response = ((JToken)j).ToObject<GameUpdate>(SimpleJSONMessage.JSON_SERIALIZER);
					return true;
				case ResponseType.Disconnect:
					response = ((JToken)j).ToObject<MessageResponse>(SimpleJSONMessage.JSON_SERIALIZER);
					return true;
				case ResponseType.KeepAlive:
					response = ((JToken)j).ToObject<EmptyResponse>(SimpleJSONMessage.JSON_SERIALIZER);
					return true;
				}
			}
			catch
			{
			}
			response = null;
			return false;
		}
	}
	[JsonConverter(typeof(CamelCaseStringEnumConverter))]
	public enum StandardErrors
	{
		Unknown = 0,
		ExceptionThrown = 1,
		BadRequest = 4096,
		[Obsolete("Use EffectUnknown instead.")]
		UnknownEffect = 4097,
		EffectUnknown = 4097,
		EffectDisabled = 4098,
		AlreadyFailed = 4099,
		CannotParseNumber = 4112,
		UnknownSelection = 4113,
		ConnectorError = 8192,
		ConnectorReadFailure = 8193,
		ConnectorWriteFailure = 8194,
		ConnectorNotConnected = 8195,
		ConnectorNotSupported = 8196,
		SettingsError = 12288,
		CooldownPerEffect = 12545,
		CooldownGlobal = 12546,
		RetryMaxTime = 12291,
		RetryMaxAttempts = 12292,
		NoSession = 20480,
		SessionEnding = 20481,
		BadGameState = 16384,
		GameObjectNotFound = 16640,
		PlayerNotFound = 16641,
		CharacterNotFound = 16642,
		EnemyNotFound = 16643,
		ObjectNotFound = 16644,
		PrerequisiteNotFound = 16645,
		ObjectStateError = 16896,
		AlreadyInState = 16897,
		AlreadyAcquired = 16898,
		AlreadyFinished = 16899,
		NoEmptyContainers = 16912,
		PartyFull = 16913,
		InvalidArea = 16928,
		InvalidTarget = 16929,
		NoValidTargets = 16930,
		SpawnNotAllowedHere = 16932,
		RangeError = 17152,
		AlreadyMinimum = 17153,
		AlreadyMaximum = 17154,
		EffectNotImplemented = 24576,
		PackResourceMissing = 24577,
		ConflictingEffectRunning = 32768,
		UnqueueablePending = 32769,
		EmulatorNotSupported = 28672,
		EmulatorInvalidSetting = 28673
	}
	internal static class StringEx
	{
		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool IsNullOrWhiteSpace(this string? input)
		{
			return string.IsNullOrWhiteSpace(input);
		}

		internal static string ToCamelCase(this string input)
		{
			bool flag = false;
			string text = "";
			checked
			{
				for (int i = 0; i < input.Length; i++)
				{
					if (char.IsUpper(input[i]))
					{
						if (flag)
						{
							text += input.Substring(i);
							break;
						}
						text += char.ToLower(input[i]);
					}
					else
					{
						flag = true;
						text = ((i <= 1 || !char.IsUpper(input[i - 1]) || !char.IsUpper(input[i - 2])) ? (text + input[i]) : (text.Substring(0, text.Length - 1) + char.ToUpper(input[i - 1]) + input[i]));
					}
				}
				return text;
			}
		}

		internal unsafe static string[] Chop(this string value, int chopLength)
		{
			int length = value.Length;
			char* ptr = stackalloc char[chopLength];
			string[] array = new string[length];
			for (int i = 0; i < length; i = checked(i + chopLength))
			{
				int j;
				for (j = 0; j < chopLength; j = checked(j + 1))
				{
					int num = checked(i + j);
					if (num >= length)
					{
						break;
					}
					*(char*)((byte*)ptr + checked(unchecked((nint)j) * (nint)2)) = value[num];
				}
				array[i / chopLength] = new string(ptr, 0, j);
			}
			return array;
		}
	}
}

BepInEx/plugins/CrowdControl/CrowdControl.dll

Decompiled 3 days ago
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using BepInEx;
using BepInEx.Logging;
using ConnectorLib.JSON;
using CrowdControl.Delegates.Effects;
using CrowdControl.Delegates.Metadata;
using CrowdControl.Harmony;
using CrowdControl.Utilities;
using GlobalEnums;
using GlobalSettings;
using HarmonyLib;
using HutongGames.PlayMaker;
using Microsoft.CodeAnalysis;
using Newtonsoft.Json;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class ParamCollectionAttribute : Attribute
	{
	}
	[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 CrowdControl
{
	[BepInPlugin("WarpWorld.CrowdControl", "Crowd Control", "1.0.1.0")]
	public class CrowdControlMod : BaseUnityPlugin
	{
		public class LabelInfo
		{
			public string text;

			public int opacity;

			public int slot;

			public float startTime;

			public string viewer;

			public string effectType;

			public LabelInfo(string t, string v = "", string et = "")
			{
				text = t;
				opacity = 255;
				slot = -1;
				startTime = Time.time;
				viewer = v;
				effectType = et;
			}
		}

		public const string MOD_GUID = "WarpWorld.CrowdControl";

		public const string MOD_NAME = "Crowd Control";

		public const string MOD_VERSION = "1.0.1.0";

		private readonly Harmony harmony = new Harmony("WarpWorld.CrowdControl");

		private const float GAME_STATUS_UPDATE_INTERVAL = 1f;

		private float m_gameStatusUpdateTimer;

		public static int preload = 0;

		public static GUIStyle style = new GUIStyle();

		public static bool init = false;

		public static bool enableDebugLogs = false;

		public static List<LabelInfo> labels = new List<LabelInfo>();

		public static Dictionary<string, int> geoCumulativeAmounts;

		public static Dictionary<string, int> silkCumulativeAmounts;

		public static Dictionary<string, int> shellShardCumulativeAmounts;

		public static float DeltaTime => Time.deltaTime;

		public ManualLogSource Logger => ((BaseUnityPlugin)this).Logger;

		internal static CrowdControlMod Instance { get; private set; } = null;

		public GameStateManager GameStateManager { get; private set; }

		public EffectLoader EffectLoader { get; private set; }

		public bool ClientConnected => Client.Connected;

		public NetworkClient Client { get; private set; }

		public Scheduler Scheduler { get; private set; }

		private void Awake()
		{
			Instance = this;
			PrefabLoader.bundlePrefix = "StreamingAssets/aa/StandaloneWindows64/scenes_scenes_scenes/";
			PrefabLoader.addPreload("crawler", "Tut_02", "MossBone Crawler");
			Logger.LogInfo((object)"Loaded WarpWorld.CrowdControl. Patching.");
			harmony.PatchAll();
			Logger.LogInfo((object)"Initializing Crowd Control");
			try
			{
				GameStateManager = new GameStateManager(this);
				Client = new NetworkClient(this);
				EffectLoader = new EffectLoader(this, Client);
				Scheduler = new Scheduler(this, Client);
			}
			catch (Exception arg)
			{
				Logger.LogError((object)$"Crowd Control Init Error: {arg}");
			}
			Logger.LogInfo((object)"Crowd Control Initialized");
		}

		private void FixedUpdate()
		{
			m_gameStatusUpdateTimer += DeltaTime;
			if (m_gameStatusUpdateTimer >= 1f)
			{
				GameStateManager.UpdateGameState();
				m_gameStatusUpdateTimer = 0f;
			}
			Scheduler?.Tick();
		}

		private void OnGUI()
		{
			Prefix();
		}

		public static void ShowMsg(string viewer, string msg, string effectType = "")
		{
			if (viewer == null || viewer.Length == 0)
			{
				viewer = "Crowd Control";
			}
			msg = msg.Replace("{viewer}", viewer);
			if (!string.IsNullOrEmpty(effectType))
			{
				for (int i = 0; i < labels.Count; i = checked(i + 1))
				{
					if (labels[i].viewer == viewer && labels[i].effectType == effectType)
					{
						labels[i].text = msg;
						labels[i].startTime = Time.time;
						labels[i].opacity = 255;
						return;
					}
				}
			}
			labels.Add(new LabelInfo(msg, viewer, effectType));
		}

		private static void ResetCumulativeAmount(string viewer, string effectType)
		{
			switch (effectType)
			{
			case "geo_effect":
				if (geoCumulativeAmounts != null && geoCumulativeAmounts.ContainsKey(viewer))
				{
					geoCumulativeAmounts[viewer] = 0;
				}
				break;
			case "silk_effect":
				if (silkCumulativeAmounts != null && silkCumulativeAmounts.ContainsKey(viewer))
				{
					silkCumulativeAmounts[viewer] = 0;
				}
				break;
			case "shellshard_effect":
				if (shellShardCumulativeAmounts != null && shellShardCumulativeAmounts.ContainsKey(viewer))
				{
					shellShardCumulativeAmounts[viewer] = 0;
				}
				break;
			}
		}

		public static void LogDebug(string message)
		{
			if (enableDebugLogs)
			{
				Debug.Log((object)message);
			}
		}

		public static void findSlot(LabelInfo info)
		{
			bool[] array = new bool[8] { true, true, true, true, true, true, true, true };
			checked
			{
				for (int i = 0; i < labels.Count; i++)
				{
					if (labels[i].slot >= 0)
					{
						array[labels[i].slot] = false;
					}
				}
				for (int j = 0; j < array.Length; j++)
				{
					if (array[j])
					{
						info.slot = j;
						break;
					}
				}
			}
		}

		public static void Prefix()
		{
			//IL_0192: Unknown result type (might be due to invalid IL or missing references)
			if (!init)
			{
				init = true;
				style.alignment = (TextAnchor)4;
				style.fontSize = 18;
				style.richText = true;
				style.fontStyle = (FontStyle)1;
			}
			float time = Time.time;
			checked
			{
				for (int num = labels.Count - 1; num >= 0; num--)
				{
					LabelInfo labelInfo = labels[num];
					float num2 = time - labelInfo.startTime;
					if (num2 >= 2f)
					{
						if (!string.IsNullOrEmpty(labelInfo.effectType))
						{
							ResetCumulativeAmount(labelInfo.viewer, labelInfo.effectType);
						}
						labels.RemoveAt(num);
					}
					else
					{
						if (labelInfo.slot == -1)
						{
							findSlot(labelInfo);
						}
						if (labelInfo.slot != -1)
						{
							int opacity = 255;
							if (num2 >= 1.5f)
							{
								float num3 = (num2 - 1.5f) / 0.5f;
								opacity = (int)(255f * (1f - num3));
							}
							if (opacity > 255)
							{
								opacity = 255;
							}
							if (opacity < 0)
							{
								opacity = 0;
							}
							string input = labelInfo.text.Replace("{op}", opacity.ToString("X2"));
							input = Regex.Replace(input, "<color=#([A-Fa-f0-9]{6})>", delegate(Match match)
							{
								string value = match.Groups[1].Value;
								int val = Convert.ToInt32(value.Substring(0, 2), 16);
								int val2 = Convert.ToInt32(value.Substring(2, 2), 16);
								int val3 = Convert.ToInt32(value.Substring(4, 2), 16);
								int num4 = Math.Max(val, Math.Max(val2, val3));
								if (num4 == 0)
								{
									num4 = 1;
								}
								int num5 = (int)(255.0 * (double)opacity * (double)num4 / 255.0);
								if (num5 > 255)
								{
									num5 = 255;
								}
								if (num5 < 0)
								{
									num5 = 0;
								}
								return "<color=#" + value + num5.ToString("X2") + ">";
							});
							input = "<i>" + input + "</i>";
							GUI.Label(new Rect(0f, (float)(20 + labelInfo.slot * 30), (float)Screen.width, 30f), input, style);
						}
					}
				}
			}
		}
	}
	public class DelimitedStreamReader(NetworkStream stream) : IDisposable
	{
		private readonly MemoryStream _memory_stream = new MemoryStream();

		~DelimitedStreamReader()
		{
			Dispose(disposing: false);
		}

		public void Dispose()
		{
			Dispose(disposing: true);
		}

		protected virtual void Dispose(bool disposing)
		{
			if (!disposing)
			{
				return;
			}
			try
			{
				_memory_stream.Dispose();
			}
			catch
			{
			}
		}

		public string ReadUntilNullTerminator()
		{
			int num;
			while ((num = stream.ReadByte()) != -1 && num != 0)
			{
				_memory_stream.WriteByte(checked((byte)num));
			}
			if (num == -1)
			{
				throw new EndOfStreamException("Reached end of stream without finding a null terminator.");
			}
			string result = Encoding.UTF8.GetString(_memory_stream.ToArray());
			_memory_stream.SetLength(0L);
			return result;
		}
	}
	public class GameStateManager(CrowdControlMod mod)
	{
		private enum EffectType
		{
			Enable,
			Disable
		}

		private readonly Dictionary<string, bool> _currentAbilities = new Dictionary<string, bool>();

		private readonly Dictionary<string, bool> _lastKnownAbilities = new Dictionary<string, bool>();

		private bool _abilitiesInitialized;

		private readonly Dictionary<string, (string ability, EffectType type)> _effectToAbilityMap = new Dictionary<string, (string, EffectType)>
		{
			{
				"disable_dash",
				("hasDash", EffectType.Disable)
			},
			{
				"disable_brolly",
				("hasBrolly", EffectType.Disable)
			},
			{
				"disable_walljump",
				("hasWalljump", EffectType.Disable)
			},
			{
				"disable_doublejump",
				("hasDoubleJump", EffectType.Disable)
			},
			{
				"disable_superjump",
				("hasSuperJump", EffectType.Disable)
			},
			{
				"disable_harpoondash",
				("hasHarpoonDash", EffectType.Disable)
			},
			{
				"disable_chargeslash",
				("hasChargeSlash", EffectType.Disable)
			},
			{
				"disable_silkspecial",
				("hasSilkSpecial", EffectType.Disable)
			},
			{
				"disable_needlethrow",
				("hasNeedleThrow", EffectType.Disable)
			},
			{
				"disable_threadsphere",
				("hasThreadSphere", EffectType.Disable)
			},
			{
				"disable_parry",
				("hasParry", EffectType.Disable)
			},
			{
				"disable_silkcharge",
				("hasSilkCharge", EffectType.Disable)
			},
			{
				"disable_silkbomb",
				("hasSilkBomb", EffectType.Disable)
			},
			{
				"disable_silkbossneedle",
				("hasSilkBossNeedle", EffectType.Disable)
			},
			{
				"disable_needolin",
				("hasNeedolin", EffectType.Disable)
			},
			{
				"give_dash",
				("hasDash", EffectType.Enable)
			},
			{
				"give_brolly",
				("hasBrolly", EffectType.Enable)
			},
			{
				"give_walljump",
				("hasWalljump", EffectType.Enable)
			},
			{
				"give_doublejump",
				("hasDoubleJump", EffectType.Enable)
			},
			{
				"give_superjump",
				("hasSuperJump", EffectType.Enable)
			},
			{
				"give_harpoondash",
				("hasHarpoonDash", EffectType.Enable)
			},
			{
				"give_chargeslash",
				("hasChargeSlash", EffectType.Enable)
			},
			{
				"give_silkspecial",
				("hasSilkSpecial", EffectType.Enable)
			},
			{
				"give_needlethrow",
				("hasNeedleThrow", EffectType.Enable)
			},
			{
				"give_threadsphere",
				("hasThreadSphere", EffectType.Enable)
			},
			{
				"give_parry",
				("hasParry", EffectType.Enable)
			},
			{
				"give_silkcharge",
				("hasSilkCharge", EffectType.Enable)
			},
			{
				"give_silkbomb",
				("hasSilkBomb", EffectType.Enable)
			},
			{
				"give_silkbossneedle",
				("hasSilkBossNeedle", EffectType.Enable)
			},
			{
				"give_needolin",
				("hasNeedolin", EffectType.Enable)
			}
		};

		private readonly HashSet<string> _activeEffects = new HashSet<string>();

		private GameState? _last_game_state;

		public bool IsActiveInConversation { get; set; }

		public bool IsReady(string code = "")
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Invalid comparison between Unknown and I4
			return (int)GetGameState() == 1;
		}

		public GameState GetGameState()
		{
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if (!Application.isFocused)
				{
					return (GameState)(-7);
				}
				if ((Object)(object)GameManager.instance == (Object)null)
				{
					return (GameState)(-1);
				}
				if ((Object)(object)HeroController.instance == (Object)null)
				{
					return (GameState)(-1);
				}
				if (GameStateChecker.IsTransitioning())
				{
					return (GameState)(-12);
				}
				if (GameStateChecker.IsDead() || GameStateChecker.IsHazardDeath() || GameStateChecker.IsHazardRespawning())
				{
					return (GameState)(-12);
				}
				if (GameStateChecker.IsPaused())
				{
					return (GameState)(-7);
				}
				if (GameStateChecker.IsInCutsceneMovement() || GameStateChecker.IsTriggerEventsPaused() || GameStateChecker.IsNeedolinPlayingMemory())
				{
					return (GameState)(-11);
				}
				if (GameStateChecker.IsNearBench() || GameStateChecker.IsAtBench())
				{
					return (GameState)(-9);
				}
				if (GameStateChecker.IsInWalkZone())
				{
					return (GameState)(-9);
				}
				return (GameState)1;
			}
			catch (Exception arg)
			{
				CrowdControlMod.Instance.Logger.LogError((object)$"GameStateManager Error: {arg}");
				return (GameState)(-1);
			}
		}

		private void UpdateAbilityTracking()
		{
			try
			{
				HeroController instance = HeroController.instance;
				if (instance?.playerData == null)
				{
					return;
				}
				PlayerData playerData = instance.playerData;
				Type type = ((object)playerData).GetType();
				string[] array = new string[15]
				{
					"hasDash", "hasBrolly", "hasWalljump", "hasDoubleJump", "hasSuperJump", "hasHarpoonDash", "hasChargeSlash", "hasSilkSpecial", "hasNeedleThrow", "hasThreadSphere",
					"hasParry", "hasSilkCharge", "hasSilkBomb", "hasSilkBossNeedle", "hasNeedolin"
				};
				foreach (string text in array)
				{
					FieldInfo field = type.GetField(text);
					if (field != null && field.GetValue(playerData) is bool value)
					{
						_currentAbilities[text] = value;
					}
				}
				bool flag = !_abilitiesInitialized;
				if (!flag)
				{
					foreach (KeyValuePair<string, bool> currentAbility in _currentAbilities)
					{
						if (!_lastKnownAbilities.TryGetValue(currentAbility.Key, out var value2) || value2 != currentAbility.Value)
						{
							flag = true;
							break;
						}
					}
				}
				if (!flag)
				{
					return;
				}
				UpdateEffectVisibility();
				_lastKnownAbilities.Clear();
				foreach (KeyValuePair<string, bool> currentAbility2 in _currentAbilities)
				{
					_lastKnownAbilities[currentAbility2.Key] = currentAbility2.Value;
				}
				_abilitiesInitialized = true;
			}
			catch (Exception arg)
			{
				CrowdControlMod.Instance.Logger.LogError((object)$"Ability tracking error: {arg}");
			}
		}

		private void UpdateEffectVisibility()
		{
			try
			{
				List<string> list = new List<string>();
				List<string> list2 = new List<string>();
				foreach (KeyValuePair<string, (string, EffectType)> item3 in _effectToAbilityMap)
				{
					string key = item3.Key;
					string item = item3.Value.Item1;
					EffectType item2 = item3.Value.Item2;
					bool value;
					bool flag = _currentAbilities.TryGetValue(item, out value) && value;
					bool flag2 = HasConflictingEffect(key, item);
					bool flag3 = false;
					switch (item2)
					{
					case EffectType.Disable:
						flag3 = flag && !flag2;
						break;
					case EffectType.Enable:
						flag3 = !flag && !flag2;
						break;
					}
					if (flag3)
					{
						list2.Add(key);
					}
					else
					{
						list.Add(key);
					}
				}
				if (list.Count > 0)
				{
					mod.Client.HideEffects(list.ToArray());
					CrowdControlMod.LogDebug(string.Format("Hidden {0} effects: {1}", list.Count, string.Join(", ", list)));
				}
				if (list2.Count > 0)
				{
					mod.Client.ShowEffects(list2.ToArray());
					CrowdControlMod.LogDebug(string.Format("Shown {0} effects: {1}", list2.Count, string.Join(", ", list2)));
				}
			}
			catch (Exception arg)
			{
				CrowdControlMod.Instance.Logger.LogError((object)$"Effect visibility update error: {arg}");
			}
		}

		private bool HasConflictingEffect(string currentEffectId, string ability)
		{
			string conflictingEffectId = GetConflictingEffectId(currentEffectId, ability);
			if (conflictingEffectId != null)
			{
				return _activeEffects.Contains(conflictingEffectId);
			}
			return false;
		}

		private string? GetConflictingEffectId(string effectId, string ability)
		{
			if (effectId.StartsWith("disable_"))
			{
				return effectId.Replace("disable_", "give_");
			}
			if (effectId.StartsWith("give_"))
			{
				return effectId.Replace("give_", "disable_");
			}
			return null;
		}

		public void OnEffectStarted(string effectId)
		{
			if (_effectToAbilityMap.ContainsKey(effectId))
			{
				_activeEffects.Add(effectId);
				CrowdControlMod.LogDebug($"Effect started: {effectId} (Active effects: {_activeEffects.Count})");
				UpdateEffectVisibility();
			}
		}

		public void OnEffectStopped(string effectId)
		{
			if (_effectToAbilityMap.ContainsKey(effectId))
			{
				_activeEffects.Remove(effectId);
				CrowdControlMod.LogDebug($"Effect stopped: {effectId} (Active effects: {_activeEffects.Count})");
				UpdateEffectVisibility();
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public bool UpdateGameState(bool force = false)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			UpdateAbilityTracking();
			return UpdateGameState(GetGameState(), force);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public bool UpdateGameState(GameState newState, bool force)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			return UpdateGameState(newState, null, force);
		}

		public bool UpdateGameState(GameState newState, string? message = null, bool force = false)
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Expected O, but got Unknown
			//IL_000a: 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_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			if (force || _last_game_state != (GameState?)newState)
			{
				_last_game_state = newState;
				return mod.Client.Send((SimpleJSONResponse?)new GameUpdate(newState, message));
			}
			return true;
		}
	}
	public class NetworkClient : IDisposable
	{
		public static readonly string CV_HOST = "127.0.0.1";

		public static readonly int CV_PORT = 51337;

		private TcpClient? m_client;

		private DelimitedStreamReader? m_streamReader;

		private readonly CrowdControlMod m_mod;

		private readonly CancellationTokenSource m_quitting = new CancellationTokenSource();

		private readonly Thread m_readLoop;

		private readonly Thread m_maintenanceLoop;

		private static readonly EmptyResponse KEEPALIVE = new EmptyResponse
		{
			type = (ResponseType)255
		};

		public bool Connected => m_client?.Connected ?? false;

		~NetworkClient()
		{
			Dispose(disposing: false);
		}

		public void Dispose()
		{
			Dispose(disposing: true);
		}

		protected virtual void Dispose(bool disposing)
		{
			try
			{
				m_client?.Dispose();
			}
			catch
			{
			}
			try
			{
				m_quitting.Cancel();
			}
			catch
			{
			}
			GC.SuppressFinalize(this);
		}

		public NetworkClient(CrowdControlMod mod)
		{
			m_mod = mod;
			(m_readLoop = new Thread(NetworkLoop)).Start();
			(m_maintenanceLoop = new Thread(MaintenanceLoop)).Start();
		}

		private void NetworkLoop()
		{
			Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
			while (!m_quitting.IsCancellationRequested)
			{
				CrowdControlMod.Instance.Logger.LogInfo((object)"Attempting to connect to Crowd Control");
				try
				{
					m_client = new TcpClient();
					m_client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, optionValue: true);
					m_client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, optionValue: true);
					if (m_client.BeginConnect(CV_HOST, CV_PORT, null, null).AsyncWaitHandle.WaitOne(2000, exitContext: true) && m_client.Connected)
					{
						ClientLoop();
					}
					else
					{
						CrowdControlMod.Instance.Logger.LogInfo((object)"Failed to connect to Crowd Control");
					}
				}
				catch (Exception ex)
				{
					CrowdControlMod.Instance.Logger.LogError((object)ex);
					CrowdControlMod.Instance.Logger.LogError((object)"Failed to connect to Crowd Control");
				}
				finally
				{
					try
					{
						m_client?.Close();
					}
					catch
					{
					}
				}
				Thread.Sleep(2000);
			}
		}

		private void MaintenanceLoop()
		{
			Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
			while (!m_quitting.IsCancellationRequested)
			{
				try
				{
					TcpClient? client = m_client;
					if (client != null && client.Connected)
					{
						KeepAlive();
					}
				}
				catch (Exception ex)
				{
					CrowdControlMod.Instance.Logger.LogError((object)ex);
				}
				Thread.Sleep(2000);
			}
		}

		private void ClientLoop()
		{
			m_streamReader = new DelimitedStreamReader(m_client.GetStream());
			CrowdControlMod.Instance.Logger.LogInfo((object)"Connected to Crowd Control");
			try
			{
				while (!m_quitting.IsCancellationRequested)
				{
					string text = m_streamReader.ReadUntilNullTerminator();
					OnMessage(text.Trim());
				}
			}
			catch (EndOfStreamException)
			{
				CrowdControlMod.Instance.Logger.LogInfo((object)"Disconnected from Crowd Control");
				m_client?.Close();
			}
			catch (Exception ex2)
			{
				CrowdControlMod.Instance.Logger.LogError((object)ex2);
				m_client?.Close();
			}
		}

		private void OnMessage(string message)
		{
			if (string.IsNullOrWhiteSpace(message))
			{
				return;
			}
			try
			{
				SimpleJSONRequest request = default(SimpleJSONRequest);
				if (SimpleJSONRequest.TryParse(RemoveSourceDetailsField(message), ref request))
				{
					m_mod.Scheduler.ProcessRequest(request);
				}
			}
			catch (Exception ex)
			{
				CrowdControlMod.Instance.Logger.LogError((object)ex);
			}
		}

		private string RemoveSourceDetailsField(string jsonMessage)
		{
			try
			{
				return Regex.Replace(Regex.Replace(jsonMessage, ",\\s*\"sourceDetails\"\\s*:\\s*\\{[^}]*\\}", "", RegexOptions.IgnoreCase), ",\\s*\"sourceDetails\"\\s*:\\s*null", "", RegexOptions.IgnoreCase);
			}
			catch
			{
				return jsonMessage;
			}
		}

		public bool Send(SimpleJSONResponse? response)
		{
			try
			{
				if (response == null)
				{
					return false;
				}
				if (!Connected)
				{
					return false;
				}
				byte[] bytes = Encoding.UTF8.GetBytes(((SimpleJSONMessage)response).Serialize());
				int num = 0;
				byte[] array = new byte[1 + bytes.Length];
				ReadOnlySpan<byte> readOnlySpan = new ReadOnlySpan<byte>(bytes);
				readOnlySpan.CopyTo(new Span<byte>(array).Slice(num, readOnlySpan.Length));
				num += readOnlySpan.Length;
				array[num] = 0;
				byte[] array2 = array;
				m_client.GetStream().Write(array2, 0, array2.Length);
				return true;
			}
			catch (Exception arg)
			{
				CrowdControlMod.Instance.Logger.LogError((object)$"Error sending a message to the Crowd Control client: {arg}");
				return false;
			}
		}

		public Task<bool> SendAsync(SimpleJSONResponse? response)
		{
			return Task.Run(() => Send(response));
		}

		public void Stop(string? message = null)
		{
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Expected O, but got Unknown
			if (message != null)
			{
				Send((SimpleJSONResponse?)new MessageResponse
				{
					type = (ResponseType)254,
					message = message
				});
			}
			m_client?.Close();
		}

		public Task StopAsync(string? message = null)
		{
			return Task.Run(delegate
			{
				Stop(message);
			});
		}

		public bool KeepAlive()
		{
			return Send((SimpleJSONResponse?)(object)KEEPALIVE);
		}

		public Task<bool> KeepAliveAsync()
		{
			return Task.Run((Func<bool>)KeepAlive);
		}

		public void AttachMetadata(EffectResponse response)
		{
			response.metadata = new Dictionary<string, DataResponse>();
			string[] commonMetadata = MetadataDelegates.CommonMetadata;
			foreach (string text in commonMetadata)
			{
				if (MetadataLoader.Metadata.TryGetValue(text, out MetadataDelegate value))
				{
					response.metadata.Add(text, value(m_mod));
				}
				else
				{
					CrowdControlMod.Instance.Logger.LogError((object)("Metadata delegate \"" + text + "\" could not be found. Available delegates: " + string.Join(", ", MetadataLoader.Metadata.Keys)));
				}
			}
		}

		public bool ShowEffects(params string[] codes)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Expected O, but got Unknown
			return Send((SimpleJSONResponse?)new EffectUpdate(codes, (EffectStatus)128, (string)null));
		}

		public bool ShowEffects([ParamCollection] IEnumerable<string> codes)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Expected O, but got Unknown
			return Send((SimpleJSONResponse?)new EffectUpdate(codes, (EffectStatus)128, (string)null));
		}

		public Task<bool> ShowEffectsAsync(params string[] codes)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Expected O, but got Unknown
			return SendAsync((SimpleJSONResponse?)new EffectUpdate(codes, (EffectStatus)128, (string)null));
		}

		public Task<bool> ShowEffectsAsync([ParamCollection] IEnumerable<string> codes)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Expected O, but got Unknown
			return SendAsync((SimpleJSONResponse?)new EffectUpdate(codes, (EffectStatus)128, (string)null));
		}

		public bool ShowAllEffects()
		{
			return ShowEffects(m_mod.EffectLoader.Effects.Keys);
		}

		public Task<bool> ShowAllEffectsAsync()
		{
			return ShowEffectsAsync(m_mod.EffectLoader.Effects.Keys);
		}

		public bool HideEffects(params string[] codes)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Expected O, but got Unknown
			return Send((SimpleJSONResponse?)new EffectUpdate(codes, (EffectStatus)129, (string)null));
		}

		public bool HideEffects([ParamCollection] IEnumerable<string> codes)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Expected O, but got Unknown
			return Send((SimpleJSONResponse?)new EffectUpdate(codes, (EffectStatus)129, (string)null));
		}

		public Task<bool> HideEffectsAsync(params string[] codes)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Expected O, but got Unknown
			return SendAsync((SimpleJSONResponse?)new EffectUpdate(codes, (EffectStatus)129, (string)null));
		}

		public Task<bool> HideEffectsAsync([ParamCollection] IEnumerable<string> codes)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Expected O, but got Unknown
			return SendAsync((SimpleJSONResponse?)new EffectUpdate(codes, (EffectStatus)129, (string)null));
		}

		public bool HideAllEffects()
		{
			return HideEffects(m_mod.EffectLoader.Effects.Keys);
		}

		public Task<bool> HideAllEffectsAsync()
		{
			return HideEffectsAsync(m_mod.EffectLoader.Effects.Keys);
		}

		public bool EnableEffects(params string[] codes)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Expected O, but got Unknown
			return Send((SimpleJSONResponse?)new EffectUpdate(codes, (EffectStatus)130, (string)null));
		}

		public bool EnableEffects([ParamCollection] IEnumerable<string> codes)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Expected O, but got Unknown
			return Send((SimpleJSONResponse?)new EffectUpdate(codes, (EffectStatus)130, (string)null));
		}

		public Task<bool> EnableEffectsAsync(params string[] codes)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Expected O, but got Unknown
			return SendAsync((SimpleJSONResponse?)new EffectUpdate(codes, (EffectStatus)130, (string)null));
		}

		public Task<bool> EnableEffectsAsync([ParamCollection] IEnumerable<string> codes)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Expected O, but got Unknown
			return SendAsync((SimpleJSONResponse?)new EffectUpdate(codes, (EffectStatus)130, (string)null));
		}

		public bool EnableAllEffects()
		{
			return ShowEffects(m_mod.EffectLoader.Effects.Keys);
		}

		public Task<bool> EnableAllEffectsAsync()
		{
			return ShowEffectsAsync(m_mod.EffectLoader.Effects.Keys);
		}

		public bool DisableEffects(params string[] codes)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Expected O, but got Unknown
			return Send((SimpleJSONResponse?)new EffectUpdate(codes, (EffectStatus)131, (string)null));
		}

		public bool DisableEffects([ParamCollection] IEnumerable<string> codes)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Expected O, but got Unknown
			return Send((SimpleJSONResponse?)new EffectUpdate(codes, (EffectStatus)131, (string)null));
		}

		public Task<bool> DisableEffectsAsync(params string[] codes)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Expected O, but got Unknown
			return SendAsync((SimpleJSONResponse?)new EffectUpdate(codes, (EffectStatus)131, (string)null));
		}

		public Task<bool> DisableEffectsAsync([ParamCollection] IEnumerable<string> codes)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Expected O, but got Unknown
			return SendAsync((SimpleJSONResponse?)new EffectUpdate(codes, (EffectStatus)131, (string)null));
		}

		public bool DisableAllEffects()
		{
			return ShowEffects(m_mod.EffectLoader.Effects.Keys);
		}

		public Task<bool> DisableAllEffectsAsync()
		{
			return ShowEffectsAsync(m_mod.EffectLoader.Effects.Keys);
		}
	}
	internal static class ReflectionEx
	{
		private const BindingFlags BINDING_FLAGS = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;

		public static void SetField(this object obj, string prop, object val)
		{
			obj.GetType().GetField(prop, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic).SetValue(obj, val);
		}

		public static T GetField<T>(this object obj, string prop)
		{
			return (T)obj.GetType().GetField(prop, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic).GetValue(obj);
		}

		public static void SetProperty(this object obj, string prop, object val)
		{
			obj.GetType().GetField(prop, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic).SetValue(obj, val);
		}

		public static T GetProperty<T>(this object obj, string prop)
		{
			return (T)obj.GetType().GetField(prop, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic).GetValue(obj);
		}

		public static void CallMethod(this object obj, string methodName, params object[] vals)
		{
			obj.GetType().GetMethod(methodName, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic).Invoke(obj, vals);
		}

		public static T CallMethod<T>(this object obj, string methodName, params object[] vals)
		{
			return (T)obj.GetType().GetMethod(methodName, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic).Invoke(obj, vals);
		}
	}
	public class Scheduler(CrowdControlMod mod, NetworkClient networkClient)
	{
		private class RequestState
		{
			private IEnumerator? m_enumerator;

			public EffectRequest Request { get; }

			public Effect Effect { get; }

			public TimedEffectState? TimedEffectState { get; }

			public bool MoveNext()
			{
				if (m_enumerator != null)
				{
					if (m_enumerator.MoveNext())
					{
						return true;
					}
					(m_enumerator as IDisposable)?.Dispose();
					m_enumerator = null;
				}
				switch (TimedEffectState?.State)
				{
				case CrowdControl.Delegates.Effects.TimedEffectState.EffectState.NotStarted:
					if (m_enumerator == null)
					{
						m_enumerator = TimedEffectState.Start();
					}
					m_enumerator.MoveNext();
					return true;
				case CrowdControl.Delegates.Effects.TimedEffectState.EffectState.Running:
				case CrowdControl.Delegates.Effects.TimedEffectState.EffectState.Paused:
					if (m_enumerator == null)
					{
						m_enumerator = TimedEffectState.Tick();
					}
					m_enumerator.MoveNext();
					return true;
				default:
					return false;
				}
			}

			public void Pause()
			{
				(m_enumerator as IDisposable)?.Dispose();
				m_enumerator = null;
				TimedEffectState.EffectState? effectState = TimedEffectState?.State;
				if (effectState.HasValue && effectState == CrowdControl.Delegates.Effects.TimedEffectState.EffectState.Running)
				{
					m_enumerator = TimedEffectState.Pause();
				}
			}

			public void Resume()
			{
				(m_enumerator as IDisposable)?.Dispose();
				m_enumerator = null;
				TimedEffectState.EffectState? effectState = TimedEffectState?.State;
				if (effectState.HasValue && effectState == CrowdControl.Delegates.Effects.TimedEffectState.EffectState.Paused)
				{
					m_enumerator = TimedEffectState.Resume();
				}
			}

			public void Stop()
			{
				(m_enumerator as IDisposable)?.Dispose();
				m_enumerator = null;
				TimedEffectState.EffectState? effectState = TimedEffectState?.State;
				if (effectState.HasValue)
				{
					TimedEffectState.EffectState valueOrDefault = effectState.GetValueOrDefault();
					if ((uint)(valueOrDefault - 1) <= 1u)
					{
						m_enumerator = TimedEffectState.Stop();
					}
				}
			}

			public RequestState(EffectRequest request, Effect effect)
			{
				Request = request;
				Effect = effect;
				if (Effect.IsTimed)
				{
					TimedEffectState = new TimedEffectState(effect, request, SITimeSpan.FromMilliseconds(request.duration.GetValueOrDefault()));
				}
			}
		}

		private CrowdControlMod m_mod = mod;

		private NetworkClient m_networkClient = networkClient;

		private readonly ConcurrentQueue<RequestState> m_requestQueue = new ConcurrentQueue<RequestState>();

		private readonly ConcurrentDictionary<uint, RequestState> m_runningEffects = new ConcurrentDictionary<uint, RequestState>();

		public bool IsRunning(string id)
		{
			foreach (TimedEffectState item in m_requestQueue.Select((RequestState p) => p.TimedEffectState).OfType<TimedEffectState>())
			{
				if (item.Effect.EffectAttribute.IDs.Contains(id))
				{
					return true;
				}
			}
			return false;
		}

		public void ProcessRequest(SimpleJSONRequest? request)
		{
			//IL_0010: 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_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Expected I4, but got Unknown
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Invalid comparison between Unknown and I4
			//IL_01bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c7: Expected O, but got Unknown
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Expected O, but got Unknown
			//IL_0153: Unknown result type (might be due to invalid IL or missing references)
			//IL_015d: Expected O, but got Unknown
			//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fb: Expected O, but got Unknown
			RequestType? val = request?.type;
			if (!val.HasValue)
			{
				return;
			}
			RequestType valueOrDefault = val.GetValueOrDefault();
			switch ((int)valueOrDefault)
			{
			default:
				if ((int)valueOrDefault == 253)
				{
					mod.GameStateManager.UpdateGameState(force: true);
				}
				break;
			case 0:
			{
				EffectRequest val5 = (EffectRequest)(object)((request is EffectRequest) ? request : null);
				if (val5 != null)
				{
					EffectRequest val4 = val5;
					if (val4.code == null)
					{
						val4.code = string.Empty;
					}
					if (!mod.EffectLoader.Effects.ContainsKey(val5.code))
					{
						networkClient.Send((SimpleJSONResponse?)new EffectResponse(((SimpleJSONRequest)val5).id, (EffectStatus)2, (StandardErrors)4097));
						CrowdControlMod.Instance.Logger.LogError((object)(StandardErrors)4097);
					}
					else
					{
						networkClient.Send((SimpleJSONResponse?)new EffectResponse(((SimpleJSONRequest)val5).id, (EffectStatus)(!mod.GameStateManager.IsReady(val5.code))));
					}
				}
				break;
			}
			case 1:
			{
				EffectRequest val3 = (EffectRequest)(object)((request is EffectRequest) ? request : null);
				if (val3 != null)
				{
					EffectRequest val4 = val3;
					if (val4.code == null)
					{
						val4.code = string.Empty;
					}
					if (!mod.EffectLoader.Effects.TryGetValue(val3.code, out Effect value2))
					{
						networkClient.Send((SimpleJSONResponse?)new EffectResponse(((SimpleJSONRequest)val3).id, (EffectStatus)2, (StandardErrors)4097));
						CrowdControlMod.Instance.Logger.LogError((object)(StandardErrors)4097);
					}
					else
					{
						m_requestQueue.Enqueue(new RequestState(val3, value2));
					}
				}
				break;
			}
			case 2:
			{
				EffectRequest val2 = (EffectRequest)(object)((request is EffectRequest) ? request : null);
				if (val2 != null)
				{
					if (!m_runningEffects.TryGetValue(((SimpleJSONRequest)val2).id, out RequestState value))
					{
						networkClient.Send((SimpleJSONResponse?)new EffectResponse(((SimpleJSONRequest)val2).id, (EffectStatus)1, (StandardErrors)16899));
						CrowdControlMod.Instance.Logger.LogError((object)(StandardErrors)16899);
					}
					else
					{
						value.Stop();
					}
				}
				break;
			}
			}
		}

		public void Enqueue(EffectRequest request, Effect effect)
		{
			m_requestQueue.Enqueue(new RequestState(request, effect));
		}

		public void PauseAll()
		{
			foreach (KeyValuePair<uint, RequestState> runningEffect in m_runningEffects)
			{
				runningEffect.Value.Pause();
			}
		}

		public void ResumeAll()
		{
			foreach (KeyValuePair<uint, RequestState> runningEffect in m_runningEffects)
			{
				runningEffect.Value.Resume();
			}
		}

		public void Tick()
		{
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Expected O, but got Unknown
			RequestState result;
			while (m_requestQueue.TryDequeue(out result))
			{
				if (!mod.GameStateManager.IsReady(result.Request.code))
				{
					networkClient.SendAsync((SimpleJSONResponse?)new EffectResponse(((SimpleJSONRequest)result.Request).id, (EffectStatus)3)).Forget();
					continue;
				}
				if (result.TimedEffectState != null)
				{
					m_runningEffects.TryAdd(((SimpleJSONRequest)result.Request).id, result);
					continue;
				}
				EffectResponse response;
				try
				{
					response = result.Effect.Start(result.Request);
				}
				catch (Exception ex)
				{
					response = EffectResponse.Failure(((SimpleJSONRequest)result.Request).id, (StandardErrors)1);
					CrowdControlMod.Instance.Logger.LogError((object)ex.Message);
				}
				networkClient.AttachMetadata(response);
				networkClient.SendAsync((SimpleJSONResponse?)(object)response).Forget();
			}
			ConsumeEnumerators();
		}

		private void ConsumeEnumerators()
		{
			foreach (KeyValuePair<uint, RequestState> runningEffect in m_runningEffects)
			{
				if (!runningEffect.Value.MoveNext())
				{
					m_runningEffects.TryRemove(runningEffect.Key, out RequestState _);
				}
			}
		}
	}
	[Serializable]
	[JsonConverter(typeof(Converter))]
	public struct SITimeSpan : IEquatable<SITimeSpan>, IEquatable<TimeSpan>, IEquatable<double>, IComparable<SITimeSpan>, IComparable<TimeSpan>, IComparable<double>, IFormattable
	{
		private class Converter : JsonConverter<SITimeSpan>
		{
			public override void WriteJson(JsonWriter writer, SITimeSpan value, JsonSerializer serializer)
			{
				writer.WriteValue(value._value.TotalSeconds);
			}

			public override SITimeSpan ReadJson(JsonReader reader, Type objectType, SITimeSpan existingValue, bool hasExistingValue, JsonSerializer serializer)
			{
				if (reader.Value is TimeSpan timeSpan)
				{
					return timeSpan;
				}
				if (reader.Value is string s)
				{
					if (TimeSpan.TryParse(s, out var result))
					{
						return result;
					}
					if (double.TryParse(s, out var result2))
					{
						return result2;
					}
				}
				return Convert.ToDouble(reader.Value);
			}
		}

		public static readonly SITimeSpan Zero = new SITimeSpan(TimeSpan.Zero);

		public static readonly SITimeSpan MinValue = new SITimeSpan(TimeSpan.MinValue);

		public static readonly SITimeSpan MaxValue = new SITimeSpan(TimeSpan.MaxValue);

		private readonly TimeSpan _value;

		public long Ticks => _value.Ticks;

		public int Milliseconds => _value.Milliseconds;

		public int Seconds => _value.Seconds;

		public int Minutes => _value.Minutes;

		public int Hours => _value.Hours;

		public int Days => _value.Days;

		public double TotalMilliseconds => _value.TotalMilliseconds;

		public double TotalSeconds => _value.TotalSeconds;

		public double TotalMinutes => _value.TotalMinutes;

		public double TotalHours => _value.TotalHours;

		public double TotalDays => _value.TotalDays;

		public override string ToString()
		{
			return _value.ToString();
		}

		public string ToString(string? format)
		{
			return _value.ToString(format);
		}

		public string ToString(string? format, IFormatProvider? formatProvider)
		{
			return _value.ToString(format, formatProvider);
		}

		public static SITimeSpan Parse(string input)
		{
			if (input.Contains('.'))
			{
				return new SITimeSpan(TimeSpan.ParseExact(input, "mm\\:ss\\.fff", null));
			}
			return new SITimeSpan(TimeSpan.Parse(input));
		}

		public static bool TryParse(string s, out SITimeSpan result)
		{
			TimeSpan result3;
			bool result2 = TimeSpan.TryParse(s, out result3);
			result = new SITimeSpan(result3);
			return result2;
		}

		public static int Compare(SITimeSpan t1, SITimeSpan t2)
		{
			return TimeSpan.Compare(t1._value, t2._value);
		}

		public static int Compare(TimeSpan t1, SITimeSpan t2)
		{
			return TimeSpan.Compare(t1, t2._value);
		}

		public static int Compare(SITimeSpan t1, TimeSpan t2)
		{
			return TimeSpan.Compare(t1._value, t2);
		}

		public static int Compare(double t1, SITimeSpan t2)
		{
			if (t1 > t2.TotalSeconds)
			{
				return 1;
			}
			if (!(t1 < t2.TotalSeconds))
			{
				return 0;
			}
			return -1;
		}

		public static int Compare(SITimeSpan t1, double t2)
		{
			if (t1.TotalSeconds > t2)
			{
				return 1;
			}
			if (!(t1.TotalSeconds < t2))
			{
				return 0;
			}
			return -1;
		}

		public static bool Equals(SITimeSpan t1, SITimeSpan t2)
		{
			return TimeSpan.Equals(t1._value, t2._value);
		}

		public static bool Equals(TimeSpan t1, SITimeSpan t2)
		{
			return TimeSpan.Equals(t1, t2._value);
		}

		public static bool Equals(SITimeSpan t1, TimeSpan t2)
		{
			return TimeSpan.Equals(t1._value, t2);
		}

		public static bool Equals(double t1, SITimeSpan t2)
		{
			return object.Equals(t1, (double)t2);
		}

		public static bool Equals(SITimeSpan t1, double t2)
		{
			return object.Equals((double)t1, t2);
		}

		public static SITimeSpan FromTicks(long value)
		{
			return new SITimeSpan(TimeSpan.FromTicks(value));
		}

		public static SITimeSpan FromMilliseconds(double value)
		{
			return new SITimeSpan(TimeSpan.FromMilliseconds(value));
		}

		public static SITimeSpan FromSeconds(double value)
		{
			return new SITimeSpan(TimeSpan.FromSeconds(value));
		}

		public static SITimeSpan FromMinutes(double value)
		{
			return new SITimeSpan(TimeSpan.FromMinutes(value));
		}

		public static SITimeSpan FromHours(double value)
		{
			return new SITimeSpan(TimeSpan.FromHours(value));
		}

		public static SITimeSpan FromDays(double value)
		{
			return new SITimeSpan(TimeSpan.FromDays(value));
		}

		public SITimeSpan Duration()
		{
			return new SITimeSpan(_value.Duration());
		}

		public SITimeSpan Add(SITimeSpan other)
		{
			return new SITimeSpan(_value.Add(other._value));
		}

		public SITimeSpan Subtract(SITimeSpan other)
		{
			return new SITimeSpan(_value.Subtract(other._value));
		}

		public SITimeSpan Negate()
		{
			return new SITimeSpan(_value.Negate());
		}

		private SITimeSpan(TimeSpan value)
		{
			_value = value;
		}

		private SITimeSpan(double value)
		{
			_value = TimeSpan.FromSeconds(value);
		}

		private SITimeSpan(long value)
		{
			_value = TimeSpan.FromSeconds(value);
		}

		public SITimeSpan? NullIfZero()
		{
			if (!(_value == TimeSpan.Zero))
			{
				return this;
			}
			return null;
		}

		public static implicit operator SITimeSpan(double value)
		{
			return new SITimeSpan(value);
		}

		public static implicit operator SITimeSpan?(double? value)
		{
			if (!value.HasValue)
			{
				return null;
			}
			return new SITimeSpan(value.Value);
		}

		public static implicit operator SITimeSpan(TimeSpan value)
		{
			return new SITimeSpan(value);
		}

		public static implicit operator SITimeSpan?(TimeSpan? value)
		{
			if (!value.HasValue)
			{
				return null;
			}
			return new SITimeSpan(value.Value);
		}

		public static implicit operator SITimeSpan(Func<TimeSpan> value)
		{
			return new SITimeSpan(value());
		}

		public static implicit operator SITimeSpan?(Func<TimeSpan>? value)
		{
			if (value == null)
			{
				return null;
			}
			return new SITimeSpan(value());
		}

		public static implicit operator SITimeSpan(Func<SITimeSpan> value)
		{
			return new SITimeSpan(value()._value);
		}

		public static implicit operator SITimeSpan?(Func<SITimeSpan>? value)
		{
			if (value == null)
			{
				return null;
			}
			return new SITimeSpan(value()._value);
		}

		public static explicit operator double(SITimeSpan value)
		{
			return value._value.TotalSeconds;
		}

		public static explicit operator double?(SITimeSpan? value)
		{
			return value?._value.TotalSeconds;
		}

		public static explicit operator float(SITimeSpan value)
		{
			return (float)value._value.TotalSeconds;
		}

		public static explicit operator float?(SITimeSpan? value)
		{
			return (float?)value?._value.TotalSeconds;
		}

		public static explicit operator long(SITimeSpan value)
		{
			return checked((long)value._value.TotalSeconds);
		}

		public static explicit operator long?(SITimeSpan? value)
		{
			return checked((long?)value?._value.TotalSeconds);
		}

		public static explicit operator TimeSpan(SITimeSpan value)
		{
			return value._value;
		}

		public static explicit operator TimeSpan?(SITimeSpan? value)
		{
			return value?._value;
		}

		public static explicit operator Func<TimeSpan>(SITimeSpan value)
		{
			return () => value._value;
		}

		public static explicit operator Func<TimeSpan?>(SITimeSpan? value)
		{
			return () => value?._value;
		}

		public static explicit operator Func<SITimeSpan>(SITimeSpan value)
		{
			return () => value;
		}

		public static explicit operator Func<SITimeSpan?>(SITimeSpan? value)
		{
			return () => value;
		}

		public override bool Equals(object? obj)
		{
			if (obj is SITimeSpan other)
			{
				return Equals(other);
			}
			if (obj is TimeSpan other2)
			{
				return Equals(other2);
			}
			if (obj is double other3)
			{
				return Equals(other3);
			}
			return false;
		}

		public override int GetHashCode()
		{
			return _value.GetHashCode();
		}

		public bool Equals(SITimeSpan other)
		{
			return _value.Equals(other._value);
		}

		public int CompareTo(SITimeSpan other)
		{
			return _value.CompareTo(other._value);
		}

		public static bool operator ==(SITimeSpan a, SITimeSpan b)
		{
			return a._value.Equals(b._value);
		}

		public static bool operator !=(SITimeSpan a, SITimeSpan b)
		{
			return !a._value.Equals(b._value);
		}

		public static bool operator <(SITimeSpan a, SITimeSpan b)
		{
			return a._value < b._value;
		}

		public static bool operator <=(SITimeSpan a, SITimeSpan b)
		{
			return a._value <= b._value;
		}

		public static bool operator >(SITimeSpan a, SITimeSpan b)
		{
			return a._value > b._value;
		}

		public static bool operator >=(SITimeSpan a, SITimeSpan b)
		{
			return a._value >= b._value;
		}

		public bool Equals(TimeSpan other)
		{
			return _value.Equals(other);
		}

		public int CompareTo(TimeSpan other)
		{
			return _value.CompareTo(other);
		}

		public static bool operator ==(SITimeSpan a, TimeSpan b)
		{
			return a.Equals(b);
		}

		public static bool operator ==(TimeSpan a, SITimeSpan b)
		{
			return b.Equals(a);
		}

		public static bool operator !=(SITimeSpan a, TimeSpan b)
		{
			return !a.Equals(b);
		}

		public static bool operator !=(TimeSpan a, SITimeSpan b)
		{
			return !b.Equals(a);
		}

		public static bool operator <(SITimeSpan a, TimeSpan b)
		{
			return a._value < b;
		}

		public static bool operator <(TimeSpan a, SITimeSpan b)
		{
			return a < b._value;
		}

		public static bool operator <=(SITimeSpan a, TimeSpan b)
		{
			return a._value <= b;
		}

		public static bool operator <=(TimeSpan a, SITimeSpan b)
		{
			return a <= b._value;
		}

		public static bool operator >(SITimeSpan a, TimeSpan b)
		{
			return a._value > b;
		}

		public static bool operator >(TimeSpan a, SITimeSpan b)
		{
			return a > b._value;
		}

		public static bool operator >=(SITimeSpan a, TimeSpan b)
		{
			return a._value >= b;
		}

		public static bool operator >=(TimeSpan a, SITimeSpan b)
		{
			return a >= b._value;
		}

		public static SITimeSpan operator -(SITimeSpan a)
		{
			return -a._value;
		}

		public static SITimeSpan operator +(TimeSpan a, SITimeSpan b)
		{
			return a + b._value;
		}

		public static SITimeSpan operator -(TimeSpan a, SITimeSpan b)
		{
			return a - b._value;
		}

		public static SITimeSpan operator +(SITimeSpan a, TimeSpan b)
		{
			return a._value + b;
		}

		public static SITimeSpan operator -(SITimeSpan a, TimeSpan b)
		{
			return a._value - b;
		}

		public static SITimeSpan operator +(SITimeSpan a, SITimeSpan b)
		{
			return a._value + b._value;
		}

		public static SITimeSpan operator -(SITimeSpan a, SITimeSpan b)
		{
			return a._value - b._value;
		}

		public static DateTime operator +(DateTime a, SITimeSpan b)
		{
			return a + b._value;
		}

		public static DateTime operator -(DateTime a, SITimeSpan b)
		{
			return a - b._value;
		}

		public static DateTimeOffset operator +(DateTimeOffset a, SITimeSpan b)
		{
			return a + b._value;
		}

		public static DateTimeOffset operator -(DateTimeOffset a, SITimeSpan b)
		{
			return a - b._value;
		}

		public static SITimeSpan operator +(double a, SITimeSpan b)
		{
			return a + b._value.TotalSeconds;
		}

		public static SITimeSpan operator -(double a, SITimeSpan b)
		{
			return a - b._value.TotalSeconds;
		}

		public static SITimeSpan operator *(double a, SITimeSpan b)
		{
			return a * b._value.TotalSeconds;
		}

		public static SITimeSpan operator +(SITimeSpan a, double b)
		{
			return a._value.TotalSeconds + b;
		}

		public static SITimeSpan operator -(SITimeSpan a, double b)
		{
			return a._value.TotalSeconds - b;
		}

		public static SITimeSpan operator *(SITimeSpan a, double b)
		{
			return a._value.TotalSeconds * b;
		}

		public static SITimeSpan operator /(SITimeSpan a, double b)
		{
			return a._value.TotalSeconds / b;
		}

		public static SITimeSpan operator %(SITimeSpan a, double b)
		{
			return a._value.TotalSeconds % b;
		}

		public bool Equals(double other)
		{
			return _value.TotalSeconds.Equals(other);
		}

		public int CompareTo(double other)
		{
			return _value.TotalSeconds.CompareTo(other);
		}

		public static bool operator ==(SITimeSpan a, double b)
		{
			return a.Equals(b);
		}

		public static bool operator ==(double a, SITimeSpan b)
		{
			return b.Equals(a);
		}

		public static bool operator !=(SITimeSpan a, double b)
		{
			return !a.Equals(b);
		}

		public static bool operator !=(double a, SITimeSpan b)
		{
			return !b.Equals(a);
		}

		public static bool operator <(SITimeSpan a, double b)
		{
			return a._value.TotalSeconds < b;
		}

		public static bool operator <(double a, SITimeSpan b)
		{
			return a < b._value.TotalSeconds;
		}

		public static bool operator <=(SITimeSpan a, double b)
		{
			return a._value.TotalSeconds <= b;
		}

		public static bool operator >=(SITimeSpan a, double b)
		{
			return a._value.TotalSeconds >= b;
		}

		public static bool operator >(SITimeSpan a, double b)
		{
			return a._value.TotalSeconds > b;
		}

		public static bool operator >(double a, SITimeSpan b)
		{
			return a > b._value.TotalSeconds;
		}

		public static bool operator <=(double a, SITimeSpan b)
		{
			return a <= b._value.TotalSeconds;
		}

		public static bool operator >=(double a, SITimeSpan b)
		{
			return a >= b._value.TotalSeconds;
		}
	}
	public static class TaskEx
	{
		public static async void Forget(this Task task)
		{
			try
			{
				await task.ConfigureAwait(continueOnCapturedContext: false);
			}
			catch (Exception ex)
			{
				CrowdControlMod.Instance.Logger.LogError((object)ex);
			}
		}

		public static async void Forget(this Task task, bool silent)
		{
			try
			{
				await task.ConfigureAwait(continueOnCapturedContext: false);
			}
			catch (Exception ex)
			{
				if (!silent)
				{
					CrowdControlMod.Instance.Logger.LogError((object)ex);
				}
			}
		}
	}
}
namespace CrowdControl.Utilities
{
	public static class EnemySpawnerUtility
	{
		private static readonly Dictionary<string, GameObject> _enemyPrefabCache = new Dictionary<string, GameObject>();

		private static bool _cacheInitialized = false;

		public static List<GameObject> SpawnEnemy(string enemyName, Vector3 position, int count = 1)
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			List<GameObject> list = new List<GameObject>();
			if (count <= 0)
			{
				return list;
			}
			GameObject enemyPrefab = GetEnemyPrefab(enemyName);
			if ((Object)(object)enemyPrefab == (Object)null)
			{
				Debug.LogWarning((object)("[EnemySpawnerUtility] Could not find enemy prefab for: " + enemyName));
				return list;
			}
			for (int i = 0; i < count; i = checked(i + 1))
			{
				try
				{
					GameObject val = Object.Instantiate<GameObject>(enemyPrefab, position, Quaternion.identity);
					if ((Object)(object)val != (Object)null)
					{
						val.SetActive(true);
						InitializeEnemy(val);
						list.Add(val);
						CrowdControlMod.LogDebug($"[EnemySpawnerUtility] Spawned {enemyName} at {position}");
					}
				}
				catch (Exception ex)
				{
					Debug.LogError((object)("[EnemySpawnerUtility] Error spawning enemy " + enemyName + ": " + ex.Message));
				}
			}
			return list;
		}

		public static List<GameObject> SpawnEnemiesInCircle(string enemyName, Vector3 centerPosition, float radius, int count)
		{
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: 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)
			List<GameObject> list = new List<GameObject>();
			if (count <= 0)
			{
				return list;
			}
			GameObject enemyPrefab = GetEnemyPrefab(enemyName);
			if ((Object)(object)enemyPrefab == (Object)null)
			{
				Debug.LogWarning((object)("[EnemySpawnerUtility] Could not find enemy prefab for: " + enemyName));
				return list;
			}
			for (int i = 0; i < count; i = checked(i + 1))
			{
				float num = 360f / (float)count * (float)i;
				Vector3 val = centerPosition + new Vector3(Mathf.Cos(num * (MathF.PI / 180f)) * radius, Mathf.Sin(num * (MathF.PI / 180f)) * radius, 0f);
				try
				{
					GameObject val2 = Object.Instantiate<GameObject>(enemyPrefab, val, Quaternion.identity);
					if ((Object)(object)val2 != (Object)null)
					{
						val2.SetActive(true);
						InitializeEnemy(val2);
						list.Add(val2);
						CrowdControlMod.LogDebug($"[EnemySpawnerUtility] Spawned {enemyName} at {val}");
					}
				}
				catch (Exception ex)
				{
					Debug.LogError((object)("[EnemySpawnerUtility] Error spawning enemy " + enemyName + ": " + ex.Message));
				}
			}
			return list;
		}

		public static List<GameObject> SpawnEnemiesRandomly(string enemyName, Vector3 centerPosition, float minDistance, float maxDistance, int count)
		{
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			List<GameObject> list = new List<GameObject>();
			if (count <= 0)
			{
				return list;
			}
			GameObject enemyPrefab = GetEnemyPrefab(enemyName);
			if ((Object)(object)enemyPrefab == (Object)null)
			{
				Debug.LogWarning((object)("[EnemySpawnerUtility] Could not find enemy prefab for: " + enemyName));
				return list;
			}
			for (int i = 0; i < count; i = checked(i + 1))
			{
				float num = Random.Range(0f, 360f);
				float num2 = Random.Range(minDistance, maxDistance);
				Vector3 val = centerPosition + new Vector3(Mathf.Cos(num * (MathF.PI / 180f)) * num2, Mathf.Sin(num * (MathF.PI / 180f)) * num2, 0f);
				try
				{
					GameObject val2 = Object.Instantiate<GameObject>(enemyPrefab, val, Quaternion.identity);
					if ((Object)(object)val2 != (Object)null)
					{
						val2.SetActive(true);
						InitializeEnemy(val2);
						list.Add(val2);
						CrowdControlMod.LogDebug($"[EnemySpawnerUtility] Spawned {enemyName} at {val}");
					}
				}
				catch (Exception ex)
				{
					Debug.LogError((object)("[EnemySpawnerUtility] Error spawning enemy " + enemyName + ": " + ex.Message));
				}
			}
			return list;
		}

		public static GameObject GetEnemyPrefab(string enemyName)
		{
			if (!_cacheInitialized)
			{
				InitializeEnemyCache();
			}
			if (_enemyPrefabCache.TryGetValue(enemyName, out GameObject value))
			{
				return value;
			}
			return FindEnemyByPartialName(enemyName);
		}

		public static List<string> GetAvailableEnemyNames()
		{
			if (!_cacheInitialized)
			{
				InitializeEnemyCache();
			}
			return _enemyPrefabCache.Keys.ToList();
		}

		public static bool IsEnemyAvailable(string enemyName)
		{
			if (!_cacheInitialized)
			{
				InitializeEnemyCache();
			}
			if (!_enemyPrefabCache.ContainsKey(enemyName))
			{
				return (Object)(object)FindEnemyByPartialName(enemyName) != (Object)null;
			}
			return true;
		}

		private static void InitializeEnemyCache()
		{
			CrowdControlMod.LogDebug("[EnemySpawnerUtility] Initializing enemy cache...");
			GameObject[] array = Resources.FindObjectsOfTypeAll<GameObject>();
			int num = 0;
			GameObject[] array2 = array;
			foreach (GameObject val in array2)
			{
				if (IsValidEnemyPrefab(val))
				{
					string cleanEnemyName = GetCleanEnemyName(((Object)val).name);
					if (!string.IsNullOrEmpty(cleanEnemyName) && !_enemyPrefabCache.ContainsKey(cleanEnemyName))
					{
						_enemyPrefabCache[cleanEnemyName] = val;
						num = checked(num + 1);
						CrowdControlMod.LogDebug("[EnemySpawnerUtility] Cached enemy: " + cleanEnemyName + " (original: " + ((Object)val).name + ")");
					}
				}
			}
			_cacheInitialized = true;
			CrowdControlMod.LogDebug($"[EnemySpawnerUtility] Cache initialization complete. Found {num} enemy prefabs.");
		}

		private static bool IsValidEnemyPrefab(GameObject obj)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			Scene scene = obj.scene;
			if (((Scene)(ref scene)).IsValid())
			{
				return false;
			}
			if (((Object)obj).name.Contains("Effect") || ((Object)obj).name.Contains("UI") || ((Object)obj).name.Contains("Particle") || ((Object)obj).name.Contains("Hit") || ((Object)obj).name.Contains("Death") || ((Object)obj).name.Contains("Clone") || ((Object)obj).name.Contains("Journal") || ((Object)obj).name.Contains("Corpse") || ((Object)obj).name.Contains("Damager") || ((Object)obj).name.Contains("Range") || ((Object)obj).name.Contains("Detector") || ((Object)obj).name.Contains("Sucker") || ((Object)obj).name.Contains("Physics Pusher") || ((Object)obj).name.Contains("ThreadedEnemy"))
			{
				return false;
			}
			return (Object)(object)obj.GetComponent<HealthManager>() != (Object)null;
		}

		private static string GetCleanEnemyName(string originalName)
		{
			string text = originalName;
			string[] array = new string[9] { " (1)", " (2)", " (3)", " (4)", " (5)", " (6)", " (7)", " (8)", " (9)" };
			checked
			{
				foreach (string text2 in array)
				{
					if (text.EndsWith(text2))
					{
						text = text.Substring(0, text.Length - text2.Length);
						break;
					}
				}
				if (text.EndsWith("Prefab"))
				{
					text = text.Substring(0, text.Length - 6);
				}
				return text.Trim();
			}
		}

		private static GameObject FindEnemyByPartialName(string enemyName)
		{
			foreach (KeyValuePair<string, GameObject> item in _enemyPrefabCache)
			{
				if (item.Key.Equals(enemyName, StringComparison.OrdinalIgnoreCase))
				{
					return item.Value;
				}
			}
			foreach (KeyValuePair<string, GameObject> item2 in _enemyPrefabCache)
			{
				if (item2.Key.Contains(enemyName, StringComparison.OrdinalIgnoreCase) || enemyName.Contains(item2.Key, StringComparison.OrdinalIgnoreCase))
				{
					return item2.Value;
				}
			}
			return null;
		}

		private static void InitializeEnemy(GameObject enemy)
		{
			HealthManager component = enemy.GetComponent<HealthManager>();
			if ((Object)(object)component != (Object)null)
			{
				component.HealToMax();
			}
			PlayMakerFSM val = PlayMakerFSM.FindFsmOnGameObject(enemy, "chaser");
			if ((Object)(object)val != (Object)null)
			{
				val.FsmVariables.FindFsmBool("Start Alert").Value = true;
			}
			IInitialisable component2 = enemy.GetComponent<IInitialisable>();
			if (component2 != null)
			{
				component2.OnAwake();
				component2.OnStart();
			}
		}

		public static void ClearCache()
		{
			_enemyPrefabCache.Clear();
			_cacheInitialized = false;
		}
	}
	public static class GameStateChecker
	{
		public static bool IsTransitioning()
		{
			HeroController instance = HeroController.instance;
			if ((Object)(object)instance == (Object)null)
			{
				return false;
			}
			return instance.cState.transitioning;
		}

		public static bool IsInTransitionState(HeroTransitionState state)
		{
			//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)
			HeroController instance = HeroController.instance;
			if ((Object)(object)instance == (Object)null)
			{
				return false;
			}
			return instance.transitionState == state;
		}

		public static bool IsDead()
		{
			HeroController instance = HeroController.instance;
			if ((Object)(object)instance == (Object)null)
			{
				return false;
			}
			return instance.cState.dead;
		}

		public static bool IsFrostDeath()
		{
			HeroController instance = HeroController.instance;
			if ((Object)(object)instance == (Object)null)
			{
				return false;
			}
			return instance.cState.isFrostDeath;
		}

		public static bool IsHazardDeath()
		{
			HeroController instance = HeroController.instance;
			if ((Object)(object)instance == (Object)null)
			{
				return false;
			}
			return instance.cState.hazardDeath;
		}

		public static bool IsHazardRespawning()
		{
			HeroController instance = HeroController.instance;
			if ((Object)(object)instance == (Object)null)
			{
				return false;
			}
			return instance.cState.hazardRespawning;
		}

		public static bool IsNearBench()
		{
			HeroController instance = HeroController.instance;
			if ((Object)(object)instance == (Object)null)
			{
				return false;
			}
			return instance.cState.nearBench;
		}

		public static bool IsAtBench()
		{
			return PlayerData.instance?.atBench ?? false;
		}

		public static bool IsInSavingState()
		{
			if (!IsAtBench())
			{
				return IsNearBench();
			}
			return true;
		}

		public static bool IsGameSaving()
		{
			if ((Object)(object)Platform.Current != (Object)null)
			{
				if (!Platform.Current.IsSavingAllowedByEngagement)
				{
					return false;
				}
				if (!Platform.Current.IsSaveStoreMounted)
				{
					return false;
				}
			}
			if (IsAtBench())
			{
				return true;
			}
			if (IsNearBench())
			{
				return true;
			}
			if (IsPaused())
			{
				return true;
			}
			if (IsInCutsceneMovement())
			{
				return true;
			}
			if (IsGameSavingThroughReflection())
			{
				return true;
			}
			return false;
		}

		private static bool IsGameSavingThroughReflection()
		{
			try
			{
				GameManager instance = GameManager.instance;
				if ((Object)(object)instance == (Object)null)
				{
					return false;
				}
				Type type = ((object)instance).GetType();
				FieldInfo field = type.GetField("isSaveGameQueued", BindingFlags.Instance | BindingFlags.NonPublic);
				if (field != null && (bool)field.GetValue(instance))
				{
					CrowdControlMod.LogDebug("SAVING DETECTED: isSaveGameQueued = true");
					return true;
				}
				FieldInfo field2 = type.GetField("isAutoSaveQueued", BindingFlags.Instance | BindingFlags.NonPublic);
				if (field2 != null && (bool)field2.GetValue(instance))
				{
					CrowdControlMod.LogDebug("SAVING DETECTED: isAutoSaveQueued = true");
					return true;
				}
				FieldInfo field3 = type.GetField("SavePersistentObjects", BindingFlags.Instance | BindingFlags.Public);
				if (field3 != null && field3.GetValue(instance) is Action)
				{
					CrowdControlMod.LogDebug("SAVING DETECTED: SavePersistentObjects event has subscribers");
					return true;
				}
				if (IsInMenuOrUIState())
				{
					CrowdControlMod.LogDebug("SAVING DETECTED: In menu/UI state");
					return true;
				}
			}
			catch (Exception ex)
			{
				CrowdControlMod.LogDebug("Error detecting saving through reflection: " + ex.Message);
			}
			return false;
		}

		private static bool IsInMenuOrUIState()
		{
			if (IsPaused())
			{
				return true;
			}
			if (IsInCutsceneMovement())
			{
				return true;
			}
			if (IsAtBench() || IsNearBench())
			{
				return true;
			}
			if (IsInWalkZone())
			{
				return true;
			}
			return false;
		}

		public static bool IsInWalkZone()
		{
			HeroController instance = HeroController.instance;
			if ((Object)(object)instance == (Object)null)
			{
				return false;
			}
			return instance.cState.inWalkZone;
		}

		public static bool IsPaused()
		{
			GameManager instance = GameManager.instance;
			if ((Object)(object)instance == (Object)null)
			{
				return false;
			}
			return instance.isPaused;
		}

		public static bool IsInCutsceneMovement()
		{
			HeroController instance = HeroController.instance;
			if ((Object)(object)instance == (Object)null)
			{
				return false;
			}
			return instance.cState.isInCutsceneMovement;
		}

		public static bool IsTriggerEventsPaused()
		{
			HeroController instance = HeroController.instance;
			if ((Object)(object)instance == (Object)null)
			{
				return false;
			}
			return instance.cState.isTriggerEventsPaused;
		}

		public static bool IsNeedolinPlayingMemory()
		{
			HeroController instance = HeroController.instance;
			if ((Object)(object)instance == (Object)null)
			{
				return false;
			}
			return instance.cState.needolinPlayingMemory;
		}

		public static bool IsAttacking()
		{
			HeroController instance = HeroController.instance;
			if ((Object)(object)instance == (Object)null)
			{
				return false;
			}
			return instance.cState.attacking;
		}

		public static bool IsDashing()
		{
			HeroController instance = HeroController.instance;
			if ((Object)(object)instance == (Object)null)
			{
				return false;
			}
			return instance.cState.dashing;
		}

		public static bool IsBackDashing()
		{
			HeroController instance = HeroController.instance;
			if ((Object)(object)instance == (Object)null)
			{
				return false;
			}
			return instance.cState.backDashing;
		}

		public static bool IsWallSliding()
		{
			HeroController instance = HeroController.instance;
			if ((Object)(object)instance == (Object)null)
			{
				return false;
			}
			return instance.cState.wallSliding;
		}

		public static bool IsDoubleJumping()
		{
			HeroController instance = HeroController.instance;
			if ((Object)(object)instance == (Object)null)
			{
				return false;
			}
			return instance.cState.doubleJumping;
		}

		public static bool IsFalling()
		{
			HeroController instance = HeroController.instance;
			if ((Object)(object)instance == (Object)null)
			{
				return false;
			}
			return instance.cState.falling;
		}

		public static bool IsOnGround()
		{
			HeroController instance = HeroController.instance;
			if ((Object)(object)instance == (Object)null)
			{
				return false;
			}
			return instance.cState.onGround;
		}

		public static bool IsRecoiling()
		{
			HeroController instance = HeroController.instance;
			if ((Object)(object)instance == (Object)null)
			{
				return false;
			}
			return instance.cState.recoiling;
		}

		public static bool IsSprinting()
		{
			HeroController instance = HeroController.instance;
			if ((Object)(object)instance == (Object)null)
			{
				return false;
			}
			return instance.cState.isSprinting;
		}

		public static bool IsBackScuttling()
		{
			HeroController instance = HeroController.instance;
			if ((Object)(object)instance == (Object)null)
			{
				return false;
			}
			return instance.cState.isBackScuttling;
		}

		public static bool ShouldPauseEffects()
		{
			if (!IsTransitioning() && !IsDead() && !IsHazardDeath() && !IsHazardRespawning() && !IsPaused() && !IsInCutsceneMovement() && !IsTriggerEventsPaused() && !IsNeedolinPlayingMemory() && !IsGameSaving())
			{
				return !Application.isFocused;
			}
			return true;
		}

		public static bool ShouldDisableEffects()
		{
			if (!IsDead() && !IsHazardDeath())
			{
				return IsHazardRespawning();
			}
			return true;
		}

		public static string GetGameStateDebugInfo()
		{
			if ((Object)(object)HeroController.instance == (Object)null)
			{
				return "HeroController not found";
			}
			List<string> list = new List<string>();
			if (IsTransitioning())
			{
				list.Add("Transitioning");
			}
			if (IsDead())
			{
				list.Add("Dead");
			}
			if (IsFrostDeath())
			{
				list.Add("FrostDeath");
			}
			if (IsHazardDeath())
			{
				list.Add("HazardDeath");
			}
			if (IsHazardRespawning())
			{
				list.Add("HazardRespawning");
			}
			if (IsPaused())
			{
				list.Add("Paused");
			}
			if (IsInCutsceneMovement())
			{
				list.Add("CutsceneMovement");
			}
			if (IsTriggerEventsPaused())
			{
				list.Add("TriggerEventsPaused");
			}
			if (IsNeedolinPlayingMemory())
			{
				list.Add("NeedolinPlayingMemory");
			}
			if (IsAtBench())
			{
				list.Add("AtBench");
			}
			if (IsNearBench())
			{
				list.Add("NearBench");
			}
			if (IsInSavingState())
			{
				list.Add("InSavingState");
			}
			if (IsGameSaving())
			{
				list.Add("GameSaving");
			}
			if (IsInWalkZone())
			{
				list.Add("InWalkZone");
			}
			if (IsAttacking())
			{
				list.Add("Attacking");
			}
			if (IsDashing())
			{
				list.Add("Dashing");
			}
			if (IsBackDashing())
			{
				list.Add("BackDashing");
			}
			if (IsWallSliding())
			{
				list.Add("WallSliding");
			}
			if (IsDoubleJumping())
			{
				list.Add("DoubleJumping");
			}
			if (IsFalling())
			{
				list.Add("Falling");
			}
			if (IsOnGround())
			{
				list.Add("OnGround");
			}
			if (IsRecoiling())
			{
				list.Add("Recoiling");
			}
			if (IsSprinting())
			{
				list.Add("Sprinting");
			}
			if (IsBackScuttling())
			{
				list.Add("BackScuttling");
			}
			if (list.Count <= 0)
			{
				return "Normal";
			}
			return string.Join(", ", list);
		}
	}
	public class PreloadInfo
	{
		public string key;

		public string scene;

		public string name;

		public string bundle;

		public GameObject obj;

		public PreloadInfo(string key, string scene, string name, string bundle)
		{
			this.key = key;
			this.scene = scene;
			this.name = name;
			this.bundle = PrefabLoader.bundlePrefix + bundle + PrefabLoader.bundleSuffix;
			obj = null;
		}
	}
	public static class PrefabLoader
	{
		public static List<PreloadInfo> preloads = new List<PreloadInfo>();

		public static List<AsyncOperation> ops = new List<AsyncOperation>();

		public static Dictionary<string, (AsyncOperation load, AsyncOperation unload)> asyncops = new Dictionary<string, (AsyncOperation, AsyncOperation)>();

		public static string bundlePrefix = "";

		public static string bundleSuffix = ".bundle";

		public static void addPreload(string key, string scene, string name)
		{
			preloads.Add(new PreloadInfo(key, scene, name, scene.ToLower()));
		}

		public static bool checkPreload()
		{
			checked
			{
				if (CrowdControlMod.preload == 0)
				{
					((MonoBehaviour)CrowdControlMod.Instance).StartCoroutine(preloadObjects());
					CrowdControlMod.preload++;
					return false;
				}
				if (CrowdControlMod.preload == 1)
				{
					return false;
				}
				return true;
			}
		}

		public static GameObject getPrefab(string key)
		{
			List<PreloadInfo> list = preloads.Where((PreloadInfo t) => t.key == key).ToList();
			if (list.Count > 0)
			{
				return list[0].obj;
			}
			return null;
		}

		private static IEnumerator GetObjects(string sceneName, List<PreloadInfo> loading)
		{
			Scene sceneByName = SceneManager.GetSceneByName(sceneName);
			GameObject[] rootGameObjects = ((Scene)(ref sceneByName)).GetRootGameObjects();
			GameObject[] array = rootGameObjects;
			for (int i = 0; i < array.Length; i++)
			{
				array[i].SetActive(false);
			}
			foreach (PreloadInfo item in loading)
			{
				CrowdControlMod.Instance.Logger.LogInfo((object)("Preloading object " + item.name));
				GameObject val;
				try
				{
					string[] nameparts = item.name.Split('/');
					val = ((IEnumerable<GameObject>)rootGameObjects).FirstOrDefault((Func<GameObject, bool>)((GameObject t) => ((Object)t).name == nameparts[0]));
					if (!((Object)(object)val == (Object)null))
					{
						if (nameparts.Length <= 1)
						{
							goto IL_0172;
						}
						nameparts = nameparts.Where((string source, int index) => index != 0).ToArray();
						string text = string.Join("/", nameparts);
						Transform val2 = val.transform.Find(text);
						if (!((Object)(object)val2 == (Object)null))
						{
							val = ((Component)val2).gameObject;
							goto IL_0172;
						}
					}
				}
				catch (Exception)
				{
					CrowdControlMod.Instance.Logger.LogError((object)("Invalid object name " + item.name + " when preloading scene " + sceneName));
				}
				continue;
				IL_0172:
				if ((Object)(object)val == (Object)null)
				{
					CrowdControlMod.Instance.Logger.LogError((object)("Object " + item.name + " not found when preloading scene " + sceneName));
					continue;
				}
				val = Object.Instantiate<GameObject>(val);
				Object.DontDestroyOnLoad((Object)(object)val);
				val.SetActive(false);
				item.obj = val;
				CrowdControlMod.Instance.Logger.LogInfo((object)$"Created prefab reference {item.name} {val}");
			}
			yield break;
		}

		private static void UnloadScene(string sceneName, AssetBundle myAssetBundle)
		{
			CrowdControlMod.Instance.Logger.LogInfo((object)("Unloading scene " + sceneName));
			try
			{
				AsyncOperation op = SceneManager.UnloadSceneAsync(sceneName);
				ops.Add(op);
				asyncops[sceneName] = (asyncops[sceneName].load, op);
				op.completed += delegate
				{
					ops.Remove(op);
				};
			}
			catch (Exception)
			{
				asyncops.Remove(sceneName);
			}
			if ((Object)(object)myAssetBundle != (Object)null)
			{
				myAssetBundle.Unload(false);
			}
		}

		private static IEnumerator LoadScene(AsyncOperation op, List<PreloadInfo> loading, AssetBundle myAssetBundle)
		{
			yield return op;
			ops.Remove(op);
			yield return GetObjects(loading[0].scene, loading);
			yield return null;
			int num = 30;
			if (num > 0)
			{
				SceneManager.GetSceneByName(loading[0].scene);
			}
			if (num > 0)
			{
				UnloadScene(loading[0].scene, myAssetBundle);
				yield break;
			}
			asyncops.Remove(loading[0].scene);
			if ((Object)(object)myAssetBundle != (Object)null)
			{
				myAssetBundle.Unload(false);
			}
		}

		public static void preloadScene(string scene, string bundle)
		{
			CrowdControlMod.Instance.Logger.LogInfo((object)("Preloading scene " + scene));
			List<PreloadInfo> loading = preloads.Where((PreloadInfo t) => t.scene == scene).ToList();
			AssetBundle myAssetBundle = AssetBundle.LoadFromFile(bundle);
			AsyncOperation val = SceneManager.LoadSceneAsync(scene, (LoadSceneMode)1);
			((MonoBehaviour)CrowdControlMod.Instance).StartCoroutine(LoadScene(val, loading, myAssetBundle));
			asyncops[scene] = (val, null);
			ops.Add(val);
		}

		public static IEnumerator preloadObjects()
		{
			List<string> list = (from t in preloads
				group t by t.scene into t
				select t.Key).ToList();
			float progress = 0f;
			foreach (string scene in list)
			{
				PreloadInfo preloadInfo = preloads.Where((PreloadInfo t) => t.scene == scene).First();
				preloadScene(scene, preloadInfo.bundle);
				yield return null;
			}
			while (progress < 1f && asyncops.Count > 0)
			{
				progress = asyncops.Values.Select<(AsyncOperation, AsyncOperation), float>(delegate((AsyncOperation load, AsyncOperation unload) x)
				{
					AsyncOperation item = x.load;
					float num = ((item != null) ? item.progress : 0f) * 0.5f;
					AsyncOperation item2 = x.unload;
					return num + ((item2 != null) ? item2.progress : 0f) * 0.5f;
				}).Average();
				yield return null;
			}
			CrowdControlMod.preload = 2;
		}
	}
}
namespace CrowdControl.Harmony
{
	[HarmonyPatch(typeof(CameraController), "LateUpdate")]
	public static class CameraZoomPatch
	{
		private static bool zoomOverrideActive = false;

		private static float overrideOrthographicSize = 1f;

		public static void SetZoomOverride(bool active, float orthographicSize = 1f)
		{
			zoomOverrideActive = active;
			overrideOrthographicSize = orthographicSize;
		}

		public static void ClearZoomOverride()
		{
			zoomOverrideActive = false;
		}

		public static bool IsZoomOverrideActive()
		{
			return zoomOverrideActive;
		}

		private static void Postfix(CameraController __instance)
		{
			if (zoomOverrideActive && (Object)(object)__instance != (Object)null && (Object)(object)__instance.cam != (Object)null)
			{
				__instance.cam.orthographicSize = overrideOrthographicSize;
			}
		}
	}
	[HarmonyPatch(/*Could not decode attribute arguments.*/)]
	public static class NailDamagePatch
	{
		private static bool damageOverrideActive = false;

		private static float damageMultiplier = 1f;

		public static void SetDamageOverride(bool active, float multiplier = 1f)
		{
			damageOverrideActive = active;
			damageMultiplier = multiplier;
		}

		public static void ClearDamageOverride()
		{
			damageOverrideActive = false;
		}

		public static bool IsDamageOverrideActive()
		{
			return damageOverrideActive;
		}

		private static void Postfix(ref int __result)
		{
			if (damageOverrideActive)
			{
				__result = Mathf.RoundToInt((float)__result * damageMultiplier);
			}
		}
	}
	[HarmonyPatch(typeof(HeroController), "FixedUpdate")]
	public static class GravityPatch
	{
		private static bool gravityOverrideActive = false;

		private static float overrideGravityScale = 1f;

		public static void SetGravityOverride(bool active, float gravityScale = 1f)
		{
			gravityOverrideActive = active;
			overrideGravityScale = gravityScale;
		}

		public static void ClearGravityOverride()
		{
			gravityOverrideActive = false;
		}

		public static bool IsGravityOverrideActive()
		{
			return gravityOverrideActive;
		}

		private static void Postfix(HeroController __instance)
		{
			if (gravityOverrideActive && (Object)(object)__instance != (Object)null && (Object)(object)__instance.Body != (Object)null && !GameStateChecker.ShouldPauseEffects())
			{
				__instance.Body.gravityScale = overrideGravityScale;
			}
		}
	}
	[HarmonyPatch(typeof(HeroController), "ResetGravity")]
	public static class ResetGravityPatch
	{
		private static bool Prefix(HeroController __instance)
		{
			if (GravityPatch.IsGravityOverrideActive())
			{
				return false;
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(HeroController), "UpdateMoveInput")]
	public static class MoveInputInversionPatch
	{
		private static bool inversionActive;

		public static void SetInversionActive(bool active)
		{
			inversionActive = active;
		}

		private static void Postfix(HeroController __instance)
		{
			if (inversionActive)
			{
				__instance.move_input = 0f - __instance.move_input;
			}
		}
	}
	[HarmonyPatch(typeof(HeroController), "LookForInput")]
	public static class VerticalInputInversionPatch
	{
		private static bool inversionActive;

		public static void SetInversionActive(bool active)
		{
			inversionActive = active;
		}

		private static void Postfix(HeroController __instance)
		{
			if (inversionActive)
			{
				__instance.vertical_input = 0f - __instance.vertical_input;
			}
		}
	}
	[HarmonyPatch(typeof(GameManager), "EnterHero")]
	public static class PreloadPatch
	{
		private static void Prefix()
		{
			PrefabLoader.checkPreload();
		}
	}
	[HarmonyPatch(typeof(HeroController), "GetWalkSpeed")]
	public static class WalkSpeedPatch
	{
		private static bool speedOverrideActive = false;

		private static float walkSpeedMultiplier = 1f;

		private static float originalWalkSpeed = 0f;

		public static void SetSpeedOverride(bool active, float multiplier, float originalSpeed)
		{
			speedOverrideActive = active;
			walkSpeedMultiplier = multiplier;
			originalWalkSpeed = originalSpeed;
		}

		public static void ClearSpeedOverride()
		{
			speedOverrideActive = false;
		}

		private static void Postfix(ref float __result)
		{
			if (speedOverrideActive && !GameStateChecker.ShouldPauseEffects())
			{
				__result = originalWalkSpeed * walkSpeedMultiplier;
			}
		}
	}
	[HarmonyPatch(typeof(HeroController), "GetRunSpeed")]
	public static class RunSpeedPatch
	{
		private static bool speedOverrideActive = false;

		private static float runSpeedMultiplier = 1f;

		private static float originalRunSpeed = 0f;

		public static void SetSpeedOverride(bool active, float multiplier, float originalSpeed)
		{
			speedOverrideActive = active;
			runSpeedMultiplier = multiplier;
			originalRunSpeed = originalSpeed;
		}

		public static void ClearSpeedOverride()
		{
			speedOverrideActive = false;
		}

		private static void Postfix(ref float __result)
		{
			if (speedOverrideActive && !GameStateChecker.ShouldPauseEffects())
			{
				__result = originalRunSpeed * runSpeedMultiplier;
			}
		}
	}
	[HarmonyPatch(typeof(HeroController), "Dash")]
	public static class DashSpeedPatch
	{
		private static bool speedOverrideActive = false;

		private static float dashSpeedMultiplier = 1f;

		private static float originalDashSpeed = 0f;

		public static void SetSpeedOverride(bool active, float multiplier, float originalSpeed)
		{
			speedOverrideActive = active;
			dashSpeedMultiplier = multiplier;
			originalDashSpeed = originalSpeed;
		}

		public static void ClearSpeedOverride()
		{
			speedOverrideActive = false;
		}

		private static void Prefix(HeroController __instance)
		{
			if (speedOverrideActive && !GameStateChecker.ShouldPauseEffects())
			{
				__instance.DASH_SPEED = originalDashSpeed * dashSpeedMultiplier;
			}
		}

		private static void Postfix(HeroController __instance)
		{
			if (speedOverrideActive)
			{
				__instance.DASH_SPEED = originalDashSpeed;
			}
		}
	}
}
namespace CrowdControl.Delegates.Metadata
{
	[AttributeUsage(AttributeTargets.Method)]
	public class MetadataAttribute(params string[] ids) : Attribute()
	{
		public string[] IDs { get; } = ids;

		public MetadataAttribute(string ids)
			: this(new string[1] { ids })
		{
		}

		public MetadataAttribute([ParamCollection] IEnumerable<string> ids)
			: this(ids.ToArray())
		{
		}
	}
	public delegate DataResponse MetadataDelegate(CrowdControlMod mod);
	public static class MetadataDelegates
	{
		public static readonly string[] CommonMetadata = Array.Empty<string>();
	}
	public static class MetadataLoader
	{
		private const BindingFlags BINDING_FLAGS = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;

		public static readonly Dictionary<string, MetadataDelegate> Metadata;

		static MetadataLoader()
		{
			Metadata = new Dictionary<string, MetadataDelegate>();
			Type[] types = Assembly.GetExecutingAssembly().GetTypes();
			foreach (Type type in types)
			{
				try
				{
					MethodInfo[] methods = type.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
					foreach (MethodInfo methodInfo in methods)
					{
						try
						{
							foreach (MetadataAttribute customAttribute in methodInfo.GetCustomAttributes<MetadataAttribute>())
							{
								string[] iDs = customAttribute.IDs;
								foreach (string key in iDs)
								{
									try
									{
										Metadata[key] = (MetadataDelegate)Delegate.CreateDelegate(typeof(MetadataDelegate), methodInfo);
									}
									catch (Exception ex)
									{
										CrowdControlMod.Instance.Logger.LogError((object)ex);
									}
								}
							}
						}
						catch
						{
						}
					}
				}
				catch
				{
				}
			}
		}
	}
}
namespace CrowdControl.Delegates.Effects
{
	public abstract class Effect
	{
		public EffectAttribute EffectAttribute { get; }

		public bool IsTimed => EffectAttribute.DefaultDuration > 0.0;

		public CrowdControlMod Mod { get; }

		public NetworkClient Client { get; }

		protected Effect(CrowdControlMod mod, NetworkClient client)
		{
			Mod = mod;
			Client = client;
			EffectAttribute = GetType().GetCustomAttributes<EffectAttribute>(inherit: false).First();
		}

		public abstract EffectResponse Start(EffectRequest request);

		public virtual EffectResponse? Tick(EffectRequest request)
		{
			return null;
		}

		public virtual EffectResponse? Pause(EffectRequest request)
		{
			return EffectResponse.Paused(((SimpleJSONMessage)request).ID, (string)null);
		}

		public virtual EffectResponse? Resume(EffectRequest request)
		{
			return EffectResponse.Resumed(((SimpleJSONMessage)request).ID, (string)null);
		}

		public virtual EffectResponse? Stop(EffectRequest request)
		{
			return EffectResponse.Finished(((SimpleJSONMessage)request).ID, (string)null);
		}
	}
	[AttributeUsage(AttributeTargets.Class)]
	public class EffectAttribute(string[] ids, SITimeSpan defaultDuration, string[] conflicts) : Attribute()
	{
		public IReadOnlyList<string> IDs { get; } = ids;

		public SITimeSpan DefaultDuration { get; } = defaultDuration;

		public IReadOnlyList<string> Conflicts { get; } = conflicts;

		public EffectAttribute([ParamCollection] IEnumerable<string> ids)
			: this(ids.ToArray(), SITimeSpan.Zero, Array.Empty<string>())
		{
		}

		public EffectAttribute(params string[] ids)
			: this(ids.ToArray(), SITimeSpan.Zero, Array.Empty<string>())
		{
		}

		public EffectAttribute(string[] ids, float defaultDuration, string[] conflicts)
			: this(ids, (SITimeSpan)defaultDuration, conflicts)
		{
		}

		public EffectAttribute(string[] ids, float defaultDuration, string conflict)
			: this(ids, defaultDuration, new string[1] { conflict })
		{
		}

		public EffectAttribute(string id)
			: this(new string[1] { id }, SITimeSpan.Zero, Array.Empty<string>())
		{
		}

		public EffectAttribute(string id, float defaultDuration)
			: this(new string[1] { id }, defaultDuration, (!(SITimeSpan.Zero > 0.0)) ? Array.Empty<string>() : new string[1] { id })
		{
		}

		public EffectAttribute(string id, float defaultDuration, string conflict)
			: this(new string[1] { id }, defaultDuration, new string[1] { conflict })
		{
		}

		public EffectAttribute(string id, float defaultDuration, string[] conflicts)
			: this(new string[1] { id }, defaultDuration, conflicts)
		{
		}

		public EffectAttribute(string id, float defaultDuration, bool selfConflict)
			: this(new string[1] { id }, defaultDuration, (!selfConflict) ? Array.Empty<string>() : new string[1] { id })
		{
		}

		public EffectAttribute(string[] ids, float defaultDuration, bool selfConflict)
			: this(ids, defaultDuration, selfConflict ? ids : Array.Empty<string>())
		{
		}

		public EffectAttribute(string id, bool selfConflict)
			: this(new string[1] { id }, SITimeSpan.Zero, (!selfConflict) ? Array.Empty<string>() : new string[1] { id })
		{
		}

		public EffectAttribute(string[] ids, bool selfConflict)
			: this(ids, SITimeSpan.Zero, selfConflict ? ids : Array.Empty<string>())
		{
		}
	}
	public class EffectLoader
	{
		private const BindingFlags BINDING_FLAGS = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;

		public readonly Dictionary<string, Effect> Effects = new Dictionary<string, Effect>();

		public EffectLoader(CrowdControlMod mod, NetworkClient client)
		{
			foreach (Type item in from type in Assembly.GetExecutingAssembly().GetTypes()
				where type.IsSubclassOf(typeof(Effect))
				select type)
			{
				try
				{
					foreach (EffectAttribute customAttribute in item.GetCustomAttributes<EffectAttribute>())
					{
						foreach (string iD in customAttribute.IDs)
						{
							try
							{
								Effects[iD] = (Effect)Activator.CreateInstance(item, mod, client);
							}
							catch (Exception ex)
							{
								CrowdControlMod.Instance.Logger.LogError((object)ex);
							}
						}
					}
				}
				catch (Exception ex2)
				{
					CrowdControlMod.Instance.Logger.LogError((object)ex2);
				}
			}
		}
	}
	public class TimedEffectState
	{
		public enum EffectState
		{
			NotStarted,
			Running,
			Paused,
			Finished,
			Errored
		}

		public readonly EffectRequest Request;

		public readonly SITimeSpan Duration;

		public readonly Effect Effect;

		public readonly NetworkClient Client;

		public SITimeSpan TimeRemaining;

		private int m_stateLock;

		private static readonly IEnumerator EMPTY_ENUMERATOR = Enumerable.Empty<object>().GetEnumerator();

		public EffectState State { get; private set; }

		private bool TryGetLock()
		{
			return Interlocked.CompareExchange(ref m_stateLock, 1, 0) == 0;
		}

		private void ReleaseLock()
		{
			m_stateLock = 0;
		}

		public TimedEffectState(Effect effect, EffectRequest request, SITimeSpan duration)
		{
			Effect = effect;
			Client = effect.Client;
			Request = request;
			Duration = duration;
			TimeRemaining = duration;
		}

		public IEnumerator Start()
		{
			EffectResponse response = null;
			bool locked = false;
			try
			{
				while (true)
				{
					bool flag;
					locked = (flag = TryGetLock());
					if (flag)
					{
						break;
					}
					yield return null;
				}
				if (State == EffectState.NotStarted)
				{
					try
					{
						response = Effect.Start(Request);
						TimeRemaining = Duration;
						State = EffectState.Running;
						yield break;
					}
					catch (Exception ex)
					{
						response = EffectResponse.Failure(((SimpleJSONRequest)Request).id, (StandardErrors)1);
						CrowdControlMod.Instance.Logger.LogError((object)ex.Message);
						State = EffectState.Errored;
						yield break;
					}
				}
			}
			finally
			{
				TimedEffectState timedEffectState = this;
				if (locked)
				{
					timedEffectState.ReleaseLock();
					timedEffectState.Client.Send((SimpleJSONResponse?)(object)response);
				}
			}
		}

		public IEnumerator Pause()
		{
			EffectResponse response = null;
			bool locked = false;
			try
			{
				while (true)
				{
					bool flag;
					locked = (flag = TryGetLock());
					if (flag)
					{
						break;
					}
					yield return null;
				}
				if (State == EffectState.Running)
				{
					try
					{
						response = Effect.Pause(Request);
						State = EffectState.Paused;
						yield break;
					}
					catch (Exception ex)
					{
						response = EffectResponse.Failure(((SimpleJSONRequest)Request).id, (StandardErrors)1);
						CrowdControlMod.Instance.Logger.LogError((object)ex.Message);
						State = EffectState.Errored;
						yield break;
					}
				}
			}
			finally
			{
				TimedEffectState timedEffectState = this;
				if (locked)
				{
					timedEffectState.ReleaseLock();
					timedEffectState.Client.Send((SimpleJSONResponse?)(object)response);
				}
			}
		}

		public IEnumerator Resume()
		{
			EffectResponse response = null;
			bool locked = false;
			try
			{
				while (true)
				{
					bool flag;
					locked = (flag = TryGetLock());
					if (flag)
					{
						break;
					}
					yield return null;
				}
				if (State == EffectState.Paused)
				{
					try
					{
						response = Effect.Resume(Request);
						State = EffectState.Running;
						yield break;
					}
					catch (Exception ex)
					{
						response = EffectResponse.Failure(((SimpleJSONRequest)Request).id, (StandardErrors)1);
						CrowdControlMod.Instance.Logger.LogError((object)ex.Message);
						State = EffectState.Errored;
						yield break;
					}
				}
			}
			finally
			{
				TimedEffectState timedEffectState = this;
				if (locked)
				{
					timedEffectState.ReleaseLock();
					timedEffectState.Client.Send((SimpleJSONResponse?)(object)response);
				}
			}
		}

		public IEnumerator Stop()
		{
			EffectResponse response = null;
			bool locked = false;
			try
			{
				while (true)
				{
					bool flag;
					locked = (flag = TryGetLock());
					if (flag)
					{
						break;
					}
					yield return null;
				}
				if (State != EffectState.Finished)
				{
					try
					{
						response = Effect.Stop(Request) ?? EffectResponse.Finished(((SimpleJSONRequest)Request).id, (string)null);
						State = EffectState.Finished;
						yield break;
					}
					catch (Exception ex)
					{
						response = EffectResponse.Failure(((SimpleJSONRequest)Request).id, (StandardErrors)1);
						CrowdControlMod.Instance.Logger.LogError((object)ex.Message);
						State = EffectState.Errored;
						yield break;
					}
				}
			}
			finally
			{
				TimedEffectState timedEffectState = this;
				if (locked)
				{
					timedEffectState.ReleaseLock();
					timedEffectState.Client.Send((SimpleJSONResponse?)(object)response);
				}
			}
		}

		public IEnumerator Tick()
		{
			EffectResponse val = null;
			bool flag = false;
			try
			{
				if (!(flag = TryGetLock()))
				{
					return EMPTY_ENUMERATOR;
				}
				switch (State)
				{
				case EffectState.Running:
					if (GameStateChecker.ShouldPauseEffects())
					{
						return Pause();
					}
					try
					{
						if (TimeRemaining > 0.0)
						{
							Effect.Tick(Request);
							TimeRemaining -= (double)CrowdControlMod.DeltaTime;
						}
						else
						{
							val = Effect.Stop(Request) ?? EffectResponse.Finished(((SimpleJSONRequest)Request).id, (string)null);
							State = EffectState.Finished;
							TimeRemaining = SITimeSpan.Zero;
						}
					}
					catch (Exception ex)
					{
						val = EffectResponse.Failure(((SimpleJSONRequest)Request).id, (StandardErrors)1);
						CrowdControlMod.Instance.Logger.LogError((object)ex.Message);
						State = EffectState.Errored;
					}
					break;
				case EffectState.Paused:
					if (!GameStateChecker.ShouldPauseEffects())
					{
						return Resume();
					}
					break;
				}
				return EMPTY_ENUMERATOR;
			}
			finally
			{
				if (flag)
				{
					ReleaseLock();
					if (val != null)
					{
						Client.Send((SimpleJSONResponse?)(object)val);
					}
				}
			}
		}
	}
}
namespace CrowdControl.Delegates.Effects.Implementations
{
	[Effect("cameffect_upsidedown", 20f, true)]
	public class CameraFlip : Effect
	{
		private CameraController cameraController;

		private Camera mainCamera;

		private Vector3 originalControllerScale;

		private Vector3 originalCameraScale;

		private Quaternion originalCameraRotation;

		private bool m_flipped;

		public CameraFlip(CrowdControlMod mod, NetworkClient client)
			: base(mod, client)
		{
		}

		public override EffectResponse Start(EffectRequest request)
		{
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				cameraController = GameCameras.instance?.cameraController;
				mainCamera = GameCameras.instance?.mainCamera;
				if (cameraController == null || mainCamera == null)
				{
					return EffectResponse.Retry(((SimpleJSONMessage)request).ID, (string)null);
				}
				originalControllerScale = ((Component)cameraController).transform.localScale;
				originalCameraScale = ((Component)mainCamera).transform.localScale;
				originalCameraRotation = ((Component)mainCamera).transform.rotation;
				m_flipped = false;
				CrowdControlMod.ShowMsg(request.viewer, "<color=#FF6B6B>{viewer}</color> <color=#FF4500>flipped</color> <color=#FFFFFF>your</color> <color=#FFD93D>camera upside down</color>!");
				return EffectResponse.Success(((SimpleJSONMessage)request).ID, (string)null);
			}
			catch (Exception arg)
			{
				CrowdControlMod.LogDebug($"Camera effect error: {arg}");
				return EffectResponse.Retry(((SimpleJSONMessage)request).ID, (string)null);
			}
		}

		public override EffectResponse? Tick(EffectRequest request)
		{
			try
			{
				if (GameStateChecker.ShouldPauseEffects())
				{
					if (m_flipped)
					{
						RestoreCamera();
					}
					Pause(request);
				}
				else
				{
					FlipCamera();
				}
			}
			catch (Exception arg)
			{
				CrowdControlMod.LogDebug($"Camera effect tick error: {arg}");
			}
			return null;
		}

		public override EffectResponse? Stop(EffectRequest request)
		{
			try
			{
				RestoreCamera();
				CrowdControlMod.ShowMsg(request.viewer, "<color=#FFD93D>Normal camera</color> <color=#FFFFFF>was</color> <color=#32CD32>res